Algofox option strategy python
from flask import Flask, render_template, request ,url_for,redirect
from flask_wtf import FlaskForm
from wtforms import StringField, RadioField, DateField,SelectField,IntegerField,TimeField
from wtforms.validators import DataRequired,NumberRange
import Algofox
from Algofox import *
import json
from kite_trade import *
from datetime import datetime,timedelta
import time
import pandas as pd
import pandas_ta as ta
import threading
import time
enctoken = "TqEBToNCJM1UU++bjzoEXfsRTGYCg2x3LToWMICAYeFGyYcU38b0mvK3TWhgTSyOwwyv1ZvawbzciDYKQ0UnIFyzGRRcYd1tP+lCPwvuPq70NK2G88WaYw=="
kite = KiteApp(enctoken=enctoken)
CE_Contract_OHLC_filename=""
PE_Contract_OHLC_filename=""
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
print("Optimising Code")
class MyForm(FlaskForm):
start_time = TimeField('Start Time', validators=[DataRequired()])
end_time = TimeField('End Time', validators=[DataRequired()])
base_symbol = StringField('Base Symbol', validators=[DataRequired()])
expiry = DateField('Expiry', validators=[DataRequired()], format='%Y-%m-%d')
expiry_type = RadioField('Expiry Type', choices=[('monthly', 'Monthly'), ('weekly', 'Weekly')])
interval = SelectField('Interval',
choices=[('1Minute', '1 Minute'), ('5Minute', '5 Minutes'), ('15Minute', '15 Minutes'),
('30Minute', '30 Minutes'), ('1hour', '1 Hour')])
lot_size = IntegerField('Lot Size', validators=[DataRequired(), NumberRange(min=1)])
lots=0
start_time=datetime.now().time()
end_time=datetime.now().time()
@app.route('/', methods=['GET', 'POST'])
def home():
global start_time,end_time,week_or_exp
form = MyForm()
if form.validate_on_submit():
base_symbol = form.base_symbol.data
expiry = form.expiry.data.strftime('%Y-%m-%d')
week_or_exp = expiry
expiry_type = form.expiry_type.data
interval = form.interval.data
lot_size = request.args.get('lot_size')
lots=lot_size
start_time = form.start_time.data
end_time = form.end_time.data
print(expiry_type)
return redirect(url_for('process_form', base_symbol=base_symbol, expiry=expiry, expiry_type=expiry_type, interval=interval))
return render_template('home.html', form=form)
def is_within_time_range(start_time, end_time):
current_time = datetime.now().time()
if start_time <= current_time <= end_time:
return True
return False
weekly_exp=None
Symbol=None
expiery=None
trading_tf=""
expiry_type=""
week_or_exp=None
@app.route('/process', methods=['GET'])
def process_form():
global Symbol,expiery,trading_tf,expiry_type
start_time = request.args.get('start_time')
end_time = request.args.get('end_time')
base_symbol = request.args.get('base_symbol')
expiry_type = request.args.get('expiry_type')
Symbol = base_symbol
expiry = request.args.get('expiry')
date_str = expiry
date_parts = date_str.split("-")
year = date_parts[0][-2:]
month = date_parts[1].lstrip("0")
day = date_parts[2]
converted_date = int(year + month + day)
weekly_exp = converted_date
print("checking")
print(weekly_exp)
expiery = datetime.strptime(expiry, '%Y-%m-%d')
expiery = expiery.strftime('%d%b%Y')
day = expiery[-2:]
month = expiery[2:5].upper()
expiery = day + month
interval = request.args.get('interval')
if interval == "1Minute":
trading_tf="minute"
if interval == "5Minute":
trading_tf="5minute"
if interval == "15Minute":
trading_tf="15minute"
if interval == "30Minute":
trading_tf="30minute"
if interval == "1hour":
trading_tf="60minute"
# Process the form data here as needed
return redirect(url_for('create_ce_pe_contract', symbol=Symbol, expiry=expiery,expiry_type=expiry_type,weekly_exp=weekly_exp))
def custom_round(price):
last_two_digits = price % 100
if last_two_digits < 25:
rounded_price = (price // 100) * 100
elif last_two_digits < 75:
rounded_price = (price // 100) * 100 + 50
else:
rounded_price = (price // 100 + 1) * 100
return rounded_price
ce_ins_token=0
pe_ins_token=0
CE_Contract=None
PE_Contract=None
strike=0
@app.route('/create_ce_pe_contract')
def create_ce_pe_contract():
symbol = request.args.get('symbol')
expiry = request.args.get('expiry')
weekly_exp= request.args.get('weekly_exp')
nifty_ltp = kite.ltp(["NSE:NIFTY 50", "NSE:NIFTY BANK"])['NSE:NIFTY 50']['last_price']
rounded_price1 = custom_round(nifty_ltp)
strike=rounded_price1
global CE_Contract,PE_Contract,expiry_type
if expiry_type=="monthly" :
CE_Contract = symbol + expiry + str(int(rounded_price1)) + "CE"
PE_Contract = symbol + expiry + str(int(rounded_price1)) + "PE"
if expiry_type=="weekly" :
CE_Contract = symbol + weekly_exp + str(int(rounded_price1)) + "CE"
PE_Contract = symbol + weekly_exp + str(int(rounded_price1)) + "PE"
value = kite.instruments("NFO")
global ce_ins_token,pe_ins_token
for i in range(len(value)):
if CE_Contract == value[i]['tradingsymbol']:
ce_ins_token = value[i]['instrument_token']
if PE_Contract == value[i]['tradingsymbol']:
pe_ins_token = value[i]['instrument_token']
return redirect(url_for('calculate_historical_data', ce_contract=CE_Contract, pe_contract=PE_Contract,
ce_ins_token=ce_ins_token, pe_ins_token=pe_ins_token))
@app.route('/calculate_historical_data')
def calculate_historical_data():
global CE_Contract,PE_Contract,ce_ins_token,pe_ins_token,trading_tf
global CE_Contract_OHLC_filename, PE_Contract_OHLC_filename
ce_contract =CE_Contract
pe_contract = PE_Contract
ce_ins_token = ce_ins_token
pe_ins_token = pe_ins_token
print("Creating")
# ce historical
instrument_token = ce_ins_token
from_datetime = datetime.now() - timedelta(days=1) # From last & days
to_datetime = datetime.now()
interval = trading_tf
# print(kite.historical_data(instrument_token, from_datetime, to_datetime, interval, continuous=False, oi=False))
historical_data = kite.historical_data(instrument_token, from_datetime, to_datetime, interval, continuous=False,
oi=False)
CE_Contract_OHLC = pd.DataFrame()
for i in range(len(historical_data)):
dataobj = historical_data[i]['date']
reliance = dataobj.strftime('%Y-%m-%d %H:%M')
row_to_append = {'open': float(historical_data[i]['open']),
'high': float(historical_data[i]['high']),
'low': float(historical_data[i]['low']),
'close': float(historical_data[i]['close']),
'Timestamp': reliance}
CE_Contract_OHLC = pd.concat([CE_Contract_OHLC, pd.DataFrame([row_to_append])], ignore_index=True)
CE_Contract_OHLC_filename = ce_contract + ".csv"
CE_Contract_OHLC.to_csv(CE_Contract_OHLC_filename, index=False)
# pe historical data
instrument_token = pe_ins_token
from_datetime = datetime.now() - timedelta(days=1) # From last & days
to_datetime = datetime.now()
interval = trading_tf
# print(kite.historical_data(instrument_token, from_datetime, to_datetime, interval, continuous=False, oi=False))
historical_data = kite.historical_data(instrument_token, from_datetime, to_datetime, interval, continuous=False,
oi=False)
PE_Contract_OHLC = pd.DataFrame()
for i in range(len(historical_data)):
dataobj = historical_data[i]['date']
reliance = dataobj.strftime('%Y-%m-%d %H:%M')
row_to_append = {'open': float(historical_data[i]['open']),
'high': float(historical_data[i]['high']),
'low': float(historical_data[i]['low']),
'close': float(historical_data[i]['close']),
'Timestamp': reliance}
PE_Contract_OHLC = pd.concat([PE_Contract_OHLC, pd.DataFrame([row_to_append])], ignore_index=True)
PE_Contract_OHLC_filename = pe_contract + ".csv"
PE_Contract_OHLC.to_csv(PE_Contract_OHLC_filename, index=False)
df = pd.read_csv(CE_Contract_OHLC_filename)
df["Supertrend_CE"] = ta.supertrend(high=df['high'], low=df['low'], close=df['close'], length=5, multiplier=0.5)[
"SUPERT_5_0.5"]
df.to_csv(CE_Contract_OHLC_filename)
dfF = pd.read_csv(PE_Contract_OHLC_filename)
dfF["Supertrend_PE"] = \
ta.supertrend(high=dfF['high'], low=dfF['low'], close=dfF['close'], length=5, multiplier=0.5)["SUPERT_5_0.5"]
dfF.to_csv(PE_Contract_OHLC_filename)
current_time = time.localtime()
next_run_time = time.mktime((current_time.tm_year, current_time.tm_mon, current_time.tm_mday,
current_time.tm_hour, current_time.tm_min + 5, 55,
current_time.tm_wday, current_time.tm_yday, current_time.tm_isdst))
time_diff = next_run_time - time.mktime(current_time)
threading.Timer(time_diff, calculate_historical_data).start()
monitor_trade_signals()
return f"CE Contract: {ce_contract}<br>PE Contract: {pe_contract}<br>CE Ins Token: {ce_ins_token}<br>PE Ins Token: {pe_ins_token}"
def refresh_cepe():
global Symbol,expiery,weekly_exp,week_or_exp
symbol = Symbol
expiry = expiery
nifty_ltp = kite.ltp(["NSE:NIFTY 50", "NSE:NIFTY BANK"])['NSE:NIFTY 50']['last_price']
rounded_price1 = custom_round(nifty_ltp)
strike = rounded_price1
print(rounded_price1)
global CE_Contract, PE_Contract
if expiry_type == "monthly":
CE_Contract = symbol + expiry + str(int(rounded_price1)) + "CE"
PE_Contract = symbol + expiry + str(int(rounded_price1)) + "PE"
if expiry_type == "weekly":
CE_Contract = symbol + weekly_exp + str(int(rounded_price1)) + "CE"
PE_Contract = symbol + weekly_exp + str(int(rounded_price1)) + "PE"
print(CE_Contract)
print(PE_Contract)
value = kite.instruments("NFO")
global ce_ins_token, pe_ins_token
for i in range(len(value)):
if CE_Contract == value[i]['tradingsymbol']:
ce_ins_token = value[i]['instrument_token']
if PE_Contract == value[i]['tradingsymbol']:
pe_ins_token = value[i]['instrument_token']
print(ce_ins_token)
print(pe_ins_token)
def refresh_historicaldata():
global CE_Contract, PE_Contract, ce_ins_token, pe_ins_token
global CE_Contract_OHLC_filename, PE_Contract_OHLC_filename
ce_contract = CE_Contract
pe_contract = PE_Contract
ce_ins_token = ce_ins_token
pe_ins_token = pe_ins_token
print(ce_contract)
print(pe_contract)
print(ce_ins_token)
print(pe_ins_token)
# ce historical
instrument_token = ce_ins_token
from_datetime = datetime.now() - timedelta(days=1) # From last & days
to_datetime = datetime.now()
interval = trading_tf
# print(kite.historical_data(instrument_token, from_datetime, to_datetime, interval, continuous=False, oi=False))
historical_data = kite.historical_data(instrument_token, from_datetime, to_datetime, interval, continuous=False,
oi=False)
CE_Contract_OHLC = pd.DataFrame()
for i in range(len(historical_data)):
dataobj = historical_data[i]['date']
reliance = dataobj.strftime('%Y-%m-%d %H:%M')
row_to_append = {'open': float(historical_data[i]['open']),
'high': float(historical_data[i]['high']),
'low': float(historical_data[i]['low']),
'close': float(historical_data[i]['close']),
'Timestamp': reliance}
CE_Contract_OHLC = pd.concat([CE_Contract_OHLC, pd.DataFrame([row_to_append])], ignore_index=True)
CE_Contract_OHLC_filename = ce_contract + ".csv"
CE_Contract_OHLC.to_csv(CE_Contract_OHLC_filename, index=False)
# pe historical data
instrument_token = pe_ins_token
from_datetime = datetime.now() - timedelta(days=1) # From last & days
to_datetime = datetime.now()
interval = trading_tf
# print(kite.historical_data(instrument_token, from_datetime, to_datetime, interval, continuous=False, oi=False))
historical_data = kite.historical_data(instrument_token, from_datetime, to_datetime, interval, continuous=False,
oi=False)
PE_Contract_OHLC = pd.DataFrame()
for i in range(len(historical_data)):
dataobj = historical_data[i]['date']
reliance = dataobj.strftime('%Y-%m-%d %H:%M')
row_to_append = {'open': float(historical_data[i]['open']),
'high': float(historical_data[i]['high']),
'low': float(historical_data[i]['low']),
'close': float(historical_data[i]['close']),
'Timestamp': reliance}
PE_Contract_OHLC = pd.concat([PE_Contract_OHLC, pd.DataFrame([row_to_append])], ignore_index=True)
PE_Contract_OHLC_filename = pe_contract + ".csv"
PE_Contract_OHLC.to_csv(PE_Contract_OHLC_filename, index=False)
df = pd.read_csv(CE_Contract_OHLC_filename)
df["Supertrend_CE"] = ta.supertrend(high=df['high'], low=df['low'], close=df['close'], length=5, multiplier=0.5)[
"SUPERT_5_0.5"]
df.to_csv(CE_Contract_OHLC_filename)
dfF = pd.read_csv(PE_Contract_OHLC_filename)
dfF["Supertrend_PE"] = \
ta.supertrend(high=dfF['high'], low=dfF['low'], close=dfF['close'], length=5, multiplier=0.5)["SUPERT_5_0.5"]
dfF.to_csv(PE_Contract_OHLC_filename)
current_time = time.localtime()
next_run_time = time.mktime((current_time.tm_year, current_time.tm_mon, current_time.tm_mday,
current_time.tm_hour, current_time.tm_min + 5, 55,
current_time.tm_wday, current_time.tm_yday, current_time.tm_isdst))
time_diff = next_run_time - time.mktime(current_time)
threading.Timer(time_diff, calculate_historical_data).start()
monitor_trade_signals()
return f"CE Contract: {ce_contract}<br>PE Contract: {pe_contract}<br>CE Ins Token: {ce_ins_token}<br>PE Ins Token: {pe_ins_token}<br> expiry_type:{expiry_type}"
SELL_CE=False
SELL_PE= False
position=None
def monitor_trade_signals():
print("RunningStrategy")
global CE_Contract_OHLC_filename, PE_Contract_OHLC_filename,position,strike,lots,expiry_type,week_or_exp
# ce
df=pd.read_csv(CE_Contract_OHLC_filename)
last_1_row=df.iloc[-2]
last_3rd_row = df.iloc[-4]
last_2nd_row = df.iloc[-3]
close_3rd_last = last_3rd_row['close']
supertrend_ce_3rd_last = last_3rd_row['Supertrend_CE']
close_2nd_last = last_2nd_row['close']
supertrend_ce_2nd_last = last_2nd_row['Supertrend_CE']
close_1st_last= last_1_row['close']
supertrend_ce_1st_last= last_1_row['Supertrend_CE']
# pe
gf=pd.read_csv(PE_Contract_OHLC_filename)
last_1_row_pe = gf.iloc[-2]
last_3rd_row_pe = gf.iloc[-4]
last_2nd_row_pe = gf.iloc[-3]
close_3rd_last_pe = last_3rd_row_pe['close']
supertrend_ce_3rd_last_pe = last_3rd_row_pe['Supertrend_PE']
close_2nd_last_pe = last_2nd_row_pe['close']
supertrend_ce_2nd_last_pe = last_2nd_row_pe['Supertrend_PE']
close_1st_last_pe = last_1_row_pe['close']
supertrend_ce_1st_last_pe = last_1_row_pe['Supertrend_PE']
global SELL_PE,SELL_CE
nifty_ltp = kite.ltp(["NSE:NIFTY 50", "NSE:NIFTY BANK"])['NSE:NIFTY 50']['last_price']
rounded_price1 = custom_round(nifty_ltp)
if(close_1st_last<supertrend_ce_1st_last and SELL_CE==False and is_within_time_range(start_time, end_time)) :
position=1
print("Sell position call")
SELL_CE=True
if expiry_type == "monthly":
date_str = week_or_exp
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
formatted_date = date_obj.strftime("%d%b%Y").upper()
tradesym=Symbol+"|"+formatted_date+"|"+str(int(rounded_price1))+"|"+"CE"
Algofox.Short_order_algofox(tradesym, lots, )
if expiry_type == "weekly":
date_str = week_or_exp
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
formatted_date = date_obj.strftime("%d%b%Y").upper()
tradesym=Symbol+"|"+formatted_date+"|"+str(int(rounded_price1))+"|"+"CE"
Algofox.Short_order_algofox(tradesym, lots, )
if (close_1st_last_pe < supertrend_ce_1st_last_pe and SELL_PE== False and is_within_time_range(start_time, end_time)):
position = 1
print("Sell position put")
SELL_PE=True
if expiry_type == "monthly":
date_str = week_or_exp
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
formatted_date = date_obj.strftime("%d%b%Y").upper()
tradesym = Symbol + "|" + formatted_date + "|" + str(int(rounded_price1)) + "|" + "CE"
Algofox.Short_order_algofox(tradesym, lots, )
if expiry_type == "weekly":
date_str = week_or_exp
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
formatted_date = date_obj.strftime("%d%b%Y").upper()
tradesym = Symbol + "|" + formatted_date + "|" + str(int(rounded_price1)) + "|" + "CE"
Algofox.Short_order_algofox(tradesym, lots, )
# call exit
if(close_3rd_last<=supertrend_ce_3rd_last and close_2nd_last>supertrend_ce_2nd_last and SELL_CE==True and is_within_time_range(start_time, end_time)):
position=0
print("Exit Sell position call")
SELL_CE=False
if expiry_type == "monthly":
date_str = week_or_exp
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
formatted_date = date_obj.strftime("%d%b%Y").upper()
tradesym = Symbol + "|" + formatted_date + "|" + str(int(rounded_price1)) + "|" + "CE"
Algofox.Short_order_algofox(tradesym, lots, )
if expiry_type == "weekly":
date_str = week_or_exp
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
formatted_date = date_obj.strftime("%d%b%Y").upper()
tradesym = Symbol + "|" + formatted_date + "|" + str(int(rounded_price1)) + "|" + "CE"
Algofox.Short_order_algofox(tradesym, lots, )
if (close_3rd_last_pe <= supertrend_ce_3rd_last_pe and close_2nd_last_pe > supertrend_ce_2nd_last_pe and SELL_PE == True and is_within_time_range(start_time, end_time)):
position = 0
print("Exit Sell position Put")
SELL_PE = False
if expiry_type == "monthly":
date_str = week_or_exp
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
formatted_date = date_obj.strftime("%d%b%Y").upper()
tradesym = Symbol + "|" + formatted_date + "|" + str(int(rounded_price1)) + "|" + "CE"
Algofox.Short_order_algofox(tradesym, lots, )
if expiry_type == "weekly":
date_str = week_or_exp
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
formatted_date = date_obj.strftime("%d%b%Y").upper()
tradesym = Symbol + "|" + formatted_date + "|" + str(int(rounded_price1)) + "|" + "CE"
Algofox.Short_order_algofox(tradesym, lots, )
if(SELL_PE == False and SELL_CE==False and position==0 and is_within_time_range(start_time, end_time)):
print("=====Refreshing Call Put Data =======")
refresh_cepe()
refresh_historicaldata()
if __name__ == '__main__':
app.run(debug=True)
Comments
Post a Comment