How to create Option Strategy Builder for free in python?

 Option Strategy Builder

import tkinter as tk

from tkinter import ttk

from fyers_api import fyersModel

from fyers_api import accessToken

import threading

root=tk.Tk()

style=ttk.Style()

style.theme_use('winnative')

i=1


allStrikes=[]

def optionStrikes(evt):

    global slider

    slider.destroy()

    indexType=(evt["text"])

    Lb1.delete(0,"end")

    if(indexType=="NIFTY 50"):

        price = {"symbols":"NSE:NIFTY50-INDEX"}

        ltp=(fyers.quotes(price)["d"][0]["v"]["lp"])

        value=int(ltp)

        spot.delete(0,"end")

        spot.insert(0,value)

        value=value-value%100

        price=value-1000

        start=0

        while(start<40):

            Lb1.insert(start, price)

            price+=50

            start+=1

        slider = tk.Scale(

        frame3,

        from_=value-1000,

        to=value+1000,tickinterval=200,

        orient='horizontal',command=all_profits  

        )

        slider.set(ltp)  

        slider.pack(fill='x',expand=True)

    else:

        price = {"symbols":"NSE:NIFTYBANK-INDEX"}

        ltp=(fyers.quotes(price)["d"][0]["v"]["lp"])

        value=int(ltp)

        spot.delete(0,"end")

        spot.insert(0,value)

        value=value-value%100

        price=value-2000

        start=0

        while(start<40):

            Lb1.insert(start, price)

            price+=100

            start+=1

        slider = tk.Scale(

        frame3,

        from_=value-2000,

        to=value+2000,tickinterval=400,

        orient='horizontal',command=all_profits  

        )

        slider.set(ltp)  

        slider.pack(fill='x',expand=True)    

def addStrategy():

    

    global i

    tradeIndex="NIFTY"

    tradeType="CE"

    orderType="BUY"

    qty=int(quantity.get())

    

    if(index.get()==2):

        tradeIndex="BANKNIFTY"

    if(cepe.get()==2):

        tradeType="PE"    

    if(buySell.get()==2):

        orderType="SELL" 

    f=open("E:/tools/OPTION/option.txt")

    strike=f.read()

    strike=tradeIndex+strike[5:10]+str(Lb1.get("active"))+tradeType

    

    price = {"symbols":"NSE:"+strike}

    value=fyers.quotes(price)["d"][0]["v"]["lp"]

    

    e1=ttk.Entry(frame2)

    e1.grid(row=i,column=0)

    e1.insert(0,strike)

    allStrikes.append(e1)

    e1=ttk.Entry(frame2)

    e1.grid(row=i,column=1)

    e1.insert(0,orderType)

    allStrikes.append(e1)

    e1=ttk.Entry(frame2)

    e1.grid(row=i,column=2)

    e1.insert(0,qty)

    allStrikes.append(e1)

    e1=ttk.Entry(frame2)

    e1.grid(row=i,column=3)

    e1.insert(0,value)

    allStrikes.append(e1)

    i+=1

    all_profits(value)

    t1=threading.Thread(target=max_profits)

    t1.start()  

def connect_fyers():

    global fyers

    session=accessToken.SessionModel(client_id="App Id",

    secret_key="Secret Id",redirect_uri="https://trade.fyers.in/", 

    response_type="code", grant_type="authorization_code",

    state="abcdefg",scope="",nonce="")

    response = session.generate_authcode()

#https://api.fyers.in/api/v2/generate-authcode?client_id=App Id&redirect_uri=https://trade.fyers.in/&response_type=code&state=sample_state&nonce=sample_nonce  

    auth_code=sessionVar.get()

    top.destroy()

    session.set_token(auth_code)

    

    response = session.generate_token()

    access_token = response["access_token"]

    fyers = fyersModel.FyersModel(client_id="App Id", token=access_token,log_path="E:/tools")

    profile=fyers.get_profile()

    print(profile["data"]["name"]) 

    indexValue()

def indexValue():

    price = {"symbols":"NSE:NIFTY50-INDEX"}

    value=fyers.quotes(price)["d"][0]["v"]["lp"]

    spot.delete(0,"end")

    spot.insert(0,value)

    slider.set(value)

def all_profits(evt):

    

    length = len(allStrikes)/4

    start=0

    value=float(slider.get())

    profit=0

    while(start<length):

        profit+=int(allStrikes[(start*4)+2].get())*profits(allStrikes[start*4].get(),allStrikes[(start*4)+1].get(),allStrikes[(start*4)+3].get(),value)

        start+=1

    pnl.delete(0,"end")

    pnl.insert(0,profit)

def profits(name,orderType,premium,nifty):

    

    strike=int(name[10:15])

    if(name.startswith("BANK")):

        strike=int(name[14:19])

    if(name.endswith("CE")):

        if(orderType=="BUY"):

            profit=float(nifty)-(strike+float(premium))

            if(-(profit)>float(premium)):

                profit=-(float(premium))

            return (profit)

        elif(orderType=="SELL"): 

            profit=(strike+float(premium))-float(nifty)

            if(profit>float(premium)):

                profit=float(premium)

            return (profit)

    elif(name.endswith("PE")):   

        if(orderType=="BUY"):

            profit=(strike-float(premium))-float(nifty)

            if(-(profit)>float(premium)):

                profit=-(float(premium))

            return (profit)

        elif(orderType=="SELL"): 

            profit=float(nifty)-(strike-float(premium))

            if(profit>float(premium)):

                profit=float(premium)

            return (profit)

def max_profits():

    

    value=int(spot.get())

    length = len(allStrikes)/4

    start=0

    value=float(slider.get())

    print(slider.get())

    profit=0

    j=0

    buys=0

    sells=0

    maxProf=""

    maxLos=""

    while(start<length):

        if(allStrikes[(start*4)+1].get()=="BUY"):

            buys+=1

        elif(allStrikes[(start*4)+1].get()=="SELL"):

            sells+=1 

        start+=1    

    if(buys>sells):

        maxProf="UnLimited"

    elif(sells>buys):

        maxLos="UnLimited"

    start=0  

    value-=2000

    end=value+4000

    prevProfit=0

    prevLoss=0

    breakStart=0

    breakEnd=0

    profitIndex=0

    lossIndex=0

    breaks=[]

    breakValue=0

    while(value<end):

        

        while(start<length):

            profit+=int(allStrikes[(start*4)+2].get())*profits(allStrikes[start*4].get(),allStrikes[(start*4)+1].get(),allStrikes[(start*4)+3].get(),value)

            start+=1

            #print(profit) 

        if((breakValue==0)and(len(breaks)==0)):

            breakValue=profit

        if((breakValue>0)and(profit<=0)):

            breakValue=profit

            breaks.append(value)

        elif((breakValue<0)and(profit>=0)):

            breakValue=profit

            breaks.append(value)

        if(profit>prevProfit):

            prevProfit=profit

            profitIndex=value

        if(profit<prevLoss):

            prevLoss=profit    

            lossIndex=value  

        profit=0

        start=0 

        value+=1

    pnl.delete(0,"end")

    pnl.insert(0,"0")

    breakEven.delete(0,"end")

    breakEven.insert(0,breaks)

    if(maxProf=="UnLimited"):

        maxProfit.delete(0,"end")

        maxProfit.insert(0,"UnLimited")

    else:

        maxProfit.delete(0,"end")

        maxProfit.insert(0,prevProfit)

    if(maxLos=="UnLimited"):

        maxLoss.delete(0,"end")

        maxLoss.insert(0,"UnLimited")

    else:

        maxLoss.delete(0,"end")

        maxLoss.insert(0,prevLoss)

def sessionPop():

    global top

    top=tk.Toplevel(root)

    global sessionVar

    sessionVar=ttk.Entry(top)

    sessionVar.grid(row=0,column=0)

    ttk.Button(top,text="SUBMIT",command=connect_fyers).grid(row=0,column=1) 

def clearWidgets():

    for row in allStrikes:

        row.destroy()

    allStrikes.clear()    

#connect_fyers()

def scheduleOrder():

    length = len(allStrikes)/4

    start=0

    if(positionType.get()==1):

        posType="INTRADAY"

    else:

        posType="MARGIN"    

    

    while(start<length):

        limitPrice=0

        if(mkorlmt.get()==1):

            limitPrice=float(allStrikes[(start*4)+3].get())

        if(allStrikes[(start*4)+1].get()=="BUY"):

            placeOrder(allStrikes[(start*4)].get(),int(allStrikes[(start*4)+2].get()),mkorlmt.get(),1,posType,limitPrice)

            

            #fyers.place_order(data)

        start+=1    

    start=0

    while(start<length):

        limitPrice=0

        if(mkorlmt.get()==1):

            limitPrice=float(allStrikes[(start*4)+3].get())

        if(allStrikes[(start*4)+1].get()=="SELL"):

            placeOrder(allStrikes[(start*4)].get(),int(allStrikes[(start*4)+2].get()),mkorlmt.get(),-1,posType,limitPrice)

        start+=1 

def exitSchedular():

    length = len(allStrikes)/4

    start=0

    if(positionType.get()==1):

        posType="INTRADAY"

    else:

        posType="MARGIN"    

    

    while(start<length):

        limitPrice=0

        if(mkorlmt.get()==1):

            limitPrice=float(allStrikes[(start*4)+3].get())

        if(allStrikes[(start*4)+1].get()=="SELL"):

            placeOrder(allStrikes[(start*4)].get(),int(allStrikes[(start*4)+2].get()),mkorlmt.get(),1,posType,limitPrice)

            

            #fyers.place_order(data)

        start+=1    

    start=0

    while(start<length):

        limitPrice=0

        if(mkorlmt.get()==1):

            limitPrice=float(allStrikes[(start*4)+3].get())

        if(allStrikes[(start*4)+1].get()=="BUY"):

            placeOrder(allStrikes[(start*4)].get(),int(allStrikes[(start*4)+2].get()),mkorlmt.get(),-1,posType,limitPrice)

        start+=1         

def placeOrder(name,qnty,lmt,bs,posType,limitPrice):

    data = {

      "symbol":"NSE:"+name,

      "qty":qnty,

      "type":lmt,

      "side":bs,

      "productType":posType,

      "limitPrice":limitPrice,

      "stopPrice":0,

      "validity":"DAY",

      "disclosedQty":0,

      "offlineOrder":"False",

      "stopLoss":0,

      "takeProfit":0

    }

    fyers.place_order(data)

    print(data)

setFrame=ttk.Frame(root)

setFrame.pack(fill='both',expand=True)

ttk.Label(setFrame,text="STRATEGY BUILDER").grid(row=0,column=0)

ttk.Button(setFrame,text="SESSION",command=sessionPop).grid(row=0,column=1)

frame1=ttk.Frame(root)

frame1.pack(fill='both',expand=True)

strikeFrame1=ttk.Frame(frame1)

strikeFrame1.pack(side="left",fill="both",expand=True)

Lb1 = tk.Listbox(strikeFrame1,width=30)

Lb1.pack()

strikeFrame2=ttk.Frame(frame1)

strikeFrame2.pack(side="left",fill="both",expand=True)

cepe = tk.IntVar()  

R1 = ttk.Radiobutton(strikeFrame2,width=20, text="CE", variable=cepe,value=1)

R1.grid(row = 1, column = 0)

R2 = ttk.Radiobutton(strikeFrame2,width=20, text="PE", variable=cepe,value=2)

R2.grid(row = 1, column = 1)

index = tk.IntVar()  

R1 = ttk.Radiobutton(strikeFrame2,width=20, text="NIFTY 50", variable=index,value=1,command=lambda:optionStrikes(R1))

R1.grid(row = 0, column = 0)

R2 = ttk.Radiobutton(strikeFrame2,width=20, text="NIFTY BANK", variable=index,value=2,command=lambda:optionStrikes(R2))

R2.grid(row = 0, column = 1)

buySell = tk.IntVar()  

R3 = ttk.Radiobutton(strikeFrame2,width=20, text="BUY", variable=buySell,value=1)

R3.grid(row = 2, column = 0)

R4 = ttk.Radiobutton(strikeFrame2,width=20, text="SELL", variable=buySell,value=2)

R4.grid(row = 2, column = 1)


ttk.Label(strikeFrame2,text="QUANTITY",width=20).grid(row=3,column=0)

quantity=ttk.Entry(strikeFrame2)

quantity.grid(row=3,column=1)

ttk.Button(strikeFrame2,text="ADD TO STRATEGY",command=addStrategy).grid(row=4,column=1)

ttk.Label(strikeFrame2,text="NIFTY SPOT",width=20).grid(row=5,column=0)

spot=ttk.Entry(strikeFrame2)

spot.grid(row=5,column=1)

frame2=ttk.Frame(root)

frame2.pack(fill='both',expand=True)


ttk.Label(frame2,text="NAME",width=20).grid(row=0,column=0)

ttk.Label(frame2,text="TYPE",width=20).grid(row=0,column=1)

ttk.Label(frame2,text="QUANTITY",width=20).grid(row=0,column=2)

ttk.Label(frame2,text="PRICE",width=20).grid(row=0,column=3)

frame3=ttk.Frame(root)

frame3.pack(fill='both',expand=True)

slider = tk.Scale(

    frame3,

    from_=15000,

    to=17000,tickinterval=200,

    orient='horizontal',command=all_profits  

)

slider.set(17000)

slider.pack(fill='x',expand=True)

frame4=ttk.Frame(root)

frame4.pack(fill='both',expand=True)

ttk.Label(frame4,text="BREAK EVEN",width=20).grid(row=0,column=0)

breakEven=ttk.Entry(frame4)

breakEven.grid(row=0,column=1)

ttk.Label(frame4,text="PNL",width=20).grid(row=0,column=2)

pnl=ttk.Entry(frame4)

pnl.grid(row=0,column=3)

ttk.Label(frame4,text="MAX LOSS",width=20).grid(row=1,column=0)

maxLoss=ttk.Entry(frame4)

maxLoss.grid(row=1,column=1)

ttk.Label(frame4,text="MAX PROFIT",width=20).grid(row=1,column=2)

maxProfit=ttk.Entry(frame4)

maxProfit.grid(row=1,column=3)

positionType = tk.IntVar()  

R5 = ttk.Radiobutton(frame4,width=20, text="INTRADAY", variable=positionType,value=1)

R5.grid(row = 2, column = 0)

R6 = ttk.Radiobutton(frame4,width=20, text="MARGIN", variable=positionType,value=2)

R6.grid(row = 2, column = 1)

mkorlmt = tk.IntVar()  

R7 = ttk.Radiobutton(frame4,width=20, text="MARKET", variable=mkorlmt,value=2)

R7.grid(row = 2, column = 2)

R8 = ttk.Radiobutton(frame4,width=20, text="LIMIT", variable=mkorlmt,value=1)

R8.grid(row = 2, column = 3)

ttk.Button(frame4,text="PLACE ORDER",command=scheduleOrder).grid(row = 3, column = 3)

ttk.Button(frame4,text="EXIT ORDER",command=exitSchedular).grid(row = 3, column = 2)

ttk.Button(frame4,text="RESET ALL",command=clearWidgets).grid(row = 3, column = 1)

root.mainloop()




Comments

  1. Hi,
    Excellent work.

    How to exit from one leg and riding the other one till to full profit ?

    A radio button to select the leg and exit option would be helpfull.

    Thanks,

    Magendran.N

    ReplyDelete

Post a Comment

Popular posts from this blog

Create Option Chain using PYTHON.

How to Place Order in Zerodha using Python

How to place order in zerodha when RSI crosses below 30? Algo Trading Python