Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
5778a14
file added
vrushalikapse Oct 27, 2020
8149936
Changes in code and addition of new files and folder in order to publ…
vrushalikapse Oct 28, 2020
4527893
Elemination of few unwanted keywords
vrushalikapse Nov 9, 2020
971f9db
Websocket and README File Added, Endpoints of api changed
vrushalikapse Nov 23, 2020
d8cd1ce
Merge pull request #3 from angelbroking-github/develop
vrushalikapse Nov 24, 2020
ee48512
changes in socket files and readme
vrushalikapse Nov 30, 2020
1615444
changes in endpoint url for prod
vrushalikapse Nov 30, 2020
29a05e2
changes in endpoint url for prod
vrushalikapse Nov 30, 2020
f280630
changes in readme-conflict solved
vrushalikapse Nov 30, 2020
928e6a4
changes in readme-conflict solved
vrushalikapse Nov 30, 2020
245cfb8
changes in __init__.py
vrushalikapse Nov 30, 2020
047ee2d
Merge branch 'develop' into main
vrushalikapse Nov 30, 2020
3689fc6
changes in sample.py- import statement
vrushalikapse Nov 30, 2020
920e553
Merge branch 'develop' into main
vrushalikapse Nov 30, 2020
87bf4b6
changes in version
vrushalikapse Nov 30, 2020
29accb5
Merge branch 'develop' into main
vrushalikapse Nov 30, 2020
8c6b181
changes in version
vrushalikapse Nov 30, 2020
33f1d05
Merge branch 'develop' into main
vrushalikapse Nov 30, 2020
fbdf51f
bugs resolved
vrushalikapse Nov 30, 2020
ff144d3
Changes in import statement and version
vrushalikapse Nov 30, 2020
c230c9e
Changes in readme
vrushalikapse Nov 30, 2020
7dbc0ff
changes in version
vrushalikapse Nov 30, 2020
42b4c25
bugs resolved
vrushalikapse Nov 30, 2020
064faf6
bugs resolved
vrushalikapse Nov 30, 2020
75447d4
changes in root variable
vrushalikapse Nov 30, 2020
b6d7c2f
Updated code
vrushalikapse Dec 1, 2020
bd9896f
updated Readme file
vrushalikapse Dec 1, 2020
e5e1457
changes in init.py file and readme file
vrushalikapse Dec 3, 2020
260fc76
getFeedToken() function added, Changes in import statement for websocket
vrushalikapse Dec 8, 2020
ea49f8b
getFeedToken() function added, Changes in import statement for websocket
vrushalikapse Dec 8, 2020
8fecc00
Changes in import statement for websocket
vrushalikapse Dec 9, 2020
9765bcb
getfeedToken()
vrushalikapse Dec 10, 2020
a9617ce
bugs rectified
vrushalikapse Dec 10, 2020
bd11f8a
heartbeats added in websocket
vrushalikapse Dec 11, 2020
8b0f85d
removed unnecessary print statements
vrushalikapse Dec 29, 2020
15165d4
removed unnecessary print statements
vrushalikapse Dec 29, 2020
79ce701
conflicts solved
vrushalikapse Dec 29, 2020
5e7d323
Nameerror resolved
vrushalikapse Jan 19, 2021
e38242b
Merge branch 'main' of https://github.com/angelbroking-github/smartap…
vrushalikapse Feb 18, 2021
10ed698
Gtt services added
vrushalikapse Mar 3, 2021
c361cd8
Condition added for Public Ip Header
vrushalikapse Mar 8, 2021
1461f12
Merge branch 'develop' into main
vrushalikapse Mar 8, 2021
28ee960
Changes in websocket-sendRequest(token,task)
vrushalikapse Mar 8, 2021
0fdd1b9
Historic api added and Websocket Open Forum Issues Resolved
abhijeetbote Mar 26, 2021
7cd96b4
Conflicts resolved
abhijeetbote Mar 26, 2021
1fb8531
Changes in Readme
vrushalikapse Mar 31, 2021
893022a
New url added to webSocket.py
Apr 6, 2021
3c2b332
New url added in webSocket.py
Apr 6, 2021
a3ff1d5
Version changed in setup.py
Apr 7, 2021
19a70ad
changes in sample.py
Apr 16, 2021
89dfbec
changes in readme and sample.py for websocket termination issue(multi…
vrushalikapse Apr 21, 2021
02b5dc1
changes in heartbeat seconds
vrushalikapse Apr 26, 2021
a908b06
Changes in websocket heartbeat secs
vrushalikapse May 10, 2021
6fba868
WS fixes
May 27, 2021
ba9db40
fixes
dsuraj72 May 27, 2021
ff5f1c2
Delete .pypirc
dsuraj72 May 28, 2021
86859f8
Update README.md
dsuraj72 May 28, 2021
8ffd927
connection new fix
Jun 15, 2021
9823132
version upgraded
dsuraj72 Jun 15, 2021
7f543a8
syntax fix
dsuraj72 Jun 16, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@

.pypirc
146 changes: 145 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,145 @@
# smartapi-python
# 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()
```




11 changes: 11 additions & 0 deletions SmartApi/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from __future__ import unicode_literals,absolute_import

from smartapi.smartConnect import SmartConnect
# from smartapi.webSocket import WebSocket
from smartapi.smartApiWebsocket import SmartWebSocket

__all__ = ["SmartConnect","SmartWebSocket"]




Binary file added SmartApi/__pycache__/__init__.cpython-36.pyc
Binary file not shown.
Binary file added SmartApi/__pycache__/smartConnect.cpython-36.pyc
Binary file not shown.
Binary file not shown.
Binary file added SmartApi/__pycache__/smartSocket.cpython-36.pyc
Binary file not shown.
Binary file added SmartApi/__pycache__/socket.cpython-36.pyc
Binary file not shown.
Binary file added SmartApi/__pycache__/socketTP.cpython-36.pyc
Binary file not shown.
Binary file added SmartApi/__pycache__/version.cpython-36.pyc
Binary file not shown.
182 changes: 182 additions & 0 deletions SmartApi/smartApiWebsocket.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 11:38:36 2021

@author: Sandip.Khairnar
"""

import websocket
import six
import base64
import zlib
import datetime
import time
import json
import threading
import ssl

class SmartWebSocket(object):
ROOT_URI='wss://wsfeeds.angelbroking.com/NestHtml5Mobile/socket/stream'
HB_INTERVAL=30
HB_THREAD_FLAG=False
WS_RECONNECT_FLAG=False
feed_token=None
client_code=None
ws=None
task_dict = {}

def __init__(self, FEED_TOKEN, CLIENT_CODE):
self.root = self.ROOT_URI
self.feed_token = FEED_TOKEN
self.client_code = CLIENT_CODE
if self.client_code == None or self.feed_token == None:
return "client_code or feed_token or task is missing"

def _subscribe_on_open(self):
request = {"task": "cn", "channel": "NONLM", "token": self.feed_token, "user": self.client_code,
"acctid": self.client_code}
print(request)
self.ws.send(
six.b(json.dumps(request))
)

thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()

def run(self):
while True:
# More statements comes here
if self.HB_THREAD_FLAG:
break
print(datetime.datetime.now().__str__() + ' : Start task in the background')

self.heartBeat()

time.sleep(self.HB_INTERVAL)

def subscribe(self, task, token):
# print(self.task_dict)
self.task_dict.update([(task,token),])
# print(self.task_dict)
if task in ("mw", "sfi", "dp"):
strwatchlistscrips = token # dynamic call

try:
request = {"task": task, "channel": strwatchlistscrips, "token": self.feed_token,
"user": self.client_code, "acctid": self.client_code}

self.ws.send(
six.b(json.dumps(request))
)
return True
except Exception as e:
self._close(reason="Error while request sending: {}".format(str(e)))
raise
else:
print("The task entered is invalid, Please enter correct task(mw,sfi,dp) ")

def resubscribe(self):
for task, marketwatch in self.task_dict.items():
print(task, '->', marketwatch)
try:
request = {"task": task, "channel": marketwatch, "token": self.feed_token,
"user": self.client_code, "acctid": self.client_code}

self.ws.send(
six.b(json.dumps(request))
)
return True
except Exception as e:
self._close(reason="Error while request sending: {}".format(str(e)))
raise

def heartBeat(self):
try:
request = {"task": "hb", "channel": "", "token": self.feed_token, "user": self.client_code,
"acctid": self.client_code}
print(request)
self.ws.send(
six.b(json.dumps(request))
)

except:
print("HeartBeat Sending Failed")
# time.sleep(60)

def _parse_text_message(self, message):
"""Parse text message."""

data = base64.b64decode(message)

try:
data = bytes((zlib.decompress(data)).decode("utf-8"), 'utf-8')
data = json.loads(data.decode('utf8').replace("'", '"'))
data = json.loads(json.dumps(data, indent=4, sort_keys=True))
except ValueError:
return

# return data
if data:
self._on_message(self.ws,data)

def connect(self):
# websocket.enableTrace(True)
self.ws = websocket.WebSocketApp(self.ROOT_URI,
on_message=self.__on_message,
on_close=self.__on_close,
on_open=self.__on_open,
on_error=self.__on_error)

self.ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

def __on_message(self, ws, message):
self._parse_text_message(message)
# print(msg)

def __on_open(self, ws):
print("__on_open################")
self.HB_THREAD_FLAG = False
self._subscribe_on_open()
if self.WS_RECONNECT_FLAG:
self.WS_RECONNECT_FLAG = False
self.resubscribe()
else:
self._on_open(ws)

def __on_close(self, ws):
self.HB_THREAD_FLAG = True
print("__on_close################")
self._on_close(ws)

def __on_error(self, ws, error):

if ( "timed" in str(error) ) or ( "Connection is already closed" in str(error) ) or ( "Connection to remote host was lost" in str(error) ):

self.WS_RECONNECT_FLAG = True
self.HB_THREAD_FLAG = True

if (ws is not None):
ws.close()
ws.on_message = None
ws.on_open = None
ws.close = None
# print (' deleting ws')
del ws

self.connect()
else:
print ('Error info: %s' %(error))
self._on_error(ws, error)

def _on_message(self, ws, message):
pass

def _on_open(self, ws):
pass

def _on_close(self, ws):
pass

def _on_error(self, ws, error):
pass
Loading