├── finshoonya ├── __init__.py └── finshoonya.py ├── setup.py ├── README.md ├── finvasia.txt ├── example └── fifteen_min.py └── LICENSE /finshoonya/__init__.py: -------------------------------------------------------------------------------- 1 | from .finshoonya import shoonya 2 | __all__=[shoonya] 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name = 'finshoonya', 8 | packages=setuptools.find_packages(), 9 | version = '0.2', 10 | include_package_data=True, 11 | description = 'finvasia unofficial Trading api', 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", author = 'Rahul', 14 | author_email = '1994ghuge.gmail.com', 15 | url = 'https://github.com/Rahulghuge94/finshoonya', 16 | install_requires=['requests', 'pandas','pytz','websocket-client'], 17 | keywords = ['Finvasia', 'api', 'python', 'sdk', 'trading', 'stock markets'], 18 | classifiers=[ 19 | 'Intended Audience :: Developers', 20 | 'Natural Language :: English', 21 | 'Operating System :: OS Independent', 22 | 'Programming Language :: Python', 23 | 'Programming Language :: Python :: 3.6']) 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # finshoonya 2 | unofficial library to trade in finvasia. 3 | 4 | # Installation 5 | using git. 6 | ``` 7 | pip install git+https://github.com/Rahulghuge94/finshoonya.git 8 | ``` 9 | # Login 10 | To login provide ur account id,password and pan and create shoonya object. 11 | ``` 12 | from finshoonya import shoonya 13 | client=shoonya(userid="xyzk56",password="utyh675",pan="THG56214P",api_key="gdkmbloonvkmsdf") 14 | client.login() 15 | ``` 16 | # orderbook 17 | ``` 18 | print(client.orderbook()) 19 | ``` 20 | # position 21 | ``` 22 | print(client.position()) 23 | ``` 24 | # tradebook 25 | ``` 26 | print(client.tradebook()) 27 | ``` 28 | # place order 29 | to place intraday market order.. 30 | banknifty option 31 | ``` 32 | order=client.order(price=0,qty=25,tradingsymbol="BANKNIFTY16DEC21P35700",ord_tp="MKT",sl=0,buysell="B",exch="NFO",prdct="M",disc_qty=0,amo="NO",trigger_price=None, 33 | retention='DAY', remarks=None, bkpft = 0.0, trail_price = 0.0) 34 | print(order) 35 | ``` 36 | to place intraday limit order.. 37 | wipro 38 | ``` 39 | order=client.order(price=400,qty=25,tradingsymbol="WIPRO-EQ",ord_tp="LMT",sl=0,buysell="B",exch="NFO",prdct="I",disc_qty=0,amo="NO",trigger_price=None, 40 | retention='DAY', remarks=None, bkpft = 0.0, trail_price = 0.0) 41 | print(order) 42 | ``` 43 | to place delivery market order.. 44 | banknifty option 45 | ``` 46 | order=client.order(price=0,qty=25,tradingsymbol="BANKNIFTY16DEC21P35700",ord_tp="MKT",sl=0,buysell="B",exch="NFO",prdct="M",disc_qty=0,amo="NO",trigger_price=None, 47 | retention='DAY', remarks=None, bkpft = 0.0, trail_price = 0.0) 48 | print(order) 49 | ``` 50 | to place delivery limit order.. 51 | wipro 52 | ``` 53 | order=client.order(price=400,qty=25,tradingsymbol="WIPRO-EQ",ord_tp="LMT",sl=0,buysell="B",exch="NFO",prdct="D",disc_qty=0,amo="NO",trigger_price=None, 54 | retention='DAY', remarks=None, bkpft = 0.0, trail_price = 0.0) 55 | print(order) 56 | ``` -------------------------------------------------------------------------------- /finvasia.txt: -------------------------------------------------------------------------------- 1 | place order 2 | 3 | {"qty":1,"price":"MKT","odr_type":"MKT","product_typ":"I","trg_prc":0,"validity":"DAY","disc_qty":0,"amo":false,"sec_id":"3351","inst_type":"EQUITY","exch":"NSE", 4 | "buysell":"S","gtdDate":"0000-00-00","mktProtectionFlag":"N","mktProtectionVal":0,"settler":"000000000000","token_id":"8fae3e65f683885919c4", 5 | "keyid":"4c+5W3is90wBQHWEObt+QnVl05NoqtKFdloQLqXLqK0=","userid":"FA27632","clienttype":"C","usercode":"13549","pan_no":"CJEPG1375B"}: 6 | 7 | sl order {"qty":1,"price":825,"odr_type":"LMT","product_typ":"I","trg_prc":825,"validity":"DAY","disc_qty":0,"amo":false,"sec_id":"3351","inst_type":"EQUITY","exch":"NSE","buysell":"B","gtdDate":"0000-00-00","mktProtectionFlag":"N","mktProtectionVal":0,"settler":"000000000000","token_id":"8fae3e65f683885919c4","keyid":"4c+5W3is90wBQHWEObt+QnVl05NoqtKFdloQLqXLqK0=","userid":"FA27632","clienttype":"C","usercode":"13549","pan_no":"CJEPG1375B"}: 8 | 9 | 10 | orderbook 11 | 12 | { 13 | "CLIENT_ID": "FA27632", 14 | "ORDER_DATE_TIME": "21-Oct-2021 14:15:59", 15 | "ORDER_NUMBER": 1941319, 16 | "EXCHANGE": "NSE", 17 | "BUY_SELL": "Buy", 18 | "SEGMENT": "E", 19 | "INSTRUMENT": "EQUITY", 20 | "SYMBOL": "SUNPHARMA", 21 | "PRODUCT": "INTRADAY", 22 | "STATUS": "Pending", 23 | "QUANTITY": 1, 24 | "REMAINING_QUANTITY": 1, 25 | "PRICE": "825.00", 26 | "TRG_PRICE": 825, 27 | "ORDER_TYPE": "SL", 28 | "DISCLOSE_QTY": 0, 29 | "SERIALNO": 1, 30 | "SEM_SECURITY_ID": "3351", 31 | "ORDER_VALIDITY": "DAY", 32 | "SEM_NSE_REGULAR_LOT": 0, 33 | "REM_QTY_TOT_QTY": "1/1", 34 | "TAKE_PROFIT_TRAIL_GAP": 0, 35 | "ADV_GROUP_REF_NO": 0, 36 | "TRADEDQTY": 0, 37 | "DQQTYREM": 0, 38 | "EXCHORDERNO": "1300000019370713", 39 | "REASON_DESCRIPTION": "CONFIRMED", 40 | "LEG_NO": "1", 41 | "R": 1, 42 | "TRADED_PRICE": 0, 43 | "PAN_NO": "CJEPG1375B", 44 | "PARTICIPANT_TYPE": "B", 45 | "MKT_PROTECT_FLG": "N", 46 | "MKT_PROTECT_VAL": 0, 47 | "SETTLOR": "14846", 48 | "GTC_FLG": "N", 49 | "ENCASH_FLG": "N", 50 | "MKT_TYPE": "NL", 51 | "ALGO_ORD_NO": 0, 52 | "TRAILING_SL_VALUE": 0, 53 | "SL_ABSTICK_VALUE": 0, 54 | "PR_ABSTICK_VALUE": 0, 55 | "ORDER_OFFON": "0", 56 | "CHILD_LEG_UNQ_ID": 0, 57 | "STRIKE_PRICE": 0, 58 | "EXPIRY_DATE": "21-Oct-2021 ", 59 | "OPT_TYPE": "XX", 60 | "SM_SERIES": "EQ", 61 | "GTDdate": "21-Oct-2021 14:15:59", 62 | "SOURCE_FLG": "WEB" 63 | } 64 | 65 | placeorder response 66 | { 67 | "status": "success", 68 | "errorcode": "RS-0036", 69 | "message": "Order Submitted Successfully. Your Order Ref. No.1941319" 70 | } 71 | 72 | cancel order 73 | https://shoonya.finvasia.com/trade/cancelorder 74 | {"exch":"NSE","serialno":1,"orderno":1941319,"scripname":"SUNPHARMA","buysell":"B","qty_type":"SL","qty":1,"prc":"825.00","trg_prc":825,"disc_qty":0,"productlist":"I","order_typ":"DAY","sec_id":"3351","qty_rem":1,"inst_type":"E","offline_flag":false,"gtdDate":"0000-00-00","settler":"000000000000","token_id":"8fae3e65f683885919c4","keyid":"4c+5W3is90wBQHWEObt+QnVl05NoqtKFdloQLqXLqK0=","userid":"FA27632","clienttype":"C","usercode":"13549","pan_no":"CJEPG1375B"}: 75 | -------------------------------------------------------------------------------- /example/fifteen_min.py: -------------------------------------------------------------------------------- 1 | from finshoonya import shoonya 2 | import datetime 3 | import time 4 | import json 5 | from pytz import timezone 6 | import pandas as pd 7 | import sys 8 | 9 | #sys.stdout = open("/content/drive/MyDrive/algo/algolog.txt", "w") 10 | 11 | tze = timezone("Asia/Kolkata") 12 | 13 | #replace with your api and credentials. 14 | client = shoonya("user_id", "password", "onetimeotp", 15 | "your_api_key") 16 | client.login() 17 | 18 | #program variable 19 | positions = [] 20 | exit_time = datetime.time(15, 10) 21 | no_of_lot = 1 22 | lot_size = 25 23 | symbol = "BANKNIFTY" 24 | typ_of_symbol = "C" 25 | expiry = "28JUL22" 26 | strike = 36300 27 | TSYM = symbol + expiry + typ_of_symbol + str(strike) 28 | scpd = client.get_scripcode(TSYM, "NFO")["values"][0] 29 | qty = 25 30 | trail_sl = 2 31 | 32 | def get_order_executed_price_single(oid): 33 | count = 5 34 | while count != 0: 35 | _ord = client.order_detail(oid)[0] 36 | if _ord and _ord["status"] == "COMPLETE": 37 | return float(_ord["avgprc"]) 38 | if _ord and _ord["status"] == "REJECTED": 39 | print("Order rejected.") 40 | break 41 | count -= 1 42 | 43 | HDATA, candles = {}, {} 44 | LTP={} 45 | 46 | def on_message(ws, message, data_type = None, continue_flag = None): 47 | global LTP, HDATA#global ltp object 48 | msg = json.loads(message) 49 | #print(msg) 50 | if "tk" in msg and "lp" in msg: 51 | #print(msg,type(msg)) 52 | if msg['tk'] not in HDATA: 53 | HDATA.update({str(msg['tk']): []}) 54 | LTP[str(msg['tk'])] = float(msg['lp']) 55 | HDATA[str(msg['tk'])].append({"ltt":datetime.datetime.now(tze), "ltp":float(msg['lp'])}) 56 | 57 | def get_ref_price_and_flags(): 58 | ordb = client.orderbook() 59 | ordb = [o for o in ordb if "remarks" in o and o["status"] == "COMPLETE"] 60 | BOUGHT = True if ordb[0]["trantype"] == "B" else False 61 | SOLD = True if ordb[0]["trantype"] == "S" else False 62 | refPrice = float(ordb[0]["avgprc"]) 63 | return BOUGHT, SOLD, refPrice 64 | 65 | def create_candlestick(data, timeframe = 20): 66 | _df = pd.DataFrame(data) 67 | _df.set_index(pd.DatetimeIndex(_df["ltt"]), inplace = True) 68 | _df = _df["ltp"].resample(f'{timeframe}S').ohlc() 69 | return _df 70 | 71 | #starts websocket and subscribe token.. 72 | #client.start_websocket(on_message) 73 | time.sleep(5) 74 | #client.subscribe(f'NFO|{scpd["token"]}', "t") 75 | time.sleep(5) 76 | #refPrice = LTP[scpd["token"]] 77 | positions = []#[i for i in client.position() if i['tsym'] == TSYM and int(i['netqty']) != 0] 78 | 79 | BOUGHT = False 80 | SOLD = False 81 | LONG_PRICE = None 82 | SHORT_PRICE = None 83 | if positions: 84 | BOUGHT, SOLD, refPrice = get_ref_price_and_flags() 85 | 86 | while datetime.datetime.now(tze).time() < datetime.time(23, 10): 87 | if BOUGHT and LTP[scpd["token"]] >= refPrice + 10: 88 | print(f"B|{datetime.datetime.now(tze)}|old refPrice:",refPrice) 89 | refPrice += trail_sl 90 | print(f"B|{datetime.datetime.now(tze)}|new refPrice:",refPrice) 91 | 92 | if SOLD and LTP[scpd["token"]] <= refPrice - 10: 93 | print(f"S|{datetime.datetime.now(tze)}|old refPrice:",refPrice) 94 | refPrice -= trail_sl 95 | print(f"S|{datetime.datetime.now(tze)}|new refPrice:",refPrice) 96 | if 1.5 >datetime.datetime.now(tze).time().second % 15 >= 0 and LTP[scpd["token"]] > refPrice and not BOUGHT: 97 | order = client.order(price=0, qty = qty *2 if SOLD else qty, tradingsymbol = TSYM, ord_tp = "MKT", sl = 0, buysell = "B", exch = "NFO", 98 | prdct = "M", amo="NO", remarks = "STRATEGY") 99 | _PRICE = get_order_executed_price_single(order["norenordno"]) 100 | print(f'{datetime.datetime.now(tze).time().isoformat()}|{TSYM} BOUGHT AT: {_PRICE}') 101 | SOLD = False 102 | BOUGHT = True 103 | time.sleep(1.5) 104 | 105 | if 1.5 >datetime.datetime.now(tze).time().second % 15 >= 0 and LTP[scpd["token"]] < refPrice and not SOLD: 106 | order = client.order(price=0, qty = qty *2 if BOUGHT else qty, tradingsymbol = TSYM, ord_tp = "MKT", sl = 0, buysell = "S", exch = "NFO", 107 | prdct = "M", amo="NO", remarks = "STRATEGY") 108 | _PRICE = get_order_executed_price_single(order["norenordno"]) 109 | print(f'{datetime.datetime.now(tze).time().isoformat()}|{TSYM} SOLD AT: {_PRICE}') 110 | SOLD = True 111 | BOUGHT = False 112 | 113 | time.sleep(1.5) 114 | print(f"ALGO STOPPED DUE TO TRADING HOUR IS OVER.") 115 | -------------------------------------------------------------------------------- /finshoonya/finshoonya.py: -------------------------------------------------------------------------------- 1 | """ 2 | @auther:Rahul Ghuge 3 | unofficial api to trade with finvasia. 4 | """ 5 | import requests 6 | import json,os 7 | import time,datetime 8 | from time import sleep 9 | import pandas as pd 10 | import hashlib 11 | from pytz import timezone 12 | import websocket 13 | import threading 14 | tze=timezone('Asia/Kolkata')#timezone to work with cloud instances. 15 | 16 | 17 | class shoonya(object): 18 | 19 | _root={"login": "/QuickAuth", "fund": "/Limits", "position": "/PositionBook", "orderbook": "/OrderBook", "tradebook": "/TradeBook", "holding": "/Holdings", 20 | "order": '/PlaceOrder', "modifyorder": '/ModifyOrder', "cancelorder": '/CancelOrder', "exitorder": '/ExitSNOOrder', "singleorderhistory": '/SingleOrdHist', 21 | "searchscrip": '/SearchScrip', "scripinfo": '/GetSecurityInfo', "getquote": '/GetQuotes', "hist_data": "/TPSeries", "option": "/GetOptionChain"} 22 | 23 | def __init__(self, userid: str=None, password: str=None, twofa: str=None, app_key: str=None, source="WEB"): 24 | self.userid = userid 25 | self.password = hashlib.sha256(password.encode('utf-8')).hexdigest() if password else password 26 | self.twofa = twofa 27 | self.imei = "dbbf5adf877739404c9220a28002b5d3" 28 | self.app_key = app_key 29 | self.session = requests.session() 30 | self.url = "https://trade.shoonya.com/NorenWClientWeb" 31 | self.wss_url = "wss://trade.shoonya.com/NorenWSWeb/" 32 | self.access_token = None 33 | #self.wss = None 34 | self.__wss = None 35 | self.wss_connected = False 36 | self.__ws_mutex = threading.Lock() 37 | self.subscribed = [] 38 | self.LTP = {} 39 | self.ordsource = source 40 | 41 | def login(self): 42 | values = {"uid": self.userid, "pwd": self.password, "factor2": self.twofa, 43 | "apkversion": "1.2.0", "imei": self.imei, "vc": "NOREN_WEB", 44 | "appkey": self.app_key, "source": "WEB", "addldivinf": "Chrome-96.0.4664.45"} 45 | data = "jData="+json.dumps(values) 46 | #print(data, self.url + self._root["login"]) 47 | res = self.session.post(self.url + self._root["login"], data = data) 48 | if res.status_code != 200: 49 | print(f"Unable to Login. Reason:{res.text}") 50 | return 51 | else: 52 | res = res.json() 53 | self.access_token = res["susertoken"] 54 | self.write_cred() 55 | print("Logged In.") 56 | 57 | def log_using_api(self): 58 | #Convert to SHA 256 for password and app key 59 | self.url = "https://api.shoonya.com/NorenWClientTP/" 60 | pwd = self.password 61 | u_app_key = '{0}|{1}'.format(self.userid, self.app_key) 62 | app_key = hashlib.sha256(u_app_key.encode('utf-8')).hexdigest() 63 | #prepare the data 64 | values = { "source": "API" , "apkversion": "1.0.0"} 65 | values["uid"] = self.userid 66 | values["pwd"] = self.password 67 | values["factor2"] = self.twofa 68 | values["vc"] = f"{self.userid}_U" 69 | values["appkey"] = app_key 70 | values["imei"] = "abc1234" 71 | 72 | payload = 'jData=' + json.dumps(values) 73 | res = requests.post(self.url+self._root["login"], data = payload) 74 | #print(res) 75 | resDict = json.loads(res.text) 76 | print(resDict,payload) 77 | if resDict['stat'] != 'Ok': 78 | return None 79 | self.access_token = resDict['susertoken'] 80 | self.write_cred() 81 | print("Logged In.") 82 | 83 | def check_if_source_is_api_and_add_source(self, data): 84 | if self.url == "https://api.shoonya.com/NorenWClientTP/": 85 | data.update({'ordersource':'API'}) 86 | return data 87 | 88 | def api_helper(self, url, data=None, req_typ: str="POST"): 89 | if data and req_typ == "POST": 90 | self.load_cred() 91 | data = 'jData=' + json.dumps(data) + f'&jKey={self.access_token}' 92 | res = self.session.post(url, data = data) 93 | if res.status_code !=200 and "Session Expired : Invalid Session Key" in res.text: 94 | print(f"Unable to Login. Reason:{res.text}") 95 | if self.ordsource == "WEB": 96 | self.login() 97 | else: 98 | self.log_using_api() 99 | self.write_cred() 100 | return self.session.post(url, data = data) 101 | else: 102 | res = res.json() 103 | return res 104 | if not data and req_typ == "GET": 105 | res = self.session.get(url) 106 | if res.status_code != 200 and "Session Expired : Invalid Session Key" in res.text: 107 | print(f"Unable to Login. Reason:{res.text}") 108 | return 109 | else: 110 | return res 111 | 112 | def load_cred(self): 113 | sessn = None 114 | data = None 115 | if os.path.isfile("cred.json"): 116 | sessn = open("cred.json", "r") 117 | data = json.load(sessn) 118 | else: 119 | self.login() 120 | self.userid = data["userid"] 121 | self.password = data["password"] 122 | self.twofa = data["twofa"] 123 | self.access_token = data["access_token"] 124 | self.app_key = data["app_key"] 125 | 126 | def write_cred(self): 127 | sessn = open("cred.json","w") 128 | dic = {"userid": self.userid, "password": self.password, "twofa": self.twofa, 129 | "access_token": self.access_token, "app_key": self.app_key} 130 | json.dump(dic, sessn) 131 | 132 | def fund(self): 133 | url = self.url + self._root["fund"] 134 | data={"uid": self.userid, "actid": self.userid} 135 | return self.api_helper(url, data = data, req_typ = "POST") 136 | 137 | def orderbook(self): 138 | url = self.url + self._root["orderbook"] 139 | data = {"uid": self.userid,"ordersource": self.ordsource} 140 | res = self.api_helper(url, data = data, req_typ = "POST") 141 | return res 142 | 143 | def position(self): 144 | url = self.url + self._root["position"] 145 | data = {"uid": self.userid, "actid": self.userid} 146 | res = self.api_helper(url, data = data, req_typ = "POST") 147 | return res 148 | 149 | def tradebook(self): 150 | url = self.url + self._root["tradebook"] 151 | data = {"uid": self.userid, "actid": self.userid, "ordersource": self.ordsource} 152 | res = self.api_helper(url, data=data, req_typ="POST") 153 | return res 154 | 155 | def holdings(self): 156 | url = self.url + self._root["holding"] 157 | data = {"uid": self.userid,"actid": self.userid} 158 | res = self.api_helper(url, data = data, req_typ = "POST") 159 | if res["stat"]=="Not_Ok": 160 | return [] 161 | else: 162 | return res 163 | 164 | #order status "COMPLETE",REJECTED,"CANCELED" "OPEN" "PENDING" 165 | def order(self, price, qty, tradingsymbol, ord_tp, sl = 0, buysell = "B", exch = "NSE", prdct = "I", disc_qty = 0, amo = "NO", trigger_price = None, 166 | retention = 'DAY', remarks = "Orderleg1", bkpft = 0.0, trail_price = 0.0): 167 | """ 168 | place order 169 | """ 170 | data= {"uid": self.userid, "actid": self.userid, "trantype": buysell, "prd": prdct, "exch": exch, 171 | "tsym": tradingsymbol, "qty": str(qty),"dscqty": str(disc_qty), "prctyp": ord_tp, "prc": str(price), 172 | "trgprc": str(trigger_price), "ret": retention, "remarks": remarks, "amo": amo, 'ordersource': self.ordsource} 173 | #print(data) 174 | url = self.url + self._root["order"] 175 | #cover order 176 | if prdct == 'H': 177 | data["blprc"] = str(sl) 178 | #trailing price 179 | if trail_price != 0.0: 180 | data["trailprc"] = str(trail_price) 181 | #bracket order 182 | if prdct == 'B': 183 | data["blprc"] = str(sl) 184 | data["bpprc"] = str(bkpft) 185 | #trailing price 186 | if trail_price != 0.0: 187 | data["trailprc"] = str(trail_price) 188 | res = self.api_helper(url, data = data, req_typ = "POST") 189 | if res["stat"] == "Not_Ok": 190 | return None 191 | else: 192 | return res 193 | 194 | def modify_order(self, orderno, exch, tradingsymbol, qty, ord_tp, product_type=None, price=0.0, trigger_price=None, sl=0.0, bkpft=0.0, trail_price=0.0): 195 | url = self.url + self._root["modifyorder"] 196 | data = {"uid": self.userid, "actid": self.userid, "norenordno": orderno, "exch": exch, "tsym": tradingsymbol, "qty": str(qty), "prctyp": ord_tp, 197 | "prc": str(price), "ordersource": self.ordsource} 198 | if (ord_tp == 'SL-LMT') or (ord_tp == 'SL-MKT'): 199 | if (trigger_price != None): 200 | data["trgprc"] = trigger_price 201 | else: 202 | return None 203 | #if cover order or high leverage order 204 | if product_type == 'H': 205 | data["blprc"] = str(bkpft) 206 | #trailing price 207 | if trail_price != 0.0: 208 | data["trailprc"] = str(trail_price) 209 | #bracket order 210 | if product_type == 'B': 211 | data["blprc"] = str(sl) 212 | data["bpprc"] = str(bkpft) 213 | #trailing price 214 | if trail_price != 0.0: 215 | data["trailprc"] = str(trail_price) 216 | res = self.api_helper(url, data = data, req_typ = "POST") 217 | if res["stat"] == "Not_Ok": 218 | return None 219 | else: 220 | return res 221 | 222 | def cancel_order(self, order_no: str): 223 | url = self.url + self._root["cancelorder"] 224 | data = {"uid": self.userid, "norenordno": str(order_no), "ordersource": self.ordsource} 225 | res = self.api_helper(url, data = data, req_typ = "POST") 226 | return res 227 | 228 | def order_detail(self, order_no: str): 229 | url = self.url + self._root["singleorderhistory"] 230 | data = {"uid": self.userid, "norenordno": str(order_no), "ordersource": self.ordsource} 231 | res = self.api_helper(url, data = data, req_typ = "POST") 232 | return res 233 | 234 | def getdata(self,secid:str, fdt:str, tdt:str, exch:str="NSE", interval="1"): 235 | """ 236 | :param 237 | tdt:to date in timestamp i.e.1650864392 238 | fdt: from date in timestamp i.e.1650764392 239 | secid: security name i.e. TTTAN-EQ, NIFTY31MAR22P36000,BANKNIFTY31MAR22C36000 240 | interval possible values 1, 3, 5 , 10, 15, 30, 60, 120, 240 241 | #symbol format option SYMEXPCorPSTRIKE fut SYMEXPF expiry format ddmmyy equity sym-EQ 242 | """ 243 | url = "https://shoonyatrade.finvasia.com//NorenWClientWeb/TPSeries" 244 | data = {"uid": self.userid, "exch": exch, "token": secid, "st": fdt, "et": tdt, "intrv": interval} 245 | res = self.api_helper(url, data = data, req_typ = "POST") 246 | #print(res) 247 | res.sort(key = lambda x: x["ssboe"]) 248 | res = pd.DataFrame(res) 249 | res.rename(columns = {'into': 'Open','inth': 'High','intl': 'Low','intc': 'Close','intvwap': 'vwap','intv': 'Volume','intoi': 'OI', 250 | 'v': 'TVolume','oi': 'TOI'}, inplace = True) 251 | cng_typ = {"Open": float, "High": float, "Low": float, "Close": float, "Volume": int, "OI": int, "vwap": float, "TVolume": float, "TOI": int} 252 | res = res.astype(cng_typ) 253 | res.drop("stat", axis = 1, inplace = True) 254 | return res 255 | 256 | def get_quote(self, secid, exch="NSE"): 257 | url = self.url+self._root["getquote"] 258 | data = {"uid": self.userid, "exch": exch, "token": secid} 259 | res = self.api_helper(url, data = data, req_typ = "POST") 260 | if res["stat"] == "Not_Ok": 261 | return None 262 | else: 263 | return res 264 | 265 | def get_scripcode(self, searchstring, exch="NSE"): 266 | url = self.url + '/SearchScrip' 267 | data = {"uid": self.userid, "exch": exch, "stext": str(searchstring)} 268 | res = self.api_helper(url, data = data, req_typ = "POST") 269 | if res["stat"]=="Not_Ok": 270 | return None 271 | else: 272 | return res 273 | 274 | def get_scripinfo(self, token, exch="NSE"): 275 | url = self.url+'/GetSecurityInfo' 276 | data = {"uid": self.userid, "exch": exch, "token": str(token)} 277 | res = self.api_helper(url, data = data, req_typ = "POST") 278 | if res["stat"] == "Not_Ok": 279 | return None 280 | else: 281 | return res 282 | 283 | def close_all(self): 284 | posns = self.position() 285 | if not posns: 286 | return "No open Positions." 287 | for i in posns: 288 | if i["netqty"] < 0: 289 | ord = self.order(price = 0, qty = i["netqty"], tradingsymbol = i["tsym"], ord_tp = "MKT", sl = 0, buysell = "B", exch = i["exch"], prdct = i["prd"]) 290 | print(ord) 291 | for i in posns: 292 | if i["netqty"] > 0: 293 | self.order(price = 0, qty = i["netqty"], tradingsymbol = i["tsym"], ord_tp = "MKT", sl = 0, buysell = "S", exch = i["exch"], prdct = i["prd"]) 294 | print(ord) 295 | 296 | def get_open_position(self): 297 | posns = self.position() 298 | pos = [] 299 | if not posns: 300 | return "No open Positions." 301 | for i in posns: 302 | if i["netqty"] != 0: 303 | pos.append("i") 304 | return pos 305 | 306 | def is_position_open(self, tsym): 307 | posns = self.position() 308 | pos = [] 309 | if not posns: 310 | return False 311 | for i in posns: 312 | if i["tsym"] == tsym: 313 | return True 314 | return False 315 | 316 | def __ws_run_forever(self): 317 | while True: 318 | try: 319 | self.__wss.run_forever(ping_interval=3, ping_payload='{"t": "h"}') 320 | except Exception as e: 321 | "Error" 322 | sleep(0.1) # Sleep for 100ms between reconnection. 323 | 324 | def __ws_send(self, *args, **kwargs): 325 | while self.wss_connected == False: 326 | sleep(0.05) # sleep for 50ms if websocket is not connected, wait for reconnection 327 | with self.__ws_mutex: 328 | ret = self.__wss.send(*args, **kwargs) 329 | return ret 330 | 331 | def __on_close(self, wsapp, close_status_code, close_msg): 332 | self.wss_connected = False 333 | print("WEBSOCKET closed.", close_msg) 334 | 335 | def __on_open(self, ws=None): 336 | print("Im in open callback.") 337 | self.wss_connected = True 338 | values = { "t": "c" } 339 | values["uid"] = self.userid 340 | values["pwd"] = self.password 341 | values["actid"] = self.userid 342 | values["susertoken"] = self.access_token 343 | values["source"] = self.ordsource 344 | payload = json.dumps(values) 345 | #print(payload) 346 | self.__ws_send(payload) 347 | 348 | def __on_error(self, ws=None, error=None): 349 | print(error) 350 | 351 | def __on_data_callback(self, ws=None, message=None, data_type=None, continue_flag=None): 352 | msg = json.loads(message) 353 | if msg["tk"] not in self.LTP: 354 | self.LTP.update({str(msg['tk']): msg['lp']}) 355 | 356 | def start_websocket(self,data_and_ord_callback=None): 357 | """ Start a websocket connection for getting live data """ 358 | url=self.wss_url 359 | #print(url) 360 | if not data_and_ord_callback: 361 | data_and_ord_callback=self.__on_data_callback 362 | self.__wss = websocket.WebSocketApp(url, 363 | on_data=data_and_ord_callback, 364 | on_error=self.__on_error, 365 | on_close=self.__on_close, 366 | on_open=self.__on_open) 367 | self.__ws_thread = threading.Thread(target=self.__ws_run_forever) 368 | self.__ws_thread.daemon = True 369 | self.__ws_thread.start() 370 | 371 | def subscribe(self, instrument, feed_type="t"): #t:touchline d: 372 | values = {"t": feed_type} 373 | if type(instrument) == list: 374 | values['k'] = '#'.join(instrument) 375 | else : 376 | values['k'] = instrument 377 | data = json.dumps(values) 378 | self.__ws_send(data) 379 | self.subscribed.append(instrument.split("|")[1]) 380 | 381 | def subscribe_orders(self): 382 | values = {'t': 'o'} 383 | values['actid'] = self.userid 384 | data = json.dumps(values) 385 | self.__ws_send(data) 386 | 387 | def get_option_chain(self, exch, tradingsymbol, strikeprice, count=50): 388 | """ 389 | client.get_option_chain("NFO","BANKNIFTY30DEC21","37000",50) 390 | """ 391 | url = self.url+self._root["option"] 392 | data = {"uid": self.userid, "exch": exch, "tsym": tradingsymbol,"strprc": str(strikeprice), "cnt": str(count)} 393 | res = self.api_helper(url, data = data, req_typ = "POST") 394 | if res["stat"] == "Not_Ok": 395 | return res 396 | else: 397 | return res 398 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------