From 40e8c0da26946604d963d9188bad998d3ddc717e Mon Sep 17 00:00:00 2001 From: ankurjhaag <108059707+ankurjhaag@users.noreply.github.com> Date: Fri, 30 Sep 2022 17:38:44 +0530 Subject: [PATCH 01/46] added gitignore file --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 3953ffd0..2414d44c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ -.pypirc \ No newline at end of file +.pypirc +*.xml From b999de9e04f62b4599f86ac4b11a7a36a3cd4930 Mon Sep 17 00:00:00 2001 From: ankurjhaag <108059707+ankurjhaag@users.noreply.github.com> Date: Fri, 30 Sep 2022 18:46:25 +0530 Subject: [PATCH 02/46] updated gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 2414d44c..6b9151d1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .pypirc *.xml +.idea/smartapi-python.iml From 0d84f39e05bb3e745103e17e12f921041e90cb69 Mon Sep 17 00:00:00 2001 From: moizm89 <93924295+moizm89@users.noreply.github.com> Date: Fri, 30 Sep 2022 18:51:37 +0530 Subject: [PATCH 03/46] Update README.md --- README.md | 146 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 144 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4ded8eb6..095b325f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,145 @@ -# Migrated to New Github Repo https://github.com/angel-one/smartapi-python -For latest updates and bug fixes please refer to the new git repo. +# SMARTAPI-PYTHON + +SMARTAPI-PYTHON is a Python library for dealing AMX,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time. + +## Installation + +Use the package manager [pip](https://pip.pypa.io/en/stable/) to install smartapi-python. + +```bash +pip install smartapi-python +pip install websocket-client +``` + +## Usage + +```python +# package import statement +from smartapi import SmartConnect #or from smartapi.smartConnect import SmartConnect +#import smartapi.smartExceptions(for smartExceptions) + +#create object of call +obj=SmartConnect(api_key="your api key", + #optional + #access_token = "your access token", + #refresh_token = "your refresh_token") + +#login api call + +data = obj.generateSession("Your Client ID","Your Password") +refreshToken= data['data']['refreshToken'] + +#fetch the feedtoken +feedToken=obj.getfeedToken() + +#fetch User Profile +userProfile= obj.getProfile(refreshToken) +#place order +try: + orderparams = { + "variety": "NORMAL", + "tradingsymbol": "SBIN-EQ", + "symboltoken": "3045", + "transactiontype": "BUY", + "exchange": "NSE", + "ordertype": "LIMIT", + "producttype": "INTRADAY", + "duration": "DAY", + "price": "19500", + "squareoff": "0", + "stoploss": "0", + "quantity": "1" + } + orderId=obj.placeOrder(orderparams) + print("The order id is: {}".format(orderId)) +except Exception as e: + print("Order placement failed: {}".format(e.message)) +#gtt rule creation +try: + gttCreateParams={ + "tradingsymbol" : "SBIN-EQ", + "symboltoken" : "3045", + "exchange" : "NSE", + "producttype" : "MARGIN", + "transactiontype" : "BUY", + "price" : 100000, + "qty" : 10, + "disclosedqty": 10, + "triggerprice" : 200000, + "timeperiod" : 365 + } + rule_id=obj.gttCreateRule(gttCreateParams) + print("The GTT rule id is: {}".format(rule_id)) +except Exception as e: + print("GTT Rule creation failed: {}".format(e.message)) + +#gtt rule list +try: + status=["FORALL"] #should be a list + page=1 + count=10 + lists=obj.gttLists(status,page,count) +except Exception as e: + print("GTT Rule List failed: {}".format(e.message)) + +#Historic api +try: + historicParam={ + "exchange": "NSE", + "symboltoken": "3045", + "interval": "ONE_MINUTE", + "fromdate": "2021-02-08 09:00", + "todate": "2021-02-08 09:16" + } + obj.getCandleData(historicParam) +except Exception as e: + print("Historic Api failed: {}".format(e.message)) +#logout +try: + logout=obj.terminateSession('Your Client Id') + print("Logout Successfull") +except Exception as e: + print("Logout failed: {}".format(e.message)) +``` + + +## Getting started with SmartAPI Websocket's +```python + +from smartapi import SmartWebSocket + +# feed_token=092017047 +FEED_TOKEN="YOUR_FEED_TOKEN" +CLIENT_CODE="YOUR_CLIENT_CODE" +# token="mcx_fo|224395" +token="EXCHANGE|TOKEN_SYMBOL" #SAMPLE: nse_cm|2885&nse_cm|1594&nse_cm|11536&nse_cm|3045 +# token="mcx_fo|226745&mcx_fo|220822&mcx_fo|227182&mcx_fo|221599" +task="mw" # mw|sfi|dp + +ss = SmartWebSocket(FEED_TOKEN, CLIENT_CODE) + +def on_message(ws, message): + print("Ticks: {}".format(message)) + +def on_open(ws): + print("on open") + ss.subscribe(task,token) + +def on_error(ws, error): + print(error) + +def on_close(ws): + print("Close") + +# Assign the callbacks. +ss._on_open = on_open +ss._on_message = on_message +ss._on_error = on_error +ss._on_close = on_close + +ss.connect() +``` + + + From 81536b2b67b61f0c67f000990fcd3fb44d1fbec8 Mon Sep 17 00:00:00 2001 From: ankurjhaag <108059707+ankurjhaag@users.noreply.github.com> Date: Fri, 30 Sep 2022 19:10:16 +0530 Subject: [PATCH 04/46] Added totp change --- .gitignore | 3 +++ SmartApi/smartConnect.py | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 6b9151d1..0b843705 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,6 @@ .pypirc *.xml .idea/smartapi-python.iml +build/* +smartapi_python.egg-info +dist/* \ No newline at end of file diff --git a/SmartApi/smartConnect.py b/SmartApi/smartConnect.py index c8f65a89..7ca26e42 100644 --- a/SmartApi/smartConnect.py +++ b/SmartApi/smartConnect.py @@ -222,9 +222,9 @@ def _getRequest(self, route, params=None): """Alias for sending a GET request.""" return self._request(route, "GET", params) - def generateSession(self,clientCode,password): + def generateSession(self,clientCode,password,totp): - params={"clientcode":clientCode,"password":password} + params={"clientcode":clientCode,"password":password,"totp":totp} loginResultObject=self._postRequest("api.login",params) if loginResultObject['status']==True: From a564ca5cec683ecacab6c4ce7a607730daf18d9b Mon Sep 17 00:00:00 2001 From: ankurjhaag <108059707+ankurjhaag@users.noreply.github.com> Date: Fri, 30 Sep 2022 19:26:15 +0530 Subject: [PATCH 05/46] Added sample file with totp --- example/sample.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/sample.py b/example/sample.py index 9aca4354..8143447d 100644 --- a/example/sample.py +++ b/example/sample.py @@ -7,7 +7,7 @@ #login api call -data = obj.generateSession("Your Client ID","Your Password") +data = obj.generateSession("Your Client ID","Your Password","Your totp here") refreshToken= data['data']['refreshToken'] #fetch the feedtoken From a6fe63901ec02577c46f9e848fc7d665c835fef1 Mon Sep 17 00:00:00 2001 From: ajha1991 <108059707+ajha1991@users.noreply.github.com> Date: Fri, 30 Sep 2022 19:29:32 +0530 Subject: [PATCH 06/46] Updated Readme with new totp provision --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 095b325f..fca59ecb 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ obj=SmartConnect(api_key="your api key", #login api call -data = obj.generateSession("Your Client ID","Your Password") +data = obj.generateSession("Your Client ID","Your Password","Your totp") refreshToken= data['data']['refreshToken'] #fetch the feedtoken From 5928f1093084f63a355567503e23c10b01214b48 Mon Sep 17 00:00:00 2001 From: builder35abhishek Date: Wed, 16 Nov 2022 11:23:29 +0530 Subject: [PATCH 07/46] Save feedtoken during generate session --- SmartApi/smartConnect.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SmartApi/smartConnect.py b/SmartApi/smartConnect.py index c8f65a89..f7567571 100644 --- a/SmartApi/smartConnect.py +++ b/SmartApi/smartConnect.py @@ -241,7 +241,7 @@ def generateSession(self,clientCode,password): self.setUserId(id) user['data']['jwtToken']="Bearer "+jwtToken user['data']['refreshToken']=refreshToken - + user['data']['feedToken'] = feedToken return user else: From 2a66b8421a017566205de76be3c80cd0e6217262 Mon Sep 17 00:00:00 2001 From: rohitendras <44818445+rohitendras@users.noreply.github.com> Date: Thu, 19 Jan 2023 04:17:33 +0530 Subject: [PATCH 08/46] Update version.py version url change to https://github.com/angel-one/smartapi-python --- SmartApi/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SmartApi/version.py b/SmartApi/version.py index 78d56e9f..c240cb6a 100644 --- a/SmartApi/version.py +++ b/SmartApi/version.py @@ -1,7 +1,7 @@ __title__ = "smartapi-python" __description__ = "Angel Broking openApi integration" __url__ = "https://www.angelbroking.com/" -__download_url__ = "https://github.com/angelbroking-github/smartapi-python" +__download_url__ = "https://github.com/angel-one/smartapi-python" __version__ = "1.2.6" __author__ = "ab-smartapi" __token__ = "ab-smartapi" From 243a5634ec43d62a96b96c617d3d307d578c62df Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Mon, 5 Jun 2023 18:02:53 +0530 Subject: [PATCH 09/46] Add files via upload --- SmartApi/smartWebSocketV2.py | 438 +++++++++++++++++++++++++++++++++++ 1 file changed, 438 insertions(+) create mode 100644 SmartApi/smartWebSocketV2.py diff --git a/SmartApi/smartWebSocketV2.py b/SmartApi/smartWebSocketV2.py new file mode 100644 index 00000000..07a52698 --- /dev/null +++ b/SmartApi/smartWebSocketV2.py @@ -0,0 +1,438 @@ +import struct +import threading +import time +import ssl +import json +import websocket +from datetime import datetime, timedelta +from threading import Timer + +class SmartWebSocketV2(object): + """ + SmartAPI Web Socket version 2 + """ + + ROOT_URI = "ws://smartapisocket.angelone.in/smart-stream" + HEART_BEAT_MESSAGE = "ping" + HEART_BEAT_INTERVAL = 10 # Adjusted to 10s + LITTLE_ENDIAN_BYTE_ORDER = "<" + RESUBSCRIBE_FLAG = False + # HB_THREAD_FLAG = True + MAX_RETRY_ATTEMPT = 1 + + # Available Actions + SUBSCRIBE_ACTION = 1 + UNSUBSCRIBE_ACTION = 0 + + # Possible Subscription Mode + LTP_MODE = 1 + QUOTE = 2 + SNAP_QUOTE = 3 + + # Exchange Type + NSE_CM = 1 + NSE_FO = 2 + BSE_CM = 3 + BSE_FO = 4 + MCX_FO = 5 + NCX_FO = 7 + CDE_FO = 13 + + # Subscription Mode Map + SUBSCRIPTION_MODE_MAP = { + 1: "LTP", + 2: "QUOTE", + 3: "SNAP_QUOTE" + } + + wsapp = None + input_request_dict = {} + current_retry_attempt = 0 + + def __init__(self, auth_token, api_key, client_code, feed_token): + """ + Initialise the SmartWebSocketV2 instance + Parameters + ------ + auth_token: string + jwt auth token received from Login API + api_key: string + api key from Smart API account + client_code: string + angel one account id + feed_token: string + feed token received from Login API + """ + self.auth_token = auth_token + self.api_key = api_key + self.client_code = client_code + self.feed_token = feed_token + self.DISCONNECT_FLAG = True + self.last_pong_timestamp = None + + if not self._sanity_check(): + raise Exception("Provide valid value for all the tokens") + + def _sanity_check(self): + return True + # if self.auth_token is None or self.api_key is None or self.client_code is None or self.feed_token is None: + # return False + # return True + + def _on_message(self, wsapp, message): + print("message--->", message) + if message != "pong": + parsed_message = self._parse_binary_data(message) + self.on_message(wsapp, parsed_message) + else: + self.on_message(wsapp, message) + + def _on_data(self, wsapp, data, data_type, continue_flag): + + if data_type == 2: + parsed_message = self._parse_binary_data(data) + self.on_data(wsapp, parsed_message) + else: + self.on_data(wsapp, data) + + def _on_open(self, wsapp): + if self.RESUBSCRIBE_FLAG: + self.resubscribe() + self.RESUBSCRIBE_FLAG = False # Add this line to prevent resubscription on subsequent reconnects + else: + self.on_open(wsapp) + + def _on_pong(self, wsapp, data): + if data == self.HEART_BEAT_MESSAGE: + timestamp = time.time() + formatted_timestamp = time.strftime("%d-%m-%y %H:%M:%S", time.localtime(timestamp)) + print(f"In on pong function ==> {data}, Timestamp: {formatted_timestamp}") + self.last_pong_timestamp = timestamp + else: + # Handle the received feed data here + self.on_data(wsapp, data) + + def _on_ping(self, wsapp, data): + timestamp = time.time() + formatted_timestamp = time.strftime("%d-%m-%y %H:%M:%S", time.localtime(timestamp)) + print(f"In on ping function ==> {data}, Timestamp: {formatted_timestamp}") + self.last_ping_timestamp = timestamp + + def start_ping_timer(self): + def send_ping(): + try: + current_time = datetime.now() + if self.last_pong_timestamp is None or self.last_pong_timestamp < current_time - timedelta(seconds=20): + print("No pong response received. Disconnecting WebSocket and attempting to resubscribe...") + self.wsapp.close() + self.connect() + else: + self.last_ping_timestamp = time.time() + try: + self.wsapp.send(self.HEART_BEAT_MESSAGE) + except WebSocketConnectionClosedException: + print( + "WebSocket connection is already closed. Disconnecting WebSocket and attempting to resubscribe...") + self.resubscribe() + except Exception as e: + print(f"Error occurred: {str(e)}. Disconnecting WebSocket and attempting to resubscribe...") + self.wsapp.close() + self.resubscribe() + + ping_timer = Timer(10, send_ping) # Send a ping every 10 seconds + ping_timer.start() + + def subscribe(self, correlation_id, mode, token_list): + """ + This Function subscribe the price data for the given token + Parameters + ------ + correlation_id: string + A 10 character alphanumeric ID client may provide which will be returned by the server in error response + to indicate which request generated error response. + Clients can use this optional ID for tracking purposes between request and corresponding error response. + mode: integer + It denotes the subscription type + possible values -> 1, 2 and 3 + 1 -> LTP + 2 -> Quote + 3 -> Snap Quote + token_list: list of dict + Sample Value -> + [ + { "exchangeType": 1, "tokens": ["10626", "5290"]}, + {"exchangeType": 5, "tokens": [ "234230", "234235", "234219"]} + ] + exchangeType: integer + possible values -> + 1 -> nse_cm + 2 -> nse_fo + 3 -> bse_cm + 4 -> bse_fo + 5 -> mcx_fo + 7 -> ncx_fo + 13 -> cde_fo + tokens: list of string + """ + try: + request_data = { + "correlationID": correlation_id, + "action": self.SUBSCRIBE_ACTION, + "params": { + "mode": mode, + "tokenList": token_list + } + } + if self.input_request_dict.get(mode, None) is None: + self.input_request_dict[mode] = {} + + for token in token_list: + if token['exchangeType'] in self.input_request_dict[mode]: + self.input_request_dict[mode][token['exchangeType']].extend(token["tokens"]) + else: + self.input_request_dict[mode][token['exchangeType']] = token["tokens"] + self.wsapp.send(json.dumps(request_data)) + self.RESUBSCRIBE_FLAG = True + except Exception as e: + raise e + + def unsubscribe(self, correlation_id, mode, token_list): + """ + This function unsubscribe the data for given token + Parameters + ------ + correlation_id: string + A 10 character alphanumeric ID client may provide which will be returned by the server in error response + to indicate which request generated error response. + Clients can use this optional ID for tracking purposes between request and corresponding error response. + mode: integer + It denotes the subscription type + possible values -> 1, 2 and 3 + 1 -> LTP + 2 -> Quote + 3 -> Snap Quote + token_list: list of dict + Sample Value -> + [ + { "exchangeType": 1, "tokens": ["10626", "5290"]}, + {"exchangeType": 5, "tokens": [ "234230", "234235", "234219"]} + ] + exchangeType: integer + possible values -> + 1 -> nse_cm + 2 -> nse_fo + 3 -> bse_cm + 4 -> bse_fo + 5 -> mcx_fo + 7 -> ncx_fo + 13 -> cde_fo + tokens: list of string + """ + try: + request_data = { + "correlationID": correlation_id, + "action": self.UNSUBSCRIBE_ACTION, + "params": { + "mode": mode, + "tokenList": token_list + } + } + + self.input_request_dict.update(request_data) + self.input_request_dict.update(request_data) + self.wsapp.send(json.dumps(request_data)) + self.RESUBSCRIBE_FLAG = True + except Exception as e: + raise e + + def resubscribe(self): + try: + for key, val in self.input_request_dict.items(): + token_list = [] + for key1, val1 in val.items(): + temp_data = { + 'exchangeType': key1, + 'tokens': val1 + } + token_list.append(temp_data) + request_data = { + "action": self.SUBSCRIBE_ACTION, + "params": { + "mode": key, + "tokenList": token_list + } + } + self.wsapp.send(json.dumps(request_data)) + except Exception as e: + raise e + + + def connect(self): + """ + Make the web socket connection with the server + """ + headers = { + "Authorization": self.auth_token, + "x-api-key": self.api_key, + "x-client-code": self.client_code, + "x-feed-token": self.feed_token + } + # self.start_ping_timer() + try: + self.wsapp = websocket.WebSocketApp(self.ROOT_URI, header=headers, on_open=self._on_open, + on_error=self._on_error, on_close=self._on_close, on_data=self._on_data, + on_ping=self._on_ping, + on_pong=self._on_pong) + self.wsapp.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}, ping_interval=self.HEART_BEAT_INTERVAL, + ping_payload=self.HEART_BEAT_MESSAGE) + except Exception as e: + raise e + + + def close_connection(self): + """ + Closes the connection + """ + # print("Connection Closed") + self.RESUBSCRIBE_FLAG = False + self.DISCONNECT_FLAG = True + # self.HB_THREAD_FLAG = False + if self.wsapp: + self.wsapp.close() + + # def run(self): + # while True: + # if not self.HB_THREAD_FLAG: + # break + # self.send_heart_beat() + # time.sleep(self.HEAR_BEAT_INTERVAL) + + def send_heart_beat(self): + try: + self.wsapp.send(self.HEART_BEAT_MESSAGE) + except Exception as e: + raise e + + def _on_error(self, wsapp, error): + # self.HB_THREAD_FLAG = False + self.RESUBSCRIBE_FLAG = True + if self.current_retry_attempt < self.MAX_RETRY_ATTEMPT: + print("Attempting to resubscribe/reconnect...") + self.current_retry_attempt += 1 + try: + self.close_connection() + self.connect() + except Exception as e: + print("Error occurred during resubscribe/reconnect:", str(e)) + else: + print("Connection Close") + + def _on_close(self, wsapp): + # self.HB_THREAD_FLAG = False + # print(self.wsapp.close_frame) + self.on_close(wsapp) + + def _parse_binary_data(self, binary_data): + parsed_data = { + "subscription_mode": self._unpack_data(binary_data, 0, 1, byte_format="B")[0], + "exchange_type": self._unpack_data(binary_data, 1, 2, byte_format="B")[0], + "token": SmartWebSocketV2._parse_token_value(binary_data[2:27]), + "sequence_number": self._unpack_data(binary_data, 27, 35, byte_format="q")[0], + "exchange_timestamp": self._unpack_data(binary_data, 35, 43, byte_format="q")[0], + "last_traded_price": self._unpack_data(binary_data, 43, 51, byte_format="q")[0] + } + try: + parsed_data["subscription_mode_val"] = self.SUBSCRIPTION_MODE_MAP.get(parsed_data["subscription_mode"]) + + if parsed_data["subscription_mode"] in [self.QUOTE, self.SNAP_QUOTE]: + parsed_data["last_traded_quantity"] = self._unpack_data(binary_data, 51, 59, byte_format="q")[0] + parsed_data["average_traded_price"] = self._unpack_data(binary_data, 59, 67, byte_format="q")[0] + parsed_data["volume_trade_for_the_day"] = self._unpack_data(binary_data, 67, 75, byte_format="q")[0] + parsed_data["total_buy_quantity"] = self._unpack_data(binary_data, 75, 83, byte_format="d")[0] + parsed_data["total_sell_quantity"] = self._unpack_data(binary_data, 83, 91, byte_format="d")[0] + parsed_data["open_price_of_the_day"] = self._unpack_data(binary_data, 91, 99, byte_format="q")[0] + parsed_data["high_price_of_the_day"] = self._unpack_data(binary_data, 99, 107, byte_format="q")[0] + parsed_data["low_price_of_the_day"] = self._unpack_data(binary_data, 107, 115, byte_format="q")[0] + parsed_data["closed_price"] = self._unpack_data(binary_data, 115, 123, byte_format="q")[0] + + if parsed_data["subscription_mode"] == self.SNAP_QUOTE: + parsed_data["last_traded_timestamp"] = self._unpack_data(binary_data, 123, 131, byte_format="q")[0] + parsed_data["open_interest"] = self._unpack_data(binary_data, 131, 139, byte_format="q")[0] + parsed_data["open_interest_change_percentage"] = \ + self._unpack_data(binary_data, 139, 147, byte_format="q")[0] + parsed_data["upper_circuit_limit"] = self._unpack_data(binary_data, 347, 355, byte_format="q")[0] + parsed_data["lower_circuit_limit"] = self._unpack_data(binary_data, 355, 363, byte_format="q")[0] + parsed_data["52_week_high_price"] = self._unpack_data(binary_data, 363, 371, byte_format="q")[0] + parsed_data["52_week_low_price"] = self._unpack_data(binary_data, 371, 379, byte_format="q")[0] + best_5_buy_and_sell_data = self._parse_best_5_buy_and_sell_data(binary_data[147:347]) + parsed_data["best_5_buy_data"] = best_5_buy_and_sell_data["best_5_buy_data"] + parsed_data["best_5_sell_data"] = best_5_buy_and_sell_data["best_5_sell_data"] + + return parsed_data + except Exception as e: + raise e + + def _unpack_data(self, binary_data, start, end, byte_format="I"): + """ + Unpack Binary Data to the integer according to the specified byte_format. + This function returns the tuple + """ + return struct.unpack(self.LITTLE_ENDIAN_BYTE_ORDER + byte_format, binary_data[start:end]) + + @staticmethod + def _parse_token_value(binary_packet): + token = "" + for i in range(len(binary_packet)): + if chr(binary_packet[i]) == '\x00': + return token + token += chr(binary_packet[i]) + return token + + def _parse_best_5_buy_and_sell_data(self, binary_data): + + def split_packets(binary_packets): + packets = [] + + i = 0 + while i < len(binary_packets): + packets.append(binary_packets[i: i + 20]) + i += 20 + return packets + + best_5_buy_sell_packets = split_packets(binary_data) + + best_5_buy_data = [] + best_5_sell_data = [] + + for packet in best_5_buy_sell_packets: + each_data = { + "flag": self._unpack_data(packet, 0, 2, byte_format="H")[0], + "quantity": self._unpack_data(packet, 2, 10, byte_format="q")[0], + "price": self._unpack_data(packet, 10, 18, byte_format="q")[0], + "no of orders": self._unpack_data(packet, 18, 20, byte_format="H")[0] + } + + if each_data["flag"] == 0: + best_5_buy_data.append(each_data) + else: + best_5_sell_data.append(each_data) + + return { + "best_5_buy_data": best_5_buy_data, + "best_5_sell_data": best_5_sell_data + } + + # def on_message(self, wsapp, message): + # print(message) + + def on_data(self, wsapp, data): + pass + + def on_close(self, wsapp): + pass + + def on_open(self, wsapp): + pass + + def on_error(self): + pass \ No newline at end of file From 87ca4817c6297971f5afddacfc6905d17a9738fc Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Tue, 6 Jun 2023 10:27:56 +0530 Subject: [PATCH 10/46] Update smartWebSocketV2.py --- SmartApi/smartWebSocketV2.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/SmartApi/smartWebSocketV2.py b/SmartApi/smartWebSocketV2.py index 07a52698..e76a9430 100644 --- a/SmartApi/smartWebSocketV2.py +++ b/SmartApi/smartWebSocketV2.py @@ -326,6 +326,7 @@ def _on_error(self, wsapp, error): print("Error occurred during resubscribe/reconnect:", str(e)) else: print("Connection Close") + self.close_connection() def _on_close(self, wsapp): # self.HB_THREAD_FLAG = False @@ -435,4 +436,4 @@ def on_open(self, wsapp): pass def on_error(self): - pass \ No newline at end of file + pass From 85cc9addf5b8890f2bae25a1fc07098f4da185a5 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 8 Jun 2023 11:00:28 +0530 Subject: [PATCH 11/46] Update smartWebSocketV2.py --- SmartApi/smartWebSocketV2.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SmartApi/smartWebSocketV2.py b/SmartApi/smartWebSocketV2.py index e76a9430..444e5fc6 100644 --- a/SmartApi/smartWebSocketV2.py +++ b/SmartApi/smartWebSocketV2.py @@ -18,7 +18,6 @@ class SmartWebSocketV2(object): LITTLE_ENDIAN_BYTE_ORDER = "<" RESUBSCRIBE_FLAG = False # HB_THREAD_FLAG = True - MAX_RETRY_ATTEMPT = 1 # Available Actions SUBSCRIBE_ACTION = 1 @@ -49,7 +48,7 @@ class SmartWebSocketV2(object): input_request_dict = {} current_retry_attempt = 0 - def __init__(self, auth_token, api_key, client_code, feed_token): + def __init__(self, auth_token, api_key, client_code, feed_token, max_retry_attempt=1): """ Initialise the SmartWebSocketV2 instance Parameters @@ -69,6 +68,7 @@ def __init__(self, auth_token, api_key, client_code, feed_token): self.feed_token = feed_token self.DISCONNECT_FLAG = True self.last_pong_timestamp = None + self.MAX_RETRY_ATTEMPT = max_retry_attempt if not self._sanity_check(): raise Exception("Provide valid value for all the tokens") From 9a49cfad074b00fea2456bab888575e50b9b8a60 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 8 Jun 2023 11:42:45 +0530 Subject: [PATCH 12/46] Update smartWebSocketV2.py --- SmartApi/smartWebSocketV2.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/SmartApi/smartWebSocketV2.py b/SmartApi/smartWebSocketV2.py index 444e5fc6..dd3716fe 100644 --- a/SmartApi/smartWebSocketV2.py +++ b/SmartApi/smartWebSocketV2.py @@ -135,11 +135,11 @@ def send_ping(): "WebSocket connection is already closed. Disconnecting WebSocket and attempting to resubscribe...") self.resubscribe() except Exception as e: - print(f"Error occurred: {str(e)}. Disconnecting WebSocket and attempting to resubscribe...") + #print(f"Error occurred: {str(e)}. Disconnecting WebSocket and attempting to resubscribe...") self.wsapp.close() self.resubscribe() - ping_timer = Timer(10, send_ping) # Send a ping every 10 seconds + ping_timer = Timer(10, send_ping) # Send timer every 10 seconds ping_timer.start() def subscribe(self, correlation_id, mode, token_list): @@ -277,7 +277,7 @@ def connect(self): "x-client-code": self.client_code, "x-feed-token": self.feed_token } - # self.start_ping_timer() + try: self.wsapp = websocket.WebSocketApp(self.ROOT_URI, header=headers, on_open=self._on_open, on_error=self._on_error, on_close=self._on_close, on_data=self._on_data, @@ -285,6 +285,7 @@ def connect(self): on_pong=self._on_pong) self.wsapp.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}, ping_interval=self.HEART_BEAT_INTERVAL, ping_payload=self.HEART_BEAT_MESSAGE) + # self.start_ping_timer() except Exception as e: raise e From 6e8958c0e817dc3c688714d17c7c48e1337fa5e2 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 22 Jun 2023 18:02:22 +0530 Subject: [PATCH 13/46] Update smartWebSocketV2.py --- SmartApi/smartWebSocketV2.py | 37 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/SmartApi/smartWebSocketV2.py b/SmartApi/smartWebSocketV2.py index dd3716fe..d6b6c90d 100644 --- a/SmartApi/smartWebSocketV2.py +++ b/SmartApi/smartWebSocketV2.py @@ -7,6 +7,7 @@ from datetime import datetime, timedelta from threading import Timer + class SmartWebSocketV2(object): """ SmartAPI Web Socket version 2 @@ -14,7 +15,7 @@ class SmartWebSocketV2(object): ROOT_URI = "ws://smartapisocket.angelone.in/smart-stream" HEART_BEAT_MESSAGE = "ping" - HEART_BEAT_INTERVAL = 10 # Adjusted to 10s + HEART_BEAT_INTERVAL = 10 # Adjusted to 10s LITTLE_ENDIAN_BYTE_ORDER = "<" RESUBSCRIBE_FLAG = False # HB_THREAD_FLAG = True @@ -118,28 +119,28 @@ def _on_ping(self, wsapp, data): print(f"In on ping function ==> {data}, Timestamp: {formatted_timestamp}") self.last_ping_timestamp = timestamp + def check_connection_status(self): + current_time = time.time() + if self.last_pong_timestamp is not None and current_time - self.last_pong_timestamp > 2*self.HEART_BEAT_MESSAGE: + # Stale connection detected, take appropriate action + self.close_connection() + self.connect() + def start_ping_timer(self): def send_ping(): try: current_time = datetime.now() - if self.last_pong_timestamp is None or self.last_pong_timestamp < current_time - timedelta(seconds=20): - print("No pong response received. Disconnecting WebSocket and attempting to resubscribe...") - self.wsapp.close() + if self.last_pong_timestamp is None or self.last_pong_timestamp < current_time - timedelta(self.HEART_BEAT_MESSAGE): + # print("stale connection detected") + # self.wsapp.close() self.connect() else: self.last_ping_timestamp = time.time() - try: - self.wsapp.send(self.HEART_BEAT_MESSAGE) - except WebSocketConnectionClosedException: - print( - "WebSocket connection is already closed. Disconnecting WebSocket and attempting to resubscribe...") - self.resubscribe() except Exception as e: - #print(f"Error occurred: {str(e)}. Disconnecting WebSocket and attempting to resubscribe...") self.wsapp.close() self.resubscribe() - ping_timer = Timer(10, send_ping) # Send timer every 10 seconds + ping_timer = Timer(5, send_ping) ping_timer.start() def subscribe(self, correlation_id, mode, token_list): @@ -266,7 +267,6 @@ def resubscribe(self): except Exception as e: raise e - def connect(self): """ Make the web socket connection with the server @@ -277,7 +277,7 @@ def connect(self): "x-client-code": self.client_code, "x-feed-token": self.feed_token } - + try: self.wsapp = websocket.WebSocketApp(self.ROOT_URI, header=headers, on_open=self._on_open, on_error=self._on_error, on_close=self._on_close, on_data=self._on_data, @@ -289,12 +289,10 @@ def connect(self): except Exception as e: raise e - def close_connection(self): """ Closes the connection """ - # print("Connection Closed") self.RESUBSCRIBE_FLAG = False self.DISCONNECT_FLAG = True # self.HB_THREAD_FLAG = False @@ -326,7 +324,6 @@ def _on_error(self, wsapp, error): except Exception as e: print("Error occurred during resubscribe/reconnect:", str(e)) else: - print("Connection Close") self.close_connection() def _on_close(self, wsapp): @@ -367,8 +364,8 @@ def _parse_binary_data(self, binary_data): parsed_data["52_week_high_price"] = self._unpack_data(binary_data, 363, 371, byte_format="q")[0] parsed_data["52_week_low_price"] = self._unpack_data(binary_data, 371, 379, byte_format="q")[0] best_5_buy_and_sell_data = self._parse_best_5_buy_and_sell_data(binary_data[147:347]) - parsed_data["best_5_buy_data"] = best_5_buy_and_sell_data["best_5_buy_data"] - parsed_data["best_5_sell_data"] = best_5_buy_and_sell_data["best_5_sell_data"] + parsed_data["best_5_buy_data"] = best_5_buy_and_sell_data["best_5_sell_data"] + parsed_data["best_5_sell_data"] = best_5_buy_and_sell_data["best_5_buy_data"] return parsed_data except Exception as e: @@ -431,7 +428,7 @@ def on_data(self, wsapp, data): pass def on_close(self, wsapp): - pass + pass def on_open(self, wsapp): pass From 6322b086ed0de13ee8580560c0dda592de1bdf0a Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 16:53:02 +0530 Subject: [PATCH 14/46] Update smartConnect.py --- SmartApi/smartConnect.py | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/SmartApi/smartConnect.py b/SmartApi/smartConnect.py index c8f65a89..3418c289 100644 --- a/SmartApi/smartConnect.py +++ b/SmartApi/smartConnect.py @@ -222,30 +222,31 @@ def _getRequest(self, route, params=None): """Alias for sending a GET request.""" return self._request(route, "GET", params) - def generateSession(self,clientCode,password): - - params={"clientcode":clientCode,"password":password} - loginResultObject=self._postRequest("api.login",params) - - if loginResultObject['status']==True: - jwtToken=loginResultObject['data']['jwtToken'] + def generateSession(self, clientCode, password, totp): + + params = {"clientcode": clientCode, "password": password, "totp": totp} + loginResultObject = self._postRequest("api.login", params) + + if loginResultObject['status'] == True: + jwtToken = loginResultObject['data']['jwtToken'] self.setAccessToken(jwtToken) - refreshToken=loginResultObject['data']['refreshToken'] - feedToken=loginResultObject['data']['feedToken'] + refreshToken = loginResultObject['data']['refreshToken'] + feedToken = loginResultObject['data']['feedToken'] self.setRefreshToken(refreshToken) self.setFeedToken(feedToken) - user=self.getProfile(refreshToken) - - id=user['data']['clientcode'] - #id='D88311' + user = self.getProfile(refreshToken) + + id = user['data']['clientcode'] + # id='D88311' self.setUserId(id) - user['data']['jwtToken']="Bearer "+jwtToken - user['data']['refreshToken']=refreshToken + user['data']['jwtToken'] = "Bearer " + jwtToken + user['data']['refreshToken'] = refreshToken + user['data']['feedToken'] = feedToken - return user else: return loginResultObject + def terminateSession(self,clientCode): logoutResponseObject=self._postRequest("api.logout",{"clientcode":clientCode}) return logoutResponseObject From 8a22a73e0426554e4925af1a7fdb53cf6b883503 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 16:53:32 +0530 Subject: [PATCH 15/46] Update smartConnect.py --- SmartApi/smartConnect.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/SmartApi/smartConnect.py b/SmartApi/smartConnect.py index 3418c289..5654e515 100644 --- a/SmartApi/smartConnect.py +++ b/SmartApi/smartConnect.py @@ -1,18 +1,12 @@ from six.moves.urllib.parse import urljoin -import sys -import csv import json -import dateutil.parser -import hashlib import logging -import datetime -import smartapi.smartExceptions as ex +import SmartApi.smartExceptions as ex import requests from requests import get import re, uuid import socket -import platform -from smartapi.version import __version__, __title__ +from SmartApi.version import __version__, __title__ log = logging.getLogger(__name__) #user_sys=platform.system() From 0c0a7884386bb1f456e97fbb37de00f1048e1986 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 16:57:10 +0530 Subject: [PATCH 16/46] Update sample.py --- example/sample.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/example/sample.py b/example/sample.py index 9aca4354..f9287b7c 100644 --- a/example/sample.py +++ b/example/sample.py @@ -1,5 +1,6 @@ # package import statement -from smartapi import SmartConnect #or from smartapi.smartConnect import SmartConnect +from SmartApi import SmartConnect #or from smartapi.smartConnect import SmartConnect + #import smartapi.smartExceptions(for smartExceptions) #create object of call @@ -7,7 +8,7 @@ #login api call -data = obj.generateSession("Your Client ID","Your Password") +data = obj.generateSession("Your Client ID","Your Password","Your totp") refreshToken= data['data']['refreshToken'] #fetch the feedtoken @@ -85,7 +86,8 @@ ## WebSocket -from smartapi import WebSocket + +from SmartApi.webSocket import WebSocket FEED_TOKEN= "your feed token" CLIENT_CODE="your client Id" From a5734f9897d6e55443e16d5fc6995dee104c33db Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 16:58:11 +0530 Subject: [PATCH 17/46] Add files via upload --- example/smartwebsocketexamplev2.py | 57 ++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 example/smartwebsocketexamplev2.py diff --git a/example/smartwebsocketexamplev2.py b/example/smartwebsocketexamplev2.py new file mode 100644 index 00000000..a5518b9f --- /dev/null +++ b/example/smartwebsocketexamplev2.py @@ -0,0 +1,57 @@ +from SmartApi.smartWebSocketV2 import SmartWebSocketV2 +from logzero import logger + +AUTH_TOKEN = "authToken" +API_KEY = "api_key" +CLIENT_CODE = "client code" +FEED_TOKEN = "feedToken" +correlation_id = "abc123" +action = 1 +mode = 1 + +token_list = [ + { + "exchangeType": 1, + "tokens": ["26009"] + } +] +token_list1 = [ + { + "action": 0, + "exchangeType": 1, + "tokens": ["26009"] + } +] + +sws = SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN) + +def on_data(wsapp, message): + logger.info("Ticks: {}".format(message)) + # close_connection() + +def on_open(wsapp): + logger.info("on open") + sws.subscribe(correlation_id, mode, token_list) + # sws.unsubscribe(correlation_id, mode, token_list1) + + +def on_error(wsapp, error): + logger.error(error) + + +def on_close(wsapp): + logger.info("Close") + + + +def close_connection(): + sws.close_connection() + + +# Assign the callbacks. +sws.on_open = on_open +sws.on_data = on_data +sws.on_error = on_error +sws.on_close = on_close + +sws.connect() From deed85801421c66dc9003b3e4db3b609c89b7216 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 16:59:44 +0530 Subject: [PATCH 18/46] Update test.py --- test/test.py | 248 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 152 insertions(+), 96 deletions(-) diff --git a/test/test.py b/test/test.py index 57267d6f..e6232473 100644 --- a/test/test.py +++ b/test/test.py @@ -1,21 +1,25 @@ -from smartapi import SmartConnect - -#---------for smartExceptions--------- -#import smartapi.smartExceptions -#or -#from smartapi import smartExceptions - -smartApi =SmartConnect(api_key="Your Api Key") - -login = smartApi.generateSession('Your Client Id', 'Your Password') - -refreshToken = login['data']['refreshToken'] - +from logzero import logger +from SmartApi.smartConnect import SmartConnect +import pyotp + +api_key = 'Your Api Key' +username = 'Your client code' +pwd = 'Your pin' +smartApi = SmartConnect(api_key) +token = "Your QR value" +totp=pyotp.TOTP(token).now() +correlation_id = "abcde" +data = smartApi.generateSession(username, pwd, totp) +# print(data) +authToken = data['data']['jwtToken'] +refreshToken = data['data']['refreshToken'] feedToken = smartApi.getfeedToken() - -smartApi.getProfile(refreshToken) - +# print("Feed-Token :", feedToken) +res = smartApi.getProfile(refreshToken) +# print("Res:", res) smartApi.generateToken(refreshToken) +res=res['data']['exchanges'] + orderparams = { "variety": "NORMAL", @@ -32,6 +36,7 @@ "quantity": "1" } orderid = smartApi.placeOrder(orderparams) +print("PlaceOrder", orderid) modifyparams = { "variety": "NORMAL", @@ -41,106 +46,157 @@ "duration": "DAY", "price": "19500", "quantity": "1", - "tradingsymbol":"SBIN-EQ", - "symboltoken":"3045", - "exchange":"NSE" + "tradingsymbol": "SBIN-EQ", + "symboltoken": "3045", + "exchange": "NSE" } smartApi.modifyOrder(modifyparams) +print("Modify Orders:",modifyparams) smartApi.cancelOrder(orderid, "NORMAL") -smartApi.orderBook() +orderbook=smartApi.orderBook() +print("Order Book :", orderbook) -smartApi.tradeBook() +tradebook=smartApi.tradeBook() +print("Trade Book :",tradebook) -smartApi.rmsLimit() +rmslimit=smartApi.rmsLimit() +print("RMS Limit :", rmslimit) -smartApi.position() +pos=smartApi.position() +print("Position :", pos) -smartApi.holding() +holdings=smartApi.holding() +print("Holdings :", holdings) exchange = "NSE" tradingsymbol = "SBIN-EQ" symboltoken = 3045 -smartApi.ltpData("NSE", "SBIN-EQ", "3045") +ltp=smartApi.ltpData("NSE", "SBIN-EQ", "3045") +print("Ltp Data :", ltp) + -params={ +params = { "exchange": "NSE", - "oldproducttype":"DELIVERY", + "oldproducttype": "DELIVERY", "newproducttype": "MARGIN", "tradingsymbol": "SBIN-EQ", - "transactiontype":"BUY", - "quantity":1, - "type":"DAY" + "transactiontype": "BUY", + "quantity": 1, + "type": "DAY" } -smartApi.convertPosition(params) -gttCreateParams={ - "tradingsymbol" : "SBIN-EQ", - "symboltoken" : "3045", - "exchange" : "NSE", - "producttype" : "MARGIN", - "transactiontype" : "BUY", - "price" : 100000, - "qty" : 10, - "disclosedqty": 10, - "triggerprice" : 200000, - "timeperiod" : 365 - } -rule_id=smartApi.gttCreateRule(gttCreateParams) - -gttModifyParams={ - "id": rule_id, - "symboltoken":"3045", - "exchange":"NSE", - "price":19500, - "quantity":10, - "triggerprice":200000, - "disclosedqty":10, - "timeperiod":365 - } -modified_id=smartApi.gttModifyRule(gttModifyParams) - -cancelParams={ - "id": rule_id, - "symboltoken":"3045", - "exchange":"NSE" - } - -cancelled_id=smartApi.gttCancelRule(cancelParams) - -smartApi.gttDetails(rule_id) - -smartApi.gttLists('List of status','','') - -smartApi.terminateSession('Your Client Id') - -## Websocket Programming - -from smartapi import WebSocket -import multiprocessing -import sys -FEED_TOKEN=feedToken -CLIENT_CODE="Your Client Id" -token=None -task=None -ss = WebSocket(FEED_TOKEN, CLIENT_CODE) -def on_tick(ws, tick): - print("Ticks: {}".format(tick)) - -def on_connect(ws, response): - ws.websocket_connection() - ws.send_request(token,task) - -def on_close(ws, code, reason): - ws.stop() +convertposition=smartApi.convertPosition(params) + +gttCreateParams = { + "tradingsymbol": "SBIN-EQ", + "symboltoken": "3045", + "exchange": "NSE", + "producttype": "MARGIN", + "transactiontype": "BUY", + "price": 100000, + "qty": 10, + "disclosedqty": 10, + "triggerprice": 200000, + "timeperiod": 365 +} +rule_id = smartApi.gttCreateRule(gttCreateParams) +print("Gtt Rule :", rule_id) + +gttModifyParams = { + "id": rule_id, + "symboltoken": "3045", + "exchange": "NSE", + "price": 19500, + "quantity": 10, + "triggerprice": 200000, + "disclosedqty": 10, + "timeperiod": 365 +} +modified_id = smartApi.gttModifyRule(gttModifyParams) +print("Gtt Modified Rule :", modified_id) + +cancelParams = { + "id": rule_id, + "symboltoken": "3045", + "exchange": "NSE" +} + +cancelled_id = smartApi.gttCancelRule(cancelParams) +print("gtt Cancel Rule :", cancelled_id) + +gttdetails=smartApi.gttDetails(rule_id) +print("GTT Details",gttdetails) + +smartApi.gttLists('List of status', '', '') + +candleParams={ + "exchange": "NSE", + "symboltoken": "3045", + "interval": "ONE_MINUTE", + "fromdate": "2021-02-10 09:15", + "todate": "2021-02-10 09:16" +} +candledetails=smartApi.getCandleData(candleParams) +print("Historical Data",candledetails) + +terminate=smartApi.terminateSession('Your client code') +print("Connection Close",terminate) + +# # Websocket Programming + +from SmartApi.smartWebSocketV2 import SmartWebSocketV2 + +AUTH_TOKEN = authToken +API_KEY = api_key +CLIENT_CODE = username +FEED_TOKEN = feedToken +# correlation_id = "abc123" +action = 1 +mode = 1 + +token_list = [ + { + "exchangeType": 1, + "tokens": ["26009","1594"] + } +] +token_list1 = [ + { + "action": 0, + "exchangeType": 1, + "tokens": ["26009"] + } +] + +sws = SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN) + +def on_data(wsapp, message): + logger.info("Ticks: {}".format(message)) + close_connection() + +def on_open(wsapp): + logger.info("on open") + sws.subscribe(correlation_id, mode, token_list) + # sws.unsubscribe(correlation_id, mode, token_list1) + + +def on_error(wsapp, error): + logger.error(error) + +def on_close(wsapp): + logger.info("Close") + +def close_connection(): + sws.close_connection() + # Assign the callbacks. -ss.on_ticks = on_tick -ss.on_connect = on_connect -ss.on_close = on_close +sws.on_open = on_open +sws.on_data = on_data +sws.on_error = on_error +sws.on_close = on_close -p1 = multiprocessing.Process(target = ss.connect()) -sys.exit() -p1.start() \ No newline at end of file +sws.connect() From 2cba8c7226ac0d12a39aeeca25bd1f21101a9ff5 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 17:15:12 +0530 Subject: [PATCH 19/46] Update setup.py --- setup.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 88e19084..92925d01 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,3 @@ - from setuptools import setup, find_packages about={} @@ -13,7 +12,7 @@ setup( name="smartapi-python", - version="1.2.8", + version="1.2.9", author="ab-smartapi", author_email="smartapi.sdk@gmail.com", description="Angel Broking openApi integration", @@ -36,4 +35,4 @@ "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Libraries" ], -) \ No newline at end of file +) From c5bb22e2edfe9227d2137dce2e551e85af0884b3 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 17:15:33 +0530 Subject: [PATCH 20/46] Update requirements_dev.txt --- requirements_dev.txt | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/requirements_dev.txt b/requirements_dev.txt index 84c6643f..4b11c052 100644 --- a/requirements_dev.txt +++ b/requirements_dev.txt @@ -1,2 +1,32 @@ -requests>=2.24.0 -twine>=1.13.0 +attrs==23.1.0 +autobahn==23.6.2 +Automat==22.10.0 +certifi==2023.5.7 +cffi==1.15.1 +charset-normalizer==3.1.0 +constantly==15.1.0 +cryptography==41.0.1 +hyperlink==21.0.0 +idna==3.4 +incremental==22.10.0 +isodate==0.6.1 +logzero==1.7.0 +pycparser==2.21 +pycrypto==2.6.1 +pyotp==2.8.0 +pyparsing==3.1.0 +python-dateutil==2.8.2 +pytz==2023.3 +rdflib==6.3.2 +rdflib-jsonld==0.6.2 +requests==2.31.0 +simplejson==3.19.1 +six==1.16.0 +smartapi-python==1.3.0 +Twisted==22.10.0 +txaio==23.1.1 +typing_extensions==4.6.3 +urllib3==2.0.3 +websocket-client==1.6.0 +zope.interface==6.0 + From cb42b5c2dd53d2cc35b2934ca04b8a43aa07c025 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 17:16:40 +0530 Subject: [PATCH 21/46] Update README.md --- README.md | 208 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 206 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4ded8eb6..b4f53b43 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,207 @@ -# Migrated to New Github Repo https://github.com/angel-one/smartapi-python -For latest updates and bug fixes please refer to the new git repo. +# SMARTAPI-PYTHON + +SMARTAPI-PYTHON is a Python library for dealing AMX,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time. + + + +## Installation + +Use the package manager [pip](https://pip.pypa.io/en/stable/) to install smartapi-python. + +```bash +pip install smartapi-python +pip install websocket-client +``` + +## Usage + +```python +# package import statement +from SmartApi import SmartConnect #or from SmartApi.smartConnect import SmartConnect +import pyotp + +api_key = 'Your Api Key' +clientId = 'Your Client Id' +pwd = 'Your Pin' +smartApi = SmartConnect(api_key) +token = "Your QR code value" +totp=pyotp.TOTP(token).now() +correlation_id = "abc123" + +# login api call + +data = smartApi.generateSession(clientId, pwd, totp) +# print(data) +authToken = data['data']['jwtToken'] +refreshToken = data['data']['refreshToken'] + +# fetch the feedtoken +feedToken = smartApi.getfeedToken() + +# fetch User Profile +res = smartApi.getProfile(refreshToken) +smartApi.generateToken(refreshToken) +res=res['data']['exchanges'] + + +#place order +try: + orderparams = { + "variety": "NORMAL", + "tradingsymbol": "SBIN-EQ", + "symboltoken": "3045", + "transactiontype": "BUY", + "exchange": "NSE", + "ordertype": "LIMIT", + "producttype": "INTRADAY", + "duration": "DAY", + "price": "19500", + "squareoff": "0", + "stoploss": "0", + "quantity": "1" + } + orderId=smartApi.placeOrder(orderparams) + print("The order id is: {}".format(orderId)) +except Exception as e: + print("Order placement failed: {}".format(e.message)) +#gtt rule creation +try: + gttCreateParams={ + "tradingsymbol" : "SBIN-EQ", + "symboltoken" : "3045", + "exchange" : "NSE", + "producttype" : "MARGIN", + "transactiontype" : "BUY", + "price" : 100000, + "qty" : 10, + "disclosedqty": 10, + "triggerprice" : 200000, + "timeperiod" : 365 + } + rule_id=smartApi.gttCreateRule(gttCreateParams) + print("The GTT rule id is: {}".format(rule_id)) +except Exception as e: + print("GTT Rule creation failed: {}".format(e.message)) + +#gtt rule list +try: + status=["FORALL"] #should be a list + page=1 + count=10 + lists=smartApi.gttLists(status,page,count) +except Exception as e: + print("GTT Rule List failed: {}".format(e.message)) + +#Historic api +try: + historicParam={ + "exchange": "NSE", + "symboltoken": "3045", + "interval": "ONE_MINUTE", + "fromdate": "2021-02-08 09:00", + "todate": "2021-02-08 09:16" + } + smartApi.getCandleData(historicParam) +except Exception as e: + print("Historic Api failed: {}".format(e.message)) +#logout +try: + logout=smartApi.terminateSession('Your Client Id') + print("Logout Successfull") +except Exception as e: + print("Logout failed: {}".format(e.message)) + +``` + + +## Getting started with SmartAPI Websocket's + +```python + +from SmartApi import SmartWebSocket + +# feed_token=092017047 +FEED_TOKEN="YOUR_FEED_TOKEN" +CLIENT_CODE="YOUR_CLIENT_CODE" +# token="mcx_fo|224395" +token="EXCHANGE|TOKEN_SYMBOL" #SAMPLE: nse_cm|2885&nse_cm|1594&nse_cm|11536&nse_cm|3045 +# token="mcx_fo|226745&mcx_fo|220822&mcx_fo|227182&mcx_fo|221599" +task="mw" # mw|sfi|dp + +ss = SmartWebSocket(FEED_TOKEN, CLIENT_CODE) + +def on_message(ws, message): + print("Ticks: {}".format(message)) + +def on_open(ws): + print("on open") + ss.subscribe(task,token) + +def on_error(ws, error): + print(error) + +def on_close(ws): + print("Close") + +# Assign the callbacks. +ss._on_open = on_open +ss._on_message = on_message +ss._on_error = on_error +ss._on_close = on_close + +ss.connect() + + +####### Websocket sample code ended here ####### + +####### Websocket V2 sample code ####### + +from SmartApi.smartWebSocketV2 import SmartWebSocketV2 +from logzero import logger + +AUTH_TOKEN = "Your Auth_Token" +API_KEY = "Your Api_Key" +CLIENT_CODE = "Your Client Code" +FEED_TOKEN = "Your Feed_Token" +correlation_id = "abc123" +action = 1 +mode = 1 +token_list = [ + { + "exchangeType": 1, + "tokens": ["26009"] + } +] +sws = SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN) + +def on_data(wsapp, message): + logger.info("Ticks: {}".format(message)) + # close_connection() + +def on_open(wsapp): + logger.info("on open") + sws.subscribe(correlation_id, mode, token_list) + +def on_error(wsapp, error): + logger.error(error) + +def on_close(wsapp): + logger.info("Close") + +def close_connection(): + sws.close_connection() + + +# Assign the callbacks. +sws.on_open = on_open +sws.on_data = on_data +sws.on_error = on_error +sws.on_close = on_close + +sws.connect() + + +``` + + From 73dbe883247d1a05603906253564d129a9d73c65 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 17:26:21 +0530 Subject: [PATCH 22/46] Update smartConnect.py --- SmartApi/smartConnect.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SmartApi/smartConnect.py b/SmartApi/smartConnect.py index 5654e515..f05cb657 100644 --- a/SmartApi/smartConnect.py +++ b/SmartApi/smartConnect.py @@ -216,7 +216,7 @@ def _getRequest(self, route, params=None): """Alias for sending a GET request.""" return self._request(route, "GET", params) - def generateSession(self, clientCode, password, totp): + def generateSession(self, clientCode, password, totp): params = {"clientcode": clientCode, "password": password, "totp": totp} loginResultObject = self._postRequest("api.login", params) From 710bca6addc03aa47e88e2c887969fbae08e50bf Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 17:28:14 +0530 Subject: [PATCH 23/46] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b4f53b43..d4e0d35b 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ SMARTAPI-PYTHON is a Python library for dealing AMX,that is a set of REST-like H Use the package manager [pip](https://pip.pypa.io/en/stable/) to install smartapi-python. ```bash +pip install -r requirements_dev.txt # for downloading the other required packages pip install smartapi-python pip install websocket-client ``` From 638d4571ae2ce5277dcac3499c900f67c22e23c8 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 28 Jun 2023 17:51:51 +0530 Subject: [PATCH 24/46] Update __init__.py --- SmartApi/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SmartApi/__init__.py b/SmartApi/__init__.py index 720c8164..8e9ecc04 100644 --- a/SmartApi/__init__.py +++ b/SmartApi/__init__.py @@ -1,8 +1,8 @@ from __future__ import unicode_literals,absolute_import -from smartapi.smartConnect import SmartConnect -# from smartapi.webSocket import WebSocket -from smartapi.smartApiWebsocket import SmartWebSocket +from SmartApi.smartConnect import SmartConnect +# from SmartApi.webSocket import WebSocket +from SmartApi.smartApiWebsocket import SmartWebSocket __all__ = ["SmartConnect","SmartWebSocket"] From 42815a427144dd860a17f35bc6b076e1fd8b295e Mon Sep 17 00:00:00 2001 From: ajha1991 <108059707+ajha1991@users.noreply.github.com> Date: Wed, 28 Jun 2023 18:53:08 +0530 Subject: [PATCH 25/46] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d4e0d35b..d2bc7007 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # SMARTAPI-PYTHON -SMARTAPI-PYTHON is a Python library for dealing AMX,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time. +SMARTAPI-PYTHON is a Python library for interacting with Angel's Trading platform ,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time. From 5597275d30941ac1c3039933dca4070f27e25ed3 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 29 Jun 2023 11:05:18 +0530 Subject: [PATCH 26/46] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index d2bc7007..85e73fec 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,6 @@ SMARTAPI-PYTHON is a Python library for interacting with Angel's Trading platform ,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time. - ## Installation Use the package manager [pip](https://pip.pypa.io/en/stable/) to install smartapi-python. From 5d581c674158732e757ee8cc867f97fe8a207e9c Mon Sep 17 00:00:00 2001 From: rimagiri Date: Thu, 29 Jun 2023 18:12:43 +0530 Subject: [PATCH 27/46] Test --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 85e73fec..e1cf302e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # SMARTAPI-PYTHON -SMARTAPI-PYTHON is a Python library for interacting with Angel's Trading platform ,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time. +SMARTAPI-PYTHON is a Python library for interacting with Angel's Trading platform ,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time.. ## Installation From 27f5b2791eec7a3a31fbb5612c208d69e6b45d6e Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Fri, 30 Jun 2023 10:06:39 +0530 Subject: [PATCH 28/46] Update README.md --- README.md | 65 ------------------------------------------------------- 1 file changed, 65 deletions(-) diff --git a/README.md b/README.md index dac2d059..2fcf5daa 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,14 @@ # SMARTAPI-PYTHON -<<<<<<< HEAD SMARTAPI-PYTHON is a Python library for interacting with Angel's Trading platform ,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time.. -======= -SMARTAPI-PYTHON is a Python library for dealing AMX,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time. ->>>>>>> upstream/main ## Installation Use the package manager [pip](https://pip.pypa.io/en/stable/) to install smartapi-python. ```bash -<<<<<<< HEAD pip install -r requirements_dev.txt # for downloading the other required packages -======= ->>>>>>> upstream/main pip install smartapi-python pip install websocket-client ``` @@ -24,7 +17,6 @@ pip install websocket-client ```python # package import statement -<<<<<<< HEAD from SmartApi import SmartConnect #or from SmartApi.smartConnect import SmartConnect import pyotp @@ -51,28 +43,6 @@ res = smartApi.getProfile(refreshToken) smartApi.generateToken(refreshToken) res=res['data']['exchanges'] - -======= -from smartapi import SmartConnect #or from smartapi.smartConnect import SmartConnect -#import smartapi.smartExceptions(for smartExceptions) - -#create object of call -obj=SmartConnect(api_key="your api key", - #optional - #access_token = "your access token", - #refresh_token = "your refresh_token") - -#login api call - -data = obj.generateSession("Your Client ID","Your Password","Your totp") -refreshToken= data['data']['refreshToken'] - -#fetch the feedtoken -feedToken=obj.getfeedToken() - -#fetch User Profile -userProfile= obj.getProfile(refreshToken) ->>>>>>> upstream/main #place order try: orderparams = { @@ -89,11 +59,7 @@ try: "stoploss": "0", "quantity": "1" } -<<<<<<< HEAD orderId=smartApi.placeOrder(orderparams) -======= - orderId=obj.placeOrder(orderparams) ->>>>>>> upstream/main print("The order id is: {}".format(orderId)) except Exception as e: print("Order placement failed: {}".format(e.message)) @@ -111,11 +77,7 @@ try: "triggerprice" : 200000, "timeperiod" : 365 } -<<<<<<< HEAD rule_id=smartApi.gttCreateRule(gttCreateParams) -======= - rule_id=obj.gttCreateRule(gttCreateParams) ->>>>>>> upstream/main print("The GTT rule id is: {}".format(rule_id)) except Exception as e: print("GTT Rule creation failed: {}".format(e.message)) @@ -125,11 +87,7 @@ try: status=["FORALL"] #should be a list page=1 count=10 -<<<<<<< HEAD lists=smartApi.gttLists(status,page,count) -======= - lists=obj.gttLists(status,page,count) ->>>>>>> upstream/main except Exception as e: print("GTT Rule List failed: {}".format(e.message)) @@ -142,41 +100,24 @@ try: "fromdate": "2021-02-08 09:00", "todate": "2021-02-08 09:16" } -<<<<<<< HEAD smartApi.getCandleData(historicParam) -======= - obj.getCandleData(historicParam) ->>>>>>> upstream/main except Exception as e: print("Historic Api failed: {}".format(e.message)) #logout try: -<<<<<<< HEAD logout=smartApi.terminateSession('Your Client Id') print("Logout Successfull") except Exception as e: print("Logout failed: {}".format(e.message)) -======= - logout=obj.terminateSession('Your Client Id') - print("Logout Successfull") -except Exception as e: - print("Logout failed: {}".format(e.message)) ->>>>>>> upstream/main ``` ## Getting started with SmartAPI Websocket's -<<<<<<< HEAD ```python from SmartApi import SmartWebSocket -======= -```python - -from smartapi import SmartWebSocket ->>>>>>> upstream/main # feed_token=092017047 FEED_TOKEN="YOUR_FEED_TOKEN" @@ -208,7 +149,6 @@ ss._on_error = on_error ss._on_close = on_close ss.connect() -<<<<<<< HEAD ####### Websocket sample code ended here ####### @@ -259,11 +199,6 @@ sws.on_close = on_close sws.connect() - -``` - - -======= ``` From 7af07aca6872f0956fd6e5943dc4f2c4d8884ec3 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Fri, 30 Jun 2023 10:07:38 +0530 Subject: [PATCH 29/46] Update README.md --- README.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/README.md b/README.md index 2fcf5daa..6ca796fe 100644 --- a/README.md +++ b/README.md @@ -200,8 +200,3 @@ sws.on_close = on_close sws.connect() ``` - - - ->>>>>>> upstream/main - From 007996f351fd1c373f47f16da4083bc464ad61e2 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Fri, 30 Jun 2023 10:09:49 +0530 Subject: [PATCH 30/46] Update smartConnect.py --- SmartApi/smartConnect.py | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/SmartApi/smartConnect.py b/SmartApi/smartConnect.py index 32b60b12..2bfbbe0f 100644 --- a/SmartApi/smartConnect.py +++ b/SmartApi/smartConnect.py @@ -216,15 +216,6 @@ def _getRequest(self, route, params=None): """Alias for sending a GET request.""" return self._request(route, "GET", params) -<<<<<<< HEAD - def generateSession(self, clientCode, password, totp): - - params = {"clientcode": clientCode, "password": password, "totp": totp} - loginResultObject = self._postRequest("api.login", params) - - if loginResultObject['status'] == True: - jwtToken = loginResultObject['data']['jwtToken'] -======= def generateSession(self,clientCode,password,totp): params={"clientcode":clientCode,"password":password,"totp":totp} @@ -232,13 +223,11 @@ def generateSession(self,clientCode,password,totp): if loginResultObject['status']==True: jwtToken=loginResultObject['data']['jwtToken'] ->>>>>>> upstream/main self.setAccessToken(jwtToken) refreshToken = loginResultObject['data']['refreshToken'] feedToken = loginResultObject['data']['feedToken'] self.setRefreshToken(refreshToken) self.setFeedToken(feedToken) -<<<<<<< HEAD user = self.getProfile(refreshToken) id = user['data']['clientcode'] @@ -248,17 +237,6 @@ def generateSession(self,clientCode,password,totp): user['data']['refreshToken'] = refreshToken user['data']['feedToken'] = feedToken -======= - user=self.getProfile(refreshToken) - - id=user['data']['clientcode'] - #id='D88311' - self.setUserId(id) - user['data']['jwtToken']="Bearer "+jwtToken - user['data']['refreshToken']=refreshToken - user['data']['feedToken'] = feedToken - ->>>>>>> upstream/main return user else: return loginResultObject From dbb515f6b16f18aaebe3868a2bf89fcf1a74af5e Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Fri, 30 Jun 2023 10:12:16 +0530 Subject: [PATCH 31/46] Update sample.py --- example/sample.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/example/sample.py b/example/sample.py index 78aa59f8..50b70489 100644 --- a/example/sample.py +++ b/example/sample.py @@ -8,11 +8,8 @@ #login api call -<<<<<<< HEAD data = obj.generateSession("Your Client ID","Your Password","Your totp") -======= -data = obj.generateSession("Your Client ID","Your Password","Your totp here") ->>>>>>> upstream/main + refreshToken= data['data']['refreshToken'] #fetch the feedtoken From ffd38ddf39a1257a7026644344d0d6503629915d Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 12:38:39 +0530 Subject: [PATCH 32/46] Add files via upload --- test/test_sss-8.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py new file mode 100644 index 00000000..5c76e7fa --- /dev/null +++ b/test/test_sss-8.py @@ -0,0 +1,44 @@ +from SmartApi.smartConnect import SmartConnect +import pyotp + +api_key = 'JsL6CVS5' +username = 'R50841482' +pwd = '0000' +smartApi = SmartConnect(api_key) +token = "QBGCDBGGTTWHYPEUYG6FWGBZLY" +totp=pyotp.TOTP(token).now() +correlation_id = "abcde" +data = smartApi.generateSession(username, pwd, totp) +# print(data) +authToken = data['data']['jwtToken'] +refreshToken = data['data']['refreshToken'] +feedToken = smartApi.getfeedToken() +# print("Feed-Token :", feedToken) +res = smartApi.getProfile(refreshToken) +# print("Res:", res) +smartApi.generateToken(refreshToken) +res=res['data']['exchanges'] + +try: + orderparams = { "variety": "NORMAL", + "tradingsymbol": "RELIANCE-EQ", + "symboltoken": "122334875538", + "transactiontype": "BUY", + "exchange": "NSE", + "ordertype": "LIMIT", + "producttype": "DELIVERY", + "duration": "DAY", + "price": "2430", + "squareoff": "0", + "stoploss": "0", + "quantity": "8" + } + orderId=smartApi.placeOrder(orderparams) + print("The order id is: {}".format(orderId)) +except Exception as e: + if isinstance(e, TypeError): + print("Order placement failed: Invalid request parameters.") + else: + print("Order placement failed: {}".format(str(e))) + + From ab7997991a1c15d76e33fa3bfb143ac0cef29c26 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 12:40:04 +0530 Subject: [PATCH 33/46] Delete test_sss-8.py --- test/test_sss-8.py | 44 -------------------------------------------- 1 file changed, 44 deletions(-) delete mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py deleted file mode 100644 index 5c76e7fa..00000000 --- a/test/test_sss-8.py +++ /dev/null @@ -1,44 +0,0 @@ -from SmartApi.smartConnect import SmartConnect -import pyotp - -api_key = 'JsL6CVS5' -username = 'R50841482' -pwd = '0000' -smartApi = SmartConnect(api_key) -token = "QBGCDBGGTTWHYPEUYG6FWGBZLY" -totp=pyotp.TOTP(token).now() -correlation_id = "abcde" -data = smartApi.generateSession(username, pwd, totp) -# print(data) -authToken = data['data']['jwtToken'] -refreshToken = data['data']['refreshToken'] -feedToken = smartApi.getfeedToken() -# print("Feed-Token :", feedToken) -res = smartApi.getProfile(refreshToken) -# print("Res:", res) -smartApi.generateToken(refreshToken) -res=res['data']['exchanges'] - -try: - orderparams = { "variety": "NORMAL", - "tradingsymbol": "RELIANCE-EQ", - "symboltoken": "122334875538", - "transactiontype": "BUY", - "exchange": "NSE", - "ordertype": "LIMIT", - "producttype": "DELIVERY", - "duration": "DAY", - "price": "2430", - "squareoff": "0", - "stoploss": "0", - "quantity": "8" - } - orderId=smartApi.placeOrder(orderparams) - print("The order id is: {}".format(orderId)) -except Exception as e: - if isinstance(e, TypeError): - print("Order placement failed: Invalid request parameters.") - else: - print("Order placement failed: {}".format(str(e))) - - From b96532831c405880287ff167e0932359347bab04 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 12:41:13 +0530 Subject: [PATCH 34/46] Add files via upload --- test/test_sss-8.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py new file mode 100644 index 00000000..cee931a9 --- /dev/null +++ b/test/test_sss-8.py @@ -0,0 +1,44 @@ +from SmartApi.smartConnect import SmartConnect +import pyotp + +api_key = 'api-key' +username = 'Client-code' +pwd = 'pin' +smartApi = SmartConnect(api_key) +token = "QR-code value" +totp=pyotp.TOTP(token).now() +correlation_id = "abcde" +data = smartApi.generateSession(username, pwd, totp) +# print(data) +authToken = data['data']['jwtToken'] +refreshToken = data['data']['refreshToken'] +feedToken = smartApi.getfeedToken() +# print("Feed-Token :", feedToken) +res = smartApi.getProfile(refreshToken) +# print("Res:", res) +smartApi.generateToken(refreshToken) +res=res['data']['exchanges'] + +try: + orderparams = { "variety": "NORMAL", + "tradingsymbol": "RELIANCE-EQ", + "symboltoken": "122334875538", + "transactiontype": "BUY", + "exchange": "NSE", + "ordertype": "LIMIT", + "producttype": "DELIVERY", + "duration": "DAY", + "price": "2430", + "squareoff": "0", + "stoploss": "0", + "quantity": "8" + } + orderId=smartApi.placeOrder(orderparams) + print("The order id is: {}".format(orderId)) +except Exception as e: + if isinstance(e, TypeError): + print("Order placement failed: Invalid request parameters.") + else: + print("Order placement failed: {}".format(str(e))) + + From 4a9156ecb78d415276c944011fe86be0e8fff3af Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 12:41:41 +0530 Subject: [PATCH 35/46] Update setup.py --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 92925d01..d80ab183 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ setup( name="smartapi-python", - version="1.2.9", + version="1.3.4", author="ab-smartapi", author_email="smartapi.sdk@gmail.com", description="Angel Broking openApi integration", From 2efc381ffdc57560614b4a654e62e40b08adc720 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 12:42:40 +0530 Subject: [PATCH 36/46] Update requirements_dev.txt --- requirements_dev.txt | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/requirements_dev.txt b/requirements_dev.txt index 4b11c052..c1d1a233 100644 --- a/requirements_dev.txt +++ b/requirements_dev.txt @@ -5,14 +5,12 @@ certifi==2023.5.7 cffi==1.15.1 charset-normalizer==3.1.0 constantly==15.1.0 -cryptography==41.0.1 hyperlink==21.0.0 idna==3.4 incremental==22.10.0 isodate==0.6.1 logzero==1.7.0 pycparser==2.21 -pycrypto==2.6.1 pyotp==2.8.0 pyparsing==3.1.0 python-dateutil==2.8.2 @@ -22,7 +20,7 @@ rdflib-jsonld==0.6.2 requests==2.31.0 simplejson==3.19.1 six==1.16.0 -smartapi-python==1.3.0 +smartapi-python==1.3.4 Twisted==22.10.0 txaio==23.1.1 typing_extensions==4.6.3 From f1d9d929925be58625292ef341cc8a003d7c54ec Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 14:39:28 +0530 Subject: [PATCH 37/46] Delete test_sss-8.py --- test/test_sss-8.py | 44 -------------------------------------------- 1 file changed, 44 deletions(-) delete mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py deleted file mode 100644 index cee931a9..00000000 --- a/test/test_sss-8.py +++ /dev/null @@ -1,44 +0,0 @@ -from SmartApi.smartConnect import SmartConnect -import pyotp - -api_key = 'api-key' -username = 'Client-code' -pwd = 'pin' -smartApi = SmartConnect(api_key) -token = "QR-code value" -totp=pyotp.TOTP(token).now() -correlation_id = "abcde" -data = smartApi.generateSession(username, pwd, totp) -# print(data) -authToken = data['data']['jwtToken'] -refreshToken = data['data']['refreshToken'] -feedToken = smartApi.getfeedToken() -# print("Feed-Token :", feedToken) -res = smartApi.getProfile(refreshToken) -# print("Res:", res) -smartApi.generateToken(refreshToken) -res=res['data']['exchanges'] - -try: - orderparams = { "variety": "NORMAL", - "tradingsymbol": "RELIANCE-EQ", - "symboltoken": "122334875538", - "transactiontype": "BUY", - "exchange": "NSE", - "ordertype": "LIMIT", - "producttype": "DELIVERY", - "duration": "DAY", - "price": "2430", - "squareoff": "0", - "stoploss": "0", - "quantity": "8" - } - orderId=smartApi.placeOrder(orderparams) - print("The order id is: {}".format(orderId)) -except Exception as e: - if isinstance(e, TypeError): - print("Order placement failed: Invalid request parameters.") - else: - print("Order placement failed: {}".format(str(e))) - - From 210539b27e280bec6f1e690e045b8b412e70de4b Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 14:43:40 +0530 Subject: [PATCH 38/46] Add files via upload --- test/test_sss-8.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py new file mode 100644 index 00000000..f89ecdcb --- /dev/null +++ b/test/test_sss-8.py @@ -0,0 +1,42 @@ +from SmartApi.smartConnect import SmartConnect +import pyotp + +api_key = 'api-key' +username = 'client-code' +pwd = 'pin' +smartApi = SmartConnect(api_key) +token = "QR-code value" +totp=pyotp.TOTP(token).now() +correlation_id = "abcde" +data = smartApi.generateSession(username, pwd, totp) +# print(data) +authToken = data['data']['jwtToken'] +refreshToken = data['data']['refreshToken'] +feedToken = smartApi.getfeedToken() +# print("Feed-Token :", feedToken) +res = smartApi.getProfile(refreshToken) +# print("Res:", res) +smartApi.generateToken(refreshToken) +res=res['data']['exchanges'] + +try: + orderparams = { "variety": "NORMAL", + "tradingsymbol": "RELIANCE-EQ", + "symboltoken": "122334875538", + "transactiontype": "BUY", + "exchange": "NSE", + "ordertype": "LIMIT", + "producttype": "DELIVERY", + "duration": "DAY", + "price": "2430", + "squareoff": "0", + "stoploss": "0", + "quantity": "8" + } + orderId=smartApi.placeOrder(orderparams) + print("The order id is: {}".format(orderId)) +except Exception as e: + if e.message == "Couldn't parse the JSON response received from the server": + print("Invalid symboltoken. Please check the symboltoken value.") + else: + print("Order placement failed: {}".format(e.message)) \ No newline at end of file From b29cc7e602f076bcf77183576561fade987fbd0a Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 14:45:25 +0530 Subject: [PATCH 39/46] Delete test_sss-8.py --- test/test_sss-8.py | 42 ------------------------------------------ 1 file changed, 42 deletions(-) delete mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py deleted file mode 100644 index f89ecdcb..00000000 --- a/test/test_sss-8.py +++ /dev/null @@ -1,42 +0,0 @@ -from SmartApi.smartConnect import SmartConnect -import pyotp - -api_key = 'api-key' -username = 'client-code' -pwd = 'pin' -smartApi = SmartConnect(api_key) -token = "QR-code value" -totp=pyotp.TOTP(token).now() -correlation_id = "abcde" -data = smartApi.generateSession(username, pwd, totp) -# print(data) -authToken = data['data']['jwtToken'] -refreshToken = data['data']['refreshToken'] -feedToken = smartApi.getfeedToken() -# print("Feed-Token :", feedToken) -res = smartApi.getProfile(refreshToken) -# print("Res:", res) -smartApi.generateToken(refreshToken) -res=res['data']['exchanges'] - -try: - orderparams = { "variety": "NORMAL", - "tradingsymbol": "RELIANCE-EQ", - "symboltoken": "122334875538", - "transactiontype": "BUY", - "exchange": "NSE", - "ordertype": "LIMIT", - "producttype": "DELIVERY", - "duration": "DAY", - "price": "2430", - "squareoff": "0", - "stoploss": "0", - "quantity": "8" - } - orderId=smartApi.placeOrder(orderparams) - print("The order id is: {}".format(orderId)) -except Exception as e: - if e.message == "Couldn't parse the JSON response received from the server": - print("Invalid symboltoken. Please check the symboltoken value.") - else: - print("Order placement failed: {}".format(e.message)) \ No newline at end of file From 6b04e2651a5704cfa3e00a3e3dee878f9e960bd2 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 14:46:22 +0530 Subject: [PATCH 40/46] Add files via upload --- test/test_sss-8.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py new file mode 100644 index 00000000..a0a548b3 --- /dev/null +++ b/test/test_sss-8.py @@ -0,0 +1,42 @@ +from SmartApi.smartConnect import SmartConnect +import pyotp + +api_key = 'api-key' +username = 'client-code' +pwd = 'pin' +smartApi = SmartConnect(api_key) +token = "QR-value code" +totp=pyotp.TOTP(token).now() +correlation_id = "abcde" +data = smartApi.generateSession(username, pwd, totp) +# print(data) +authToken = data['data']['jwtToken'] +refreshToken = data['data']['refreshToken'] +feedToken = smartApi.getfeedToken() +# print("Feed-Token :", feedToken) +res = smartApi.getProfile(refreshToken) +# print("Res:", res) +smartApi.generateToken(refreshToken) +res=res['data']['exchanges'] + +try: + orderparams = { "variety": "NORMAL", + "tradingsymbol": "RELIANCE-EQ", + "symboltoken": "122334875538", + "transactiontype": "BUY", + "exchange": "NSE", + "ordertype": "LIMIT", + "producttype": "DELIVERY", + "duration": "DAY", + "price": "2430", + "squareoff": "0", + "stoploss": "0", + "quantity": "8" + } + orderId=smartApi.placeOrder(orderparams) + print("The order id is: {}".format(orderId)) +except Exception as e: + if isinstance(e, TypeError): + print("Order placement failed: Invalid request parameters.") + else: + print("Order placement failed: {}".format(str(e))) \ No newline at end of file From 839501ed8c15b9cf3aa292ef1ef6dfae978c4e66 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 15:14:05 +0530 Subject: [PATCH 41/46] Delete test_sss-8.py --- test/test_sss-8.py | 42 ------------------------------------------ 1 file changed, 42 deletions(-) delete mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py deleted file mode 100644 index a0a548b3..00000000 --- a/test/test_sss-8.py +++ /dev/null @@ -1,42 +0,0 @@ -from SmartApi.smartConnect import SmartConnect -import pyotp - -api_key = 'api-key' -username = 'client-code' -pwd = 'pin' -smartApi = SmartConnect(api_key) -token = "QR-value code" -totp=pyotp.TOTP(token).now() -correlation_id = "abcde" -data = smartApi.generateSession(username, pwd, totp) -# print(data) -authToken = data['data']['jwtToken'] -refreshToken = data['data']['refreshToken'] -feedToken = smartApi.getfeedToken() -# print("Feed-Token :", feedToken) -res = smartApi.getProfile(refreshToken) -# print("Res:", res) -smartApi.generateToken(refreshToken) -res=res['data']['exchanges'] - -try: - orderparams = { "variety": "NORMAL", - "tradingsymbol": "RELIANCE-EQ", - "symboltoken": "122334875538", - "transactiontype": "BUY", - "exchange": "NSE", - "ordertype": "LIMIT", - "producttype": "DELIVERY", - "duration": "DAY", - "price": "2430", - "squareoff": "0", - "stoploss": "0", - "quantity": "8" - } - orderId=smartApi.placeOrder(orderparams) - print("The order id is: {}".format(orderId)) -except Exception as e: - if isinstance(e, TypeError): - print("Order placement failed: Invalid request parameters.") - else: - print("Order placement failed: {}".format(str(e))) \ No newline at end of file From 12eb2a35ea3384126ba3af2211228d7e9c1179c5 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Thu, 6 Jul 2023 15:17:40 +0530 Subject: [PATCH 42/46] Add files via upload --- test/test_sss-8.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py new file mode 100644 index 00000000..a0a548b3 --- /dev/null +++ b/test/test_sss-8.py @@ -0,0 +1,42 @@ +from SmartApi.smartConnect import SmartConnect +import pyotp + +api_key = 'api-key' +username = 'client-code' +pwd = 'pin' +smartApi = SmartConnect(api_key) +token = "QR-value code" +totp=pyotp.TOTP(token).now() +correlation_id = "abcde" +data = smartApi.generateSession(username, pwd, totp) +# print(data) +authToken = data['data']['jwtToken'] +refreshToken = data['data']['refreshToken'] +feedToken = smartApi.getfeedToken() +# print("Feed-Token :", feedToken) +res = smartApi.getProfile(refreshToken) +# print("Res:", res) +smartApi.generateToken(refreshToken) +res=res['data']['exchanges'] + +try: + orderparams = { "variety": "NORMAL", + "tradingsymbol": "RELIANCE-EQ", + "symboltoken": "122334875538", + "transactiontype": "BUY", + "exchange": "NSE", + "ordertype": "LIMIT", + "producttype": "DELIVERY", + "duration": "DAY", + "price": "2430", + "squareoff": "0", + "stoploss": "0", + "quantity": "8" + } + orderId=smartApi.placeOrder(orderparams) + print("The order id is: {}".format(orderId)) +except Exception as e: + if isinstance(e, TypeError): + print("Order placement failed: Invalid request parameters.") + else: + print("Order placement failed: {}".format(str(e))) \ No newline at end of file From 418b88ebd943cd69212c6848543dba3a2480335d Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Tue, 11 Jul 2023 18:19:50 +0530 Subject: [PATCH 43/46] Update requirements_dev.txt --- requirements_dev.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements_dev.txt b/requirements_dev.txt index c1d1a233..b8ff741b 100644 --- a/requirements_dev.txt +++ b/requirements_dev.txt @@ -20,7 +20,7 @@ rdflib-jsonld==0.6.2 requests==2.31.0 simplejson==3.19.1 six==1.16.0 -smartapi-python==1.3.4 +smartapi-python==1.3.5 Twisted==22.10.0 txaio==23.1.1 typing_extensions==4.6.3 From f0329d67250dee27d218e7a84229897c308f25a2 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Tue, 11 Jul 2023 18:20:15 +0530 Subject: [PATCH 44/46] Update setup.py --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index d80ab183..fc720ad6 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ setup( name="smartapi-python", - version="1.3.4", + version="1.3.5", author="ab-smartapi", author_email="smartapi.sdk@gmail.com", description="Angel Broking openApi integration", From f084a245a54d37ad982d8cdbee686638886da223 Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 12 Jul 2023 10:33:37 +0530 Subject: [PATCH 45/46] Delete test_sss-8.py --- test/test_sss-8.py | 42 ------------------------------------------ 1 file changed, 42 deletions(-) delete mode 100644 test/test_sss-8.py diff --git a/test/test_sss-8.py b/test/test_sss-8.py deleted file mode 100644 index a0a548b3..00000000 --- a/test/test_sss-8.py +++ /dev/null @@ -1,42 +0,0 @@ -from SmartApi.smartConnect import SmartConnect -import pyotp - -api_key = 'api-key' -username = 'client-code' -pwd = 'pin' -smartApi = SmartConnect(api_key) -token = "QR-value code" -totp=pyotp.TOTP(token).now() -correlation_id = "abcde" -data = smartApi.generateSession(username, pwd, totp) -# print(data) -authToken = data['data']['jwtToken'] -refreshToken = data['data']['refreshToken'] -feedToken = smartApi.getfeedToken() -# print("Feed-Token :", feedToken) -res = smartApi.getProfile(refreshToken) -# print("Res:", res) -smartApi.generateToken(refreshToken) -res=res['data']['exchanges'] - -try: - orderparams = { "variety": "NORMAL", - "tradingsymbol": "RELIANCE-EQ", - "symboltoken": "122334875538", - "transactiontype": "BUY", - "exchange": "NSE", - "ordertype": "LIMIT", - "producttype": "DELIVERY", - "duration": "DAY", - "price": "2430", - "squareoff": "0", - "stoploss": "0", - "quantity": "8" - } - orderId=smartApi.placeOrder(orderparams) - print("The order id is: {}".format(orderId)) -except Exception as e: - if isinstance(e, TypeError): - print("Order placement failed: Invalid request parameters.") - else: - print("Order placement failed: {}".format(str(e))) \ No newline at end of file From 65f2706618d1c7f76f52f7a767845fece3a93fed Mon Sep 17 00:00:00 2001 From: rimagiri <126047113+rimagiri@users.noreply.github.com> Date: Wed, 12 Jul 2023 12:09:14 +0530 Subject: [PATCH 46/46] Update test.py --- test/test.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/test.py b/test/test.py index e6232473..3a61cfb1 100644 --- a/test/test.py +++ b/test/test.py @@ -53,7 +53,8 @@ smartApi.modifyOrder(modifyparams) print("Modify Orders:",modifyparams) -smartApi.cancelOrder(orderid, "NORMAL") +cancelOrder=smartApi.cancelOrder(orderid, "NORMAL") +print("cancelOrder",cancelOrder) orderbook=smartApi.orderBook() print("Order Book :", orderbook)