Shoonya-Dev/ShoonyaApi-py

166

stars

87

commits

Python

primary language

Jul 29, 2024

updated

README

Shoonya API

Api used to connect to Shoonya OMS.

This is a python wrapper or connector to the RestAPI and websocket of Shoonya.

More details are found here https://www.shoonya.com/api-documentation


Build

to build this package and install it on your server please use

pip install -r requirements.txt


API

ShoonyaApi

Symbols

Orders and Trades

Holdings and Limits

Calculators

Websocket API

Example

login(userid, password, twoFA, vendor_code, api_secret, imei)

connect to the broker, only once this function has returned successfully can any other operations be performed Example: #For TOTP Automation, Reffer below Mentioned Command #TOKEN = 'Q65C5R7WJ2AR77VA623OC2SI5D5KM447' #otp = pyotp.TOTP(TOKEN).now()

#credentials
user    = <uid>
pwd     = <password>
factor2 = <OTP/TOTP>
vc      = <vendor code>
app_key = <API key>
imei    = <imei>

ret = api.login(userid=uid, password=pwd, twoFA=factor2, vendor_code=vc, api_secret=app_key, imei=imei)

Request Details :

Json FieldsPossible valueDescription
apkversion*Application version.For Ex. 1.0.0
uid*User Id of the login user
pwd*Shoonya login password.
factor2*OTP or TOTP as entered by the user. (User Needs to be generated from the Shoonya app)
vc*Vendor code provided by noren team, along with connection URLs
appkey*Prism Generated API key
imei*Send mac if users logs in for desktop, imei is from mobile
addldivinfOptional field, Value must be in below format:
ipaddrOptional field
sourceAPI

Response Details :

Json FieldsPossible valueDescription
statOk or Not_OkLogin Success Or failure status
susertokenIt will be present only on login success. This data to be sent in subsequent requests in jKey field and web socket connection while connecting.
lastaccesstimeIt will be present only on login success.
spasswordresetYIf Y Mandatory password reset to be enforced. Otherwise the field will be absent.
exarrJson array of strings with enabled exchange names
unameUser name
prarrJson array of Product Obj with enabled products, as defined below.
actidAccount id
emailEmail Id
brknameBroker id
emsgThis will be present only if Login fails.

Sample Success Response : { "request_time": "20:18:47 19-05-2020", "stat": "Ok", "susertoken": "3b97f4c67762259a9ded6dbd7bfafe2787e662b3870422ddd343a59895f423a0", "lastaccesstime": "1589899727" }

Sample Failure Response : { "request_time": "20:32:14 19-05-2020", "stat": "Not_Ok", "emsg": "Invalid Input : Wrong Password" }

logout()

Terminate the session

Example:

ret = api.logout()

Request Details :

Json FieldsPossible valueDescription
uid*User Id of the login user

Response Details : Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkLogout Success Or failure status
request_timeIt will be present only on successful logout.
emsgThis will be present only if Logout fails.

Sample Success Response : { "stat":"Ok", "request_time":"10:43:41 28-05-2020" }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Server Timeout : " }

place_order(buy_or_sell, product_type,exchange, tradingsymbol, quantity, discloseqty, price_type, price=0.0, trigger_price=None, retention='DAY', amo='NO', remarks=None)

place an order to oms

Example:

ret = api.place_order(buy_or_sell='B', product_type='C',
                        exchange='NSE', tradingsymbol='CANBK-EQ', 
                        quantity=1, discloseqty=0,price_type='SL-LMT', price=200.00, trigger_price=199.50,
                        retention='DAY', remarks='my_order_001')

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
actid*Login users account ID
exch*NSE / NFO / CDS / MCX / BSEExchange (Select from ‘exarr’ Array provided in User Details response)
tsym*RELIANCE-EQ / L&TFH29SEP22P97 / USDINR25NOV22C76 / CRUDEOIL16NOV22P5400 / WHIRLPOOLUnique id of contract on which order to be placed. (Use the Results from Search Script to get the trading symbol & use url encoding to avoid special char error for symbols like M&M)
qty*RELIANCE-EQ:-1 / NIFTY:-50 / BANKNIFTY:-25Order Quantity
prc*Order Price
trgprcOnly to be sent in case of SL / SL-M order.
dscqtyDisclosed quantity (Max 10% for NSE, and 50% for MCX)
prd*C / M / I / B / HProduct name (Select from ‘prarr’ Array provided in User Details response, and if same is allowed for selected, exchange. Show product display name, for user to select, and send corresponding prd in API call) "C" For CNC, "M" FOR NRML, "I" FOR MIS, "B" FOR BRACKET ORDER, "H" FOR COVER ORDER
trantype*B / SB -> BUY, S -> SELL
prctyp*LMT / MKT / SL-LMT / SL-MKT / DS / 2L / 3L
ret*DAY / EOS / IOCRetention type (Show options as per allowed exchanges)
remarksAny tag by user to mark order.
ordersourceMOB / WEB / TTUsed to generate exchange info fields.
bpprcBook Profit Price applicable only if product is selected as B (Bracket order )
blprcBook loss Price applicable only if product is selected as H and B (High Leverage and Bracket order )
trailprcTrailing Price applicable only if product is selected as H and B (High Leverage and Bracket order )
amoYes , If not sent, of Not “Yes”, will be treated as Regular order.
tsym2Trading symbol of second leg, mandatory for price type 2L and 3L (use url encoding to avoid special char error for symbols like M&M)
trantype2Transaction type of second leg, mandatory for price type 2L and 3L
qty2Quantity for second leg, mandatory for price type 2L and 3L
prc2Price for second leg, mandatory for price type 2L and 3L
tsym3Trading symbol of third leg, mandatory for price type 3L (use url encoding to avoid special char error for symbols like M&M)
trantype3Transaction type of third leg, mandatory for price type 3L
qty3Quantity for third leg, mandatory for price type 3L
prc3Price for third leg, mandatory for price type 3L

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkPlace order success or failure indication.
request_timeResponse received time.
norenordnoIt will be present only on successful Order placement to OMS.
emsgThis will be present only if Order placement fails

Sample Success Response: { "request_time": "10:48:03 20-05-2020", "stat": "Ok", "norenordno": "20052000000017" }

Sample Error Response : { "stat": "Not_Ok", "request_time": "20:40:01 19-05-2020", "emsg": "Error Occurred : 2 "invalid input"" }

modify_order(orderno, exchange, tradingsymbol, newquantity,newprice_type, newprice, newtrigger_price, amo):

modify the quantity pricetype or price of an order

Example:

orderno = ret['norenordno'] #from placeorder return value
ret = api.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno,
                                   newquantity=2, newprice_type='MKT', newprice=0.00)
## sl modification
ret = api.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno,
                                   newquantity=2, newprice_type='SL-LMT', newprice=201.00, newtrigger_price=200.00)

Request Details :

Json FieldsPossible valueDescription
exch*Exchange
norenordno*Noren order number, which needs to be modified
prctypLMT / MKT / SL-MKT / SL-LMTThis can be modified.
prcModified / New price
qtyModified / New Quantity
tsym*Unque id of contract on which order was placed. Can’t be modified, must be the same as that of original order. (use url encoding to avoid special char error for symbols like M&M)
retDAY / IOC / EOSNew Retention type of the order
trgprcNew trigger price in case of SL-MKT or SL-LMT
uid*User id of the logged in user.
bpprcBook Profit Price applicable only if product is selected as B (Bracket order )
blprcBook loss Price applicable only if product is selected as H and B (High Leverage and Bracket order )
trailprcTrailing Price applicable only if product is selected as H and B (High Leverage and Bracket order )

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkModify order success or failure indication.
resultNoren Order number of the order modified.
request_timeResponse received time.
emsgThis will be present only if Order modification fails

Sample Success Response : { "request_time":"14:14:08 26-05-2020", "stat":"Ok", "result":"20052600000103" }

Sample Failure Response : { "request_time":"16:03:29 28-05-2020", "stat":"Not_Ok", "emsg":"Rejected : ORA:Order not found" }

cancel_order(orderno)

cancel an order

Example:

orderno = ret['norenordno'] #from placeorder return value
ret = api.cancel_order(orderno=orderno)

Request Details :

Json FieldsPossible valueDescription
norenordno*Noren order number, which needs to be modified
uid*User id of the logged in user.

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkCancel order success or failure indication.
resultNoren Order number of the canceled order.
request_timeResponse received time.
emsgThis will be present only if Order cancelation fails

Sample Success Response : { "request_time":"14:14:10 26-05-2020", "stat":"Ok", "result":"20052600000103" }

Sample Failure Response : { "request_time":"16:01:48 28-05-2020", "stat":"Not_Ok", "emsg":"Rejected : ORA:Order not found to Cancel" }

exit_order(orderno)

exits a cover or bracket order

Request Details :

Json FieldsPossible valueDescription
norenordno*Noren order number, which needs to be modified
prd*H / BAllowed for only H and B products (Cover order and bracket order)
uid*User id of the logged in user.

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkCancel order success or failure indication.
dmsgDisplay message, (will be present only in case of success).
request_timeResponse received time.
emsgThis will be present only if Order cancelation fails

position_product_conversion(exchange, tradingsymbol, quantity, new_product_type, previous_product_type, buy_or_sell, day_or_cf)

Convert a product of a position

Example:

ret = api.get_positions()
#converts the first position from existing product to intraday
p = ret[0]
ret = api.position_product_conversion(p['exch'], p['tsym'], p['netqty'], 'I', p['prd'], 'B', 'DAY')

Request Details :

Json FieldsPossible valueDescription
exch*Exchange
tsym*Unique id of contract on which order was placed. Can’t be modified, must be the same as that of original order. (use url encoding to avoid special char error for symbols like M&M)
qty*Quantity to be converted.
uid*User id of the logged in user.
actid*Account id
prd*Product to which the user wants to convert position.
prevprd*Original product of the position.
trantype*Transaction type
postype*Day / CFConverting Day or Carry forward position
ordersourceMOBFor Logging

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkPosition conversion success or failure indication.
emsgThis will be present only if Position conversion fails.

Sample Success Response : { "request_time":"10:52:12 02-06-2020", "stat":"Ok" }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Invalid Input : Invalid Position Type" }

Order Book

List of Orders placed for the account

Example :

ret = api.get_order_book()
print(ret)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
prdH / M / ...Product name

Response Details :

Response data will be in json Array of objects with below fields in case of success.

Json FieldsPossible valueDescription
statOk or Not_OkOrder book success or failure indication.
exchExchange Segment
tsymTrading symbol / contract on which order is placed.
norenordnoNoren Order Number
prcOrder Price
qtyOrder Quantity
prdDisplay product alias name, using prarr returned in user details.
status
trantypeB / STransaction type of the order
prctypLMT / MKTPrice type
fillsharesTotal Traded Quantity of this order
avgprcAverage trade price of total traded quantity
rejreasonIf order is rejected, reason in text form
exchordidExchange Order Number
cancelqtyCanceled quantity for order which is in status cancelled.
remarksAny message Entered during order entry.
dscqtyOrder disclosed quantity.
trgprcOrder trigger price
retDAY / IOC / EOSOrder validity
uid
actid
bpprcBook Profit Price applicable only if product is selected as B (Bracket order )
blprcBook loss Price applicable only if product is selected as H and B (High Leverage and Bracket order )
trailprcTrailing Price applicable only if product is selected as H and B (High Leverage and Bracket order )
amoYes / No
ppPrice precision
tiTick size
lsLot size
tokenContract Token
norentm
ordenttm
exch_tm
snoordt0 for profit leg and 1 for stoploss leg
snonumThis field will be present for product H and B; and only if it is profit/sl order.

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkOrder book failure indication.
request_timeResponse received time.
emsgError message

Sample Success Output : Success response : [ { “stat” : “Ok”, “exch” : “NSE” , “tsym” : “ACC-EQ” , “norenordno” : “20062500000001223”, “prc” : “127230”, “qty” : “100”, “prd” : “C”, “status”: “Open”, “trantype” : “B”, “prctyp” : ”LMT”, “fillshares” : “0”, “avgprc” : “0”, “exchordid” : “250620000000343421”, “uid” : “VIDYA”, “actid” : “CLIENT1”, “ret” : “DAY”, “amo” : “Yes” }, { “stat” : “Ok”, “exch” : “NSE” , “tsym” : “ABB-EQ” , “norenordno” : “20062500000002543”, “prc” : “127830”, “qty” : “50”, “prd” : “C”, “status”: “REJECT”, “trantype” : “B”, “prctyp” : ”LMT”, “fillshares” : “0”, “avgprc” : “0”, “rejreason” : “Insufficient funds” “uid” : “VIDYA”, “actid” : “CLIENT1”, “ret” : “DAY”, “amo” : “No” } ]

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Session Expired : Invalid Session Key" }

Trade Book

List of Trades of the account

Example:

ret = api.get_trade_book()
print(ret)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
actid*Account Id of logged in user

Response Details :

Response data will be in json Array of objects with below fields in case of success.

Json FieldsPossible valueDescription
statOk or Not_OkOrder book success or failure indication.
exchExchange Segment
tsymTrading symbol / contract on which order is placed.
norenordnoNoren Order Number
qtyOrder Quantity
prdDisplay product alias name, using prarr returned in user details.
trantypeB / STransaction type of the order
prctypLMT / MKTPrice type
fillsharesTotal Traded Quantity of this order
avgprcAverage trade price of total traded quantity
exchordidExchange Order Number
remarksAny message Entered during order entry.
retDAY / IOC / EOSOrder validity
uid
actid
ppPrice precision
tiTick size
lsLot size
cstFrmCustom Firm
fltmFill Time
flidFill ID
flqtyFill Qty
flprcFill Price
ordersourceOrder Source
tokenToken

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkOrder book failure indication.
request_timeResponse received time.
emsgError message

Sample Success Output :

[ { "stat": "Ok", "norenordno": "20121300065715", "uid": "FA12345", "actid": "FA12345", "exch": "NSE", "prctyp": "LMT", "ret": "DAY", "prd": "M", "flid": "102", "fltm": "01-01-1980 00:00:00", "trantype": "S", "tsym": "ACCELYA-EQ", "qty": "180", "token": "7053", "fillshares": "180", "flqty": "180", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "flprc": "800.00", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6857" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "FA12345", "actid": "FA12345", "exch": "NSE", "prctyp": "LMT", "ret": "DAY", "prd": "M", "flid": "101", "fltm": "01-01-1980 00:00:00", "trantype": "B", "tsym": "ACCELYA-EQ", "qty": "180", "token": "7053", "fillshares": "180", "flqty": "180", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "flprc": "800.00", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6858" } ]

single order history(orderno)

history an order

orderno = ret['norenordno'] #from placeorder return value
ret = api.single_order_history(orderno=orderno)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
norenordno*Noren Order Number

Response Details :

Response data will be in json Array of objects with below fields in case of success.

Json FieldsPossible valueDescription
statOk or Not_OkOrder book success or failure indication.
exchExchange Segment
tsymTrading symbol / contract on which order is placed.
norenordnoNoren Order Number
prcOrder Price
qtyOrder Quantity
prdDisplay product alias name, using prarr returned in user details.
status
rpt(fill/complete etc)
trantypeB / STransaction type of the order
prctypLMT / MKTPrice type
fillsharesTotal Traded Quantity of this order
avgprcAverage trade price of total traded quantity
rejreasonIf order is rejected, reason in text form
exchordidExchange Order Number
cancelqtyCanceled quantity for order which is in status cancelled.
remarksAny message Entered during order entry.
dscqtyOrder disclosed quantity.
trgprcOrder trigger price
retDAY / IOC / EOSOrder validity
uid
actid
bpprcBook Profit Price applicable only if product is selected as B (Bracket order )
blprcBook loss Price applicable only if product is selected as H and B (High Leverage and Bracket order )
trailprcTrailing Price applicable only if product is selected as H and B (High Leverage and Bracket order )
amoYes / No
ppPrice precision
tiTick size
lsLot size
tokenContract Token
norentm
ordenttm
exch_tm

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkOrder book failure indication.
request_timeResponse received time.
emsgError message

Sample Success Output :

[ { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO01", "actid": "DEMO01", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "avgprc": "800.00", "dscqty": "0", "prd": "M", "status": "COMPLETE", "rpt": "Fill", "fillshares": "180", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6858" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO01", "actid": "DEMO01", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "dscqty": "0", "prd": "M", "status": "OPEN", "rpt": "New", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6858" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO1", "actid": "DEMO1", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "dscqty": "0", "prd": "M", "status": "PENDING", "rpt": "PendingNew", "norentm": "19:59:32 13-12-2020", "remarks": "WC TEST Order" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO1", "actid": "DEMO1", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "prd": "M", "status": "PENDING", "rpt": "NewAck", "norentm": "19:59:32 13-12-2020", "remarks": "WC TEST Order" } ]

get_holdings(product_type)

retrieves the holdings as a list

Example:

ret = api.get_holdings()

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
actid*Account id of the logged in user.
prd*Product name

Response Details : Response data will be in json format with below fields in case of Success:

Json FieldsPossible valueDescription
statOk or Not_OkHolding request success or failure indication.
exch_tsymArray of objects exch_tsym objects as defined below.
holdqtyHolding quantity
dpqtyDP Holding quantity
npoadqtyNon Poa display quantity
colqtyCollateral quantity
benqtyBeneficiary quantity
unplgdqtyUnpledged quantity
brkcolqtyBroker Collateral
btstqtyBTST quantity
btstcolqtyBTST Collateral quantity
usedqtyHolding used today
upldprcAverage price uploaded along with holdings
Notes:
Valuation : btstqty + holdqty + brkcolqty + unplgdqty + benqty + Max(npoadqty, dpqty) - usedqty
Salable: btstqty + holdqty + unplgdqty + benqty + dpqty - usedqty

Exch_tsym object:

Json Fields of object in values ArrayPossible valueDescription
exchNSE, BSE, NFO ...Exchange
tsymTrading symbol of the scrip (contract)
tokenToken of the scrip (contract)
ppPrice precision
tiTick size
lsLot size

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkPosition book request failure indication.
request_timeResponse received time.
emsgError message

Sample Success Response : [
{ "stat":"Ok", "exch_tsym":[ { "exch":"NSE", "token":"13", "tsym":"ABB-EQ" } ], "holdqty":"2000000", "colqty":"200", "btstqty":"0", "btstcolqty":"0", "usedqty":"0", "upldprc" : "1800.00" }, { "stat":"Ok", "exch_tsym":[ { "exch":"NSE", "token":"22", "tsym":"ACC-EQ" } ], "holdqty":"2000000", "colqty":"200", "btstqty":"0", "btstcolqty":"0", "usedqty":"0", "upldprc" : "1400.00" } ]

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Invalid Input : Missing uid or actid or prd." }

get_positions()

retrieves the overnight and day positions as a list

Example:

ret = api.get_positions()
mtm = 0
pnl = 0
for i in ret:
    mtm += float(i['urmtom'])
    pnl += float(i['rpnl'])
    day_m2m = mtm + pnl
print(f'{day_m2m} is your Daily MTM')

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
actid*Account id of the logged in user.

Response Details :

Response data will be in json format with Array of Objects with below fields in case of success.

Json FieldsPossible valueDescription
statOk or Not_OkPosition book success or failure indication.
exchExchange segment
tsymTrading symbol / contract.
tokenContract token
uidUser Id
actidAccount Id
prdProduct name to be shown.
netqtyNet Position quantity
netavgprcNet position average price
daybuyqtyDay Buy Quantity
daysellqtyDay Sell Quantity
daybuyavgprcDay Buy average price
daysellavgprcDay buy average price
daybuyamtDay Buy Amount
daysellamtDay Sell Amount
cfbuyqtyCarry Forward Buy Quantity
cforgavgprcOriginal Avg Price
cfsellqtyCarry Forward Sell Quantity
cfbuyavgprcCarry Forward Buy average price
cfsellavgprcCarry Forward Buy average price
cfbuyamtCarry Forward Buy Amount
cfsellamtCarry Forward Sell Amount
lpLTP
rpnlRealizedPNL
urmtomUnrealizedMTOM.
bepBreak even price
openbuyqty
opensellqty
openbuyamt
opensellamt
openbuyavgprc
opensellavgprc
mult
pp
prcftrgnpn/(gdpd).
tiTick size
lsLot size
request_timeThis will be present only in a failure response.

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkPosition book request failure indication.
request_timeResponse received time.
emsgError message

Sample Success Response : [ { "stat":"Ok", "uid":"POORNA", "actid":"POORNA", "exch":"NSE", "tsym":"ACC-EQ", "prarr":"C", "pp":"2", "ls":"1", "ti":"5.00", "mult":"1", "prcftr":"1.000000", "daybuyqty":"2", "daysellqty":"2", "daybuyamt":"2610.00", "daybuyavgprc":"1305.00", "daysellamt":"2610.00", "daysellavgprc":"1305.00", "cfbuyqty":"0", "cfsellqty":"0", "cfbuyamt":"0.00", "cfbuyavgprc":"0.00", "cfsellamt":"0.00", "cfsellavgprc":"0.00", "openbuyqty":"0", "opensellqty":"23", "openbuyamt":"0.00", "openbuyavgprc":"0.00", "opensellamt":"30015.00", "opensellavgprc":"1305.00", "netqty":"0", "netavgprc":"0.00", "lp":"0.00", "urmtom":"0.00", "rpnl":"0.00", "cforgavgprc":"0.00"

}

]

Sample Failure Response : { "stat":"Not_Ok", "request_time":"14:14:11 26-05-2020", "emsg":"Error Occurred : 5 "no data"" }

get_limits

retrieves the margin and limits set

Request Details:

ParamTypeOptionalDescription
product_typestringTrueretreives the delivery holdings or for a given product
segmentstringTrueCM / FO / FX
exchangestringTrueExchange NSE/BSE/MCX

the response is as follows,

ParamTypeOptionalDescription
statOk or Not_OkFalseLimits request success or failure indication.
actidstringTrueAccount id
prdstringTrueProduct name
segstringTrueSegment CM / FO / FX
exchstringTrueExchange
-------------------------Cash Primary Fields-------------------------------
cashstringTrueCash Margin available
payinstringTrueTotal Amount transferred using Payins today
payoutstringTrueTotal amount requested for withdrawal today
-------------------------Cash Additional Fields-------------------------------
brkcollamtstringTruePrevalued Collateral Amount
unclearedcashstringTrueUncleared Cash (Payin through cheques)
daycashstringTrueAdditional leverage amount / Amount added to handle system errors - by broker.
-------------------------Margin Utilized----------------------------------
marginusedstringTrueTotal margin / fund used today
mtomcurperstringTrueMtom current percentage
-------------------------Margin Used components---------------------
cbustringTrueCAC Buy used
cscstringTrueCAC Sell Credits
rpnlstringTrueCurrent realized PNL
unmtomstringTrueCurrent unrealized mtom
marprtstringTrueCovered Product margins
spanstringTrueSpan used
expostringTrueExposure margin
premiumstringTruePremium used
varelmstringTrueVar Elm Margin
grexpostringTrueGross Exposure
greexpo_dstringTrueGross Exposure derivative
scripbskmarstringTrueScrip basket margin
addscripbskmrgstringTrueAdditional scrip basket margin
brokeragestringTrueBrokerage amount
collateralstringTrueCollateral calculated based on uploaded holdings
grcollstringTrueValuation of uploaded holding pre haircut
-------------------------Additional Risk Limits---------------------------
turnoverlmtstringTrue
pendordvallmtstringTrue
-------------------------Additional Risk Indicators---------------------------
turnoverstringTrueTurnover
pendordvalstringTruePending Order value
-------------------------Margin used detailed breakup fields-------------------------
rzpnl_e_istringTrueCurrent realized PNL (Equity Intraday)
rzpnl_e_mstringTrueCurrent realized PNL (Equity Margin)
rzpnl_e_cstringTrueCurrent realized PNL (Equity Cash n Carry)
rzpnl_d_istringTrueCurrent realized PNL (Derivative Intraday)
rzpnl_d_mstringTrueCurrent realized PNL (Derivative Margin)
rzpnl_f_istringTrueCurrent realized PNL (FX Intraday)
rzpnl_f_mstringTrueCurrent realized PNL (FX Margin)
rzpnl_c_istringTrueCurrent realized PNL (Commodity Intraday)
rzpnl_c_mstringTrueCurrent realized PNL (Commodity Margin)
uzpnl_e_istringTrueCurrent unrealized MTOM (Equity Intraday)
uzpnl_e_mstringTrueCurrent unrealized MTOM (Equity Margin)
uzpnl_e_cstringTrueCurrent unrealized MTOM (Equity Cash n Carry)
uzpnl_d_istringTrueCurrent unrealized MTOM (Derivative Intraday)
uzpnl_d_mstringTrueCurrent unrealized MTOM (Derivative Margin)
uzpnl_f_istringTrueCurrent unrealized MTOM (FX Intraday)
uzpnl_f_mstringTrueCurrent unrealized MTOM (FX Margin)
uzpnl_c_istringTrueCurrent unrealized MTOM (Commodity Intraday)
uzpnl_c_mstringTrueCurrent unrealized MTOM (Commodity Margin)
span_d_istringTrueSpan Margin (Derivative Intraday)
span_d_mstringTrueSpan Margin (Derivative Margin)
span_f_istringTrueSpan Margin (FX Intraday)
span_f_mstringTrueSpan Margin (FX Margin)
span_c_istringTrueSpan Margin (Commodity Intraday)
span_c_mstringTrueSpan Margin (Commodity Margin)
expo_d_istringTrueExposure Margin (Derivative Intraday)
expo_d_mstringTrueExposure Margin (Derivative Margin)
expo_f_istringTrueExposure Margin (FX Intraday)
expo_f_mstringTrueExposure Margin (FX Margin)
expo_c_istringTrueExposure Margin (Commodity Intraday)
expo_c_mstringTrueExposure Margin (Commodity Margin)
premium_d_istringTrueOption premium (Derivative Intraday)
premium_d_mstringTrueOption premium (Derivative Margin)
premium_f_istringTrueOption premium (FX Intraday)
premium_f_mstringTrueOption premium (FX Margin)
premium_c_istringTrueOption premium (Commodity Intraday)
premium_c_mstringTrueOption premium (Commodity Margin)
varelm_e_istringTrueVar Elm (Equity Intraday)
varelm_e_mstringTrueVar Elm (Equity Margin)
varelm_e_cstringTrueVar Elm (Equity Cash n Carry)
marprt_e_hstringTrueCovered Product margins (Equity High leverage)
marprt_e_bstringTrueCovered Product margins (Equity Bracket Order)
marprt_d_hstringTrueCovered Product margins (Derivative High leverage)
marprt_d_bstringTrueCovered Product margins (Derivative Bracket Order)
marprt_f_hstringTrueCovered Product margins (FX High leverage)
marprt_f_bstringTrueCovered Product margins (FX Bracket Order)
marprt_c_hstringTrueCovered Product margins (Commodity High leverage)
marprt_c_bstringTrueCovered Product margins (Commodity Bracket Order)
scripbskmar_e_istringTrueScrip basket margin (Equity Intraday)
scripbskmar_e_mstringTrueScrip basket margin (Equity Margin)
scripbskmar_e_cstringTrueScrip basket margin (Equity Cash n Carry)
addscripbskmrg_d_istringTrueAdditional scrip basket margin (Derivative Intraday)
addscripbskmrg_d_mstringTrueAdditional scrip basket margin (Derivative Margin)
addscripbskmrg_f_istringTrueAdditional scrip basket margin (FX Intraday)
addscripbskmrg_f_mstringTrueAdditional scrip basket margin (FX Margin)
addscripbskmrg_c_istringTrueAdditional scrip basket margin (Commodity Intraday)
addscripbskmrg_c_mstringTrueAdditional scrip basket margin (Commodity Margin)
brkage_e_istringTrueBrokerage (Equity Intraday)
brkage_e_mstringTrueBrokerage (Equity Margin)
brkage_e_cstringTrueBrokerage (Equity CAC)
brkage_e_hstringTrueBrokerage (Equity High Leverage)
brkage_e_bstringTrueBrokerage (Equity Bracket Order)
brkage_d_istringTrueBrokerage (Derivative Intraday)
brkage_d_mstringTrueBrokerage (Derivative Margin)
brkage_d_hstringTrueBrokerage (Derivative High Leverage)
brkage_d_bstringTrueBrokerage (Derivative Bracket Order)
brkage_f_istringTrueBrokerage (FX Intraday)
brkage_f_mstringTrueBrokerage (FX Margin)
brkage_f_hstringTrueBrokerage (FX High Leverage)
brkage_f_bstringTrueBrokerage (FX Bracket Order)
brkage_c_istringTrueBrokerage (Commodity Intraday)
brkage_c_mstringTrueBrokerage (Commodity Margin)
brkage_c_hstringTrueBrokerage (Commodity High Leverage)
brkage_c_bstringTrueBrokerage (Commodity Bracket Order)
peak_marstringTruePeak margin used by the client
request_timestringTrueThis will be present only in a successful response.
emsgstringTrueThis will be present only in a failure response.

Sample Success Response : { "request_time":"18:07:31 29-05-2020", "stat":"Ok", "cash":"1500000000000000.00", "payin":"0.00", "payout":"0.00", "brkcollamt":"0.00", "unclearedcash":"0.00", "daycash":"0.00", "turnoverlmt":"50000000000000.00", "pendordvallmt":"2000000000000000.00", "turnover":"3915000.00", "pendordval":"2871000.00", "marginused":"3945540.00", "mtomcurper":"0.00", "urmtom":"30540.00", "grexpo":"3915000.00", "uzpnl_e_i":"15270.00", "uzpnl_e_m":"61080.00", "uzpnl_e_c":"-45810.00" }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Server Timeout : " } Market Info

span_calculator(actid,positionlist)

This calculates the margin requirement for a list of input positions.

Example:

ret = api.span_calculator(actid,positionlist)

Request Details :

Json FieldsPossible valueDescription
actid*Any Account id, preferably actual account id if sending from post login screen.
pos*Array of json objects. (object fields given in below table)

Position structure as follows:

Json FieldsPossible valueDescription
prdC / M / HProduct
exchNFO, CDS, MCX ...Exchange
instnameFUTSTK, FUTIDX, OPTSTK, FUTCUR...Instrument name
symnameUSDINR, ACC, ABB,NIFTY..Symbol name
exd29-DEC-2022DD-MMM-YYYY format
opttCE, PEOption Type
strprc11900.00, 71.0025Strike price
buyqtyBuy Open Quantity
sellqtySell Open Quantity
netqtyNet traded quantity

Response Details :

Json FieldsPossible valueDescription
statOk or Not_OkMarket watch success or failure indication.
spanSpan value
expoIExposure margin
span_tradeSpan value ignoring input fields buyqty, sellqty
expo_tradeExposure margin ignoring input fields buyqty, sellqty

Sample Success Response : { "request_time": "11:01:59 25-11-2022", "stat": "Ok", "span": "19416.00", "expo": "4338.34", "span_trade": "19416.00", "expo_trade": "4338.34" }

get_option_greek(expiredate,StrikePrice,SpotPrice,InitRate,Volatility,OptionType)

Options greeeks computed the delta, thetha, vega , rho values.

Example:

ret = api.option_greek(expiredate ='24-NOV-2022',StrikePrice='150',SpotPrice  = '200',InitRate  = '100',Volatility = '10',OptionType='CE')

Request Details :

Json FieldsPossible valueDescription
exd*Expiry Date
strprc*Strike Price
sptprc*Spot Price
int_rate*Init Rate
volatility*Volatility
opttCE or PEOption Type

Response Details :

Json FieldsPossible valueDescription
statOk or Not_Oksuccess or failure indication.
request_timeThis will be present only in a successful response.
cal_priceCal Price
put_pricePut Price
cal_deltaCal Delta
put_deltaPut Delta
cal_gammaCal Gamma
put_gammaPut Gamma
cal_thetaCal Theta
put_thetaPut Theta
cal_deltaCal Delta
cal_rhoCal Rho
put_rhoPut Rho
cal_vegoCal Vego
put_vegoPut Vego

Sample Success Response : { "request_time":"17:22:58 28-07-2021", "stat":"OK", "cal_price":"1441", "put_price":"0.417071", "cal_delta":"0.997304", "put_delta":"-0.002696", "cal_gamma":"0.000001", "put_gamma":"0.000001", "cal_theta":"-31.535015", "put_theta":"-31.401346", "cal_rho":"0.000119", "put_rho":"-0.016590", "cal_vego":"0.006307", put_vego":"0.006307" }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Invalid Input : jData is Missing." }

scripmasters:

The scrip masters can be downloaded from the following links

https://api.shoonya.com/NSE_symbols.txt.zip

https://api.shoonya.com/NFO_symbols.txt.zip

https://api.shoonya.com/CDS_symbols.txt.zip

https://api.shoonya.com/MCX_symbols.txt.zip

https://api.shoonya.com/BSE_symbols.txt.zip

https://api.shoonya.com/BFO_symbols.txt.zip

example is provided in test/test_download_masters.py

##Since this is a huge file, users are recommended to download it once a day and store it locally.

searchscrip(exchange, searchtext):

Search for scrip or contract and its properties

The call can be made to get the exchange provided token for a scrip or alternately can search for a partial string to get a list of matching scrips Trading Symbol:

SymbolName + ExpDate + 'F' for all data having InstrumentName starting with FUT

SymbolName + ExpDate + 'P' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType PE

SymbolName + ExpDate + 'C' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType C

For MCX, F to be ignored for FUT instruments

Example:

exch  = 'NFO'
query = 'BANKNIFTY 30DEC CE' # multiple criteria to narrow results 
ret = api.searchscrip(exchange=exch, searchtext=query)

if ret != None:
    symbols = ret['values']
    for symbol in symbols:
        print('{0} token is {1}'.format(symbol['tsym'], symbol['token']))

Example 2:

api.searchscrip(exchange='NSE', searchtext='REL')

This will reply as following

{
    "stat": "Ok",
    "values": [
        {
            "exch": "NSE",
            "token": "18069",
            "tsym": "REL100NAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "24225",
            "tsym": "RELAXO-EQ"
        },
        {
            "exch": "NSE",
            "token": "4327",
            "tsym": "RELAXOFOOT-EQ"
        },
        {
            "exch": "NSE",
            "token": "18068",
            "tsym": "RELBANKNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "2882",
            "tsym": "RELCAPITAL-EQ"
        },
        {
            "exch": "NSE",
            "token": "18070",
            "tsym": "RELCONSNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "18071",
            "tsym": "RELDIVNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "18072",
            "tsym": "RELGOLDNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "2885",
            "tsym": "RELIANCE-EQ"
        },
        {
            "exch": "NSE",
            "token": "15068",
            "tsym": "RELIGARE-EQ"
        },
        {
            "exch": "NSE",
            "token": "553",
            "tsym": "RELINFRA-EQ"
        },
        {
            "exch": "NSE",
            "token": "18074",
            "tsym": "RELNV20NAV-EQ"
        }
    ]
}

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
stext*Search Text
exchExchange (Select from ‘exarr’ Array provided in User Details response)

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkMarket watch success or failure indication.
valuesArray of json objects. (object fields given in below table)
emsgThis will be present only in case of errors.
Json Fields of object in values ArrayPossible valueDescription
exchNSE, BSE, NFO ...Exchange
tsymTrading symbol of the scrip (contract)
tokenToken of the scrip (contract)
ppPrice precision
tiTick size
lsLot size

Sample Success Response :

{ "stat": "Ok", "values": [ { "exch": "NSE", "token": "18069", "tsym": "REL100NAV-EQ" }, { "exch": "NSE", "token": "24225", "tsym": "RELAXO-EQ" }, { "exch": "NSE", "token": "4327", "tsym": "RELAXOFOOT-EQ" }, { "exch": "NSE", "token": "18068", "tsym": "RELBANKNAV-EQ" }, { "exch": "NSE", "token": "2882", "tsym": "RELCAPITAL-EQ" }, { "exch": "NSE", "token": "18070", "tsym": "RELCONSNAV-EQ" }, { "exch": "NSE", "token": "18071", "tsym": "RELDIVNAV-EQ" }, { "exch": "NSE", "token": "18072", "tsym": "RELGOLDNAV-EQ" }, { "exch": "NSE", "token": "2885", "tsym": "RELIANCE-EQ" }, { "exch": "NSE", "token": "15068", "tsym": "RELIGARE-EQ" }, { "exch": "NSE", "token": "553", "tsym": "RELINFRA-EQ" }, { "exch": "NSE", "token": "18074", "tsym": "RELNV20NAV-EQ" } ] }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"No Data : " }

get_security_info(exchange, token):

gets the complete details and its properties

Example:

exch  = 'NSE'
token = '22'
ret = api.get_security_info(exchange=exch, token=token)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
exchExchange
tokenContract Token

Response Details :

Response data will have below fields.

Json FieldsPossible valueDescription
request_timeIt will be present only in a successful response.
statOk or Not_OkMarket watch success or failure indication.
exchNSE, BSE, NFO ...Exchange
tsymTrading Symbol
cnameCompany Name
symnamSymbol Name
segSegment
exdExpiry Date
instnameIntrument Name
strprcStrike Price
opttOption Type
isinISIN
tiTick Size
lsLot Size
ppPrice precision
multMultiplier
gp_ndgn/gd * pn/pd
prcuntPrice Units
prcqqtyPrice Quote Qty
trduntTrade Units
deluntDelivery Units
frzqtyFreeze Qty
gsmindscripupdate Gsm Ind
elmbmrgElm Buy Margin
elmsmrgElm Sell Margin
addbmrgAdditional Long Margin
addsmrgAdditional Short Margin
splbmrgSpecial Long Margin
splsmrgSpecial Short Margin
delmrgDelivery Margin
tenmrgTender Margin
tenstrdTender Start Date
tenenddTender End Eate
exestrdExercise Start Date
exeenddExercise End Date
elmmrgElm Margin
varmrgVar Margin
expmrgExposure Margin
tokenContract Token
prcftr_d((GN / GD) * (PN/PD))

Sample Success Response : { "request_time": "17:43:38 31-10-2020", "stat": "Ok", "exch": "NSE", "tsym": "ACC-EQ", "cname": "ACC LIMITED", "symname": "ACC", "seg": "EQT", "instname": "EQ", "isin": "INE012A01025", "pp": "2", "ls": "1", "ti": "0.05", "mult": "1", "prcftr_d": "(1 / 1 ) * (1 / 1)", "trdunt": "", "delunt": "ACC", "token": "22", "varmrg": "40.00" }

Sample Failure Response : { "stat":"Not_Ok", "request_time":"10:50:54 10-12-2020", "emsg":"Error Occurred : 5 "no data"" }

get_quotes(exchange, token):

gets the complete details and its properties

Example:

exch  = 'NSE'
token = '22'
ret = api.get_quotes(exchange=exch, token=token)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
exchExchange
tokenContract Token

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkWatch list update success or failure indication.
request_timeIt will be present only in a successful response.
exchNSE, BSE, NFO ...Exchange
tsymTrading Symbol
cnameCompany Name
symnameSymbol Name
segSegment
instnameInstrument Name
isinISIN
ppPrice precision
lsLot Size
tiTick Size
multMultiplier
ucUpper circuit limitlc
lcLower circuit limit
prcftr_dPrice factor
tokenToken
lpLTP
oOpen Price
hDay High Price
lDay Low Price
vVolume
ltqLast trade quantity
lttLast trade time
bp1Best Buy Price 1
sp1Best Sell Price 1
bp2Best Buy Price 2
sp2Best Sell Price 2
bp3Best Buy Price 3
sp3Best Sell Price 3
bp4Best Buy Price 4
sp4Best Sell Price 4
bp5Best Buy Price 5
sp5Best Sell Price 5
bq1Best Buy Quantity 1
sq1Best Sell Quantity 1
bq2Best Buy Quantity 2
sq2Best Sell Quantity 2
bq3Best Buy Quantity 3
sq3Best Sell Quantity 3
bq4Best Buy Quantity 4
sq4Best Sell Quantity 4
bq5Best Buy Quantity 5
sq5Best Sell Quantity 5
bo1Best Buy Orders 1
so1Best Sell Orders 1
bo2Best Buy Orders 2
so2Best Sell Orders 2
bo3Best Buy Orders 3
so3Best Sell Orders 3
bo4Best Buy Orders 4
so4Best Sell Orders 4
bo5Best Buy Orders 5
so5Best Sell Orders 5

Sample Success Response : { "request_time":"12:05:21 18-05-2021", "stat":"Ok" ,"exch":"NSE", "tsym":"ACC-EQ", "cname":"ACC LIMITED", "symname":"ACC", "seg":"EQT", "instname":"EQ", "isin":"INE012A01025", "pp":"2", "ls":"1", "ti":"0.05", "mult":"1", "uc":"2093.95", "lc":"1713.25", "prcftr_d":"(1 / 1 ) * (1 / 1)", "token":"22", "lp":"0.00", "h":"0.00", "l":"0.00", "v":"0", "ltq":"0", "ltt":"05:30:00", "bp1":"2000.00", "sp1":"0.00", "bp2":"0.00", "sp2":"0.00", "bp3":"0.00", "sp3":"0.00", "bp4":"0.00", "sp4":"0.00", "bp5":"0.00", "sp5":"0.00", "bq1":"2", "sq1":"0", "bq2":"0", "sq2":"0", "bq3":"0", "sq3":"0", "bq4":"0", "sq4":"0", "bq5":"0", "sq5":"0", "bo1":"2", "so1":"0", "bo2":"0", "so2":"0", "bo3":"0", "so3":"0", "bo4":"0", "so4":"0", "bo5":"0", "So5":"0" }

Sample Failure Response : { "stat":"Not_Ok", "request_time":"10:50:54 10-12-2020", "emsg":"Error Occurred : 5 "no data"" }

get_time_price_series(exchange, token, starttime, endtime, interval):

gets the chart data for the symbol

Example:

lastBusDay = datetime.datetime.today()
lastBusDay = lastBusDay.replace(hour=0, minute=0, second=0, microsecond=0)
ret = api.get_time_price_series(exchange='NSE', token='22', starttime=lastBusDay.timestamp(), interval=5)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
exch*Exchange
token*
stStart time (seconds since 1 jan 1970)
etEnd Time (seconds since 1 jan 1970)
intrv“1”, ”3”, “5”, “10”, “15”, “30”, “60”, “120”, “240”Candle size in minutes (optional field, if not given assume to be “1”)

Response Details :

Response data will be in json format in case for failure.

Json FieldsPossible valueDescription
statNot_OkTPData failure indication.
emsgThis will be present only in case of errors.

Response data will be in json format in case for success.

Json FieldsPossible valueDescription
statOkTPData success indication.
timeDD/MM/CCYY hh:mm:ss
intoInterval open
inthInterval high
intlInterval low
intcInterval close
intvwapInterval vwap
intvInterval volume
vvolume
intoiInterval io change
oioi

Sample Success Response : [ { "stat":"Ok", "time":"02-06-2020 15:46:23", "into":"0.00", "inth":"0.00", "intl":"0.00", "intc":"0.00", "intvwap":"0.00", "intv":"0", "intoi":"0", "v":"980515", "oi":"128702" }, { "stat":"Ok", "time":"02-06-2020 15:45:23", "into":"0.00", "inth":"0.00", "intl":"0.00", "intc":"0.00", "intvwap":"0.00", "intv":"0", "intoi":"0", "v":"980515", "oi":"128702" }, { "stat":"Ok", "time":"02-06-2020 15:44:23", "into":"0.00", "inth":"0.00", "intl":"0.00", "intc":"0.00", "intvwap":"0.00", "intv":"0", "intoi":"0", "v":"980515", "oi":"128702" }, { "stat":"Ok", "time":"02-06-2020 15:43:23", "into":"1287.00", "inth":"1287.00", "intl":"0.00", "intc":"1287.00", "intvwap":"128702.00", "intv":"4", "intoi":"128702", "v":"980515", "oi":"128702" }, { "stat":"Ok", "time":"02-06-2020 15:42:23", "into":"0.00", "inth":"0.00", "intl":"0.00", "intc":"0.00", "intvwap":"0.00", "intv":"0", "intoi":"0", "v":"980511", "oi":"128702" } ]

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Session Expired : Invalid Session Key" }

get_daily_price_series(Symbol name, From date, To date):

gets the chart date for the symbol

Example:

ret =api.get_daily_price_series(exchange="NSE",tradingsymbol="PAYTM-EQ",startdate="457401600",enddate="480556800")

Request Details :

Json FieldsPossible valueDescription
sym*Symbol name
from*From date
to*To date

Response Details :

Json FieldsPossible valueDescription
statOkTPData success indication.
timeDD/MM/CCYY hh:mm:ss
intoInterval open
inthInterval high
intlInterval low
intcInterval close
ssboeDate,Seconds in 1970 format
intvInterval volume

Sample Success Response : [ "{ "time":"21-SEP-2022", "into":"2496.75", "inth":"2533.00", "intl":"2495.00", "intc":"2509.75", "ssboe":"1663718400", "intv":"4249172.00" }", "{ "time":"15-SEP-2022", "into":"2583.00", "inth":"2603.55", "intl":"2556.75", "intc":"2562.70", "ssboe":"1663200000", "intv":"4783723.00" }", "{ "time":"28-JUN-2021", "into":"2122.00", "inth":"2126.50", "intl":"2081.00", "intc":"2086.00", "ssboe":"1624838400", "intv":"9357852.00" }" ]

get_option_chain(exchange, tradingsymbol, strikeprice, count):

gets the contracts of related strikes

ParamTypeOptionalDescription
exchangestringFalseExchange (UI need to check if exchange in NFO / CDS / MCX / or any other exchange which has options, if not don't allow)
tradingsymbolstringFalseTrading symbol of any of the option or future. Option chain for that underlying will be returned. (use url encoding to avoid special char error for symbols like M&M)
strikepricefloatFalseMid price for option chain selection
countintTrueNumber of strike to return on one side of the mid price for PUT and CALL. (example cnt is 4, total 16 contracts will be returned, if cnt is is 5 total 20 contract will be returned)

the response is as follows,

ParamTypeOptionalDescription
statstringTrueok or Not_ok
valuesstringTrueproperties of the scrip
emsgstringFalseError Message
ParamTypeOptionalDescription
exchstringFalseExchange
tsymstringFalseTrading Symbol of Contract
tokenstringFalseContract token
opttstringFalseOption type
strprcstringFalseStrike Price
ppstringFalsePrice Precision
tistringFalseTick Size
lsstringFalseLot Size

start_websocket()

Note: Please ensure that only a single web-socket connection is started. Opening multiple web-socket connections is not supported by the API. starts the websocket, WebSocket feed has 2 types of ticks( t=touchline d=depth)and 2 stages (k=acknowledgement, f=further change in tick).

ParamTypeOptionalDescription
subscribe_callbackfunctionFalsecallback for market updates
order_update_callbackfunctionFalsecallback for order updates
socket_open_callbackfunctionFalsecallback when socket is open (reconnection also)
socket_close_callbackfunctionFalsecallback when socket is closed

subscribe_orders()

get order and trade update callbacks

Subscription Acknowledgement:

Json FieldsPossible valueDescription
tok‘ok’ represents order update subscription acknowledgement

Order Update subscription Updates :

Json FieldsPossible valueDescription
tom‘om’ represents touchline feed
norenordnoNoren Order Number
uidUser Id
actidAccount ID
exchExchange
tsymTrading symbol
qtyOrder quantity
prcOrder Price
prdProduct
statusOrder status (New, Replaced, Complete, Rejected etc)
reporttypeOrder event for which this message is sent out. (Fill, Rejected, Canceled)
trantypeOrder transaction type, buy or sell
prctypOrder price type (LMT, MKT, SL-LMT, SL-MKT)
retOrder retention type (DAY, EOS, IOC,...)
fillsharesTotal Filled shares for this order
avgprcAverage fill price
fltmFill Time(present only when reporttype is Fill)
flidFill ID (present only when reporttype is Fill)
flqtyFill Qty(present only when reporttype is Fill)
flprcFill Price(present only when reporttype is Fill)
rejreasonOrder rejection reason, if rejected
exchordidExchange Order ID
cancelqtyCanceled quantity, in case of canceled order
remarksUser added tag, while placing order
dscqtyDisclosed quantity
trgprcTrigger price for SL orders
snonumThis will be present for child orders in case of cover and bracket orders, if present needs to be sent during exit
snoordtThis will be present for child orders in case of cover and bracket orders, it will indicate whether the order is profit or stoploss
blprcThis will be present for cover and bracket parent order. This is the differential stop loss trigger price to be entered.
bpprcThis will be present for bracket parent order. This is the differential profit price to be entered.
trailprcThis will be present for cover and bracket parent order. This is required if trailing ticks is to be enabled.
exch_tmThis will have the exchange update time

subscribe([instruments])

send a list of instruments to watch, feed_type specifies the type of data requested ( t=touchline d=depth)

t='tk' is sent once on subscription for each instrument. this will have all the fields with the most recent value thereon t='tf' is sent for fields that have changed.

For example
quote event: 03-12-2021 11:54:44{'t': 'tk', 'e': 'NSE', 'tk': '11630', 'ts': 'NTPC-EQ', 'pp': '2', 'ls': '1', 'ti': '0.05', 'lp': '118.55', 'h': '118.65', 'l': '118.10', 'ap': '118.39', 'v': '162220', 'bp1': '118.45', 'sp1': '118.50', 'bq1': '26', 'sq1': '6325'}
quote event: 03-12-2021 11:54:45{'t': 'tf', 'e': 'NSE', 'tk': '11630', 'lp': '118.45', 'ap': '118.40', 'v': '166637', 'sp1': '118.55', 'bq1': '3135', 'sq1': '30'}
quote event: 03-12-2021 11:54:46{'t': 'tf', 'e': 'NSE', 'tk': '11630', 'lp': '118.60'}

in the example above we see first message t='tk' with all the values, 2nd message has lasttradeprice avg price and few other fields with value changed.. note bp1 isnt sent as its still 118.45 in the next tick ( 3rd message) only last price is changed to 118.6

This method can be used to subscribe indices as well such as Nifty-50 [NSE|26000], BankNifty[NSE|26009]

ParamTypeOptionalDescription
instrumentslistFalselist of instruments [NSE|22,CDS|1]

Subscription Acknowledgement:

Number of Acknowledgements for a single subscription will be the same as the number of scrips mentioned in the key (k) field.

Json FieldsPossible valueDescription
ttk‘tk’ represents touchline acknowledgement
eNSE, BSE, NFO ..Exchange name
tk22Scrip Token
pp2 for NSE, BSE & 4 for CDS USDINRPrice precision
tsTrading Symbol
tiTick size
lsLot size
lpLTP
pcPercentage change
vvolume
oOpen price
hHigh price
lLow price
cClose price
apAverage trade price
oiOpen interest
poiPrevious day closing Open Interest
toiTotal open interest for underlying
bq1Best Buy Quantity 1
bp1Best Buy Price 1
sq1Best Sell Quantity 1
sp1Best Sell Price 1

TouchLine subscription Updates : Accept for t, e, and tk other fields may / may not be present.

Json FieldsPossible valueDescription
ttf‘tf’ represents touchline acknowledgement
eNSE, BSE, NFO ..Exchange name
tk22Scrip Token
lpLTP
pcPercentage change
vvolume
oOpen price
hHigh price
lLow price
cClose price
apAverage trade price
oiOpen interest
poiPrevious day closing Open Interest
toiTotal open interest for underlying
bq1Best Buy Quantity 1
bp1Best Buy Price 1
sq1Best Sell Quantity 1
sp1Best Sell Price 1

Depth Messages will be as below

Json FieldsPossible valueDescription
tdk?dk? represents depth acknowledgement
eNSE, BSE, NFO ..Exchange name
tk22Scrip Token
lpLTP
pcPercentage change
vvolume
oOpen price
hHigh price
lLow price
cClose price
apAverage trade price
lttLast trade time
ltqLast trade quantity
tbqTotal Buy Quantity
tsqTotal Sell Quantity
bq1Best Buy Quantity 1
bq2Best Buy Quantity 2
bq3Best Buy Quantity 3
bq4Best Buy Quantity 4
bq5Best Buy Quantity 5
bp1Best Buy Price 1
bp2Best Buy Price 2
bp3Best Buy Price 3
bp4Best Buy Price 4
bp5Best Buy Price 5
bo1Best Buy Orders 1
bo2Best Buy Orders 2
bo3Best Buy Orders 3
bo4Best Buy Orders 4
bo5Best Buy Orders 5
sq1Best Sell Quantity 1
sq2Best Sell Quantity 2
sq3Best Sell Quantity 3
sq4Best Sell Quantity 4
sq5Best Sell Quantity 5
sp1Best Sell Price 1
sp2Best Sell Price 2
sp3Best Sell Price 3
sp4Best Sell Price 4
sp5Best Sell Price 5
so1Best Sell Orders 1
so2Best Sell Orders 2
so3Best Sell Orders 3
so4Best Sell Orders 4
so5Best Sell Orders 5
lcLower Circuit Limit
ucUpper Circuit Limit
52h52 week high low in other exchanges, Life time high low in mcx
52l52 week high low in other exchanges, Life time high low in mcx
oiOpen interest
poiPrevious day closing Open Interest
toiTotal open interest for underlying
ftFeed time

unsubscribe()

send a list of instruments to stop watch


Order States and Report Types

Possible Values for Order States are as follows

PENDING :- The order has been submitted but is awaiting further processing.

CANCELED :- The order has been canceled by the trader before being executed.

OPEN:- The order is active and waiting to be matched with a counterparty.

REJECTED:- The order has been declined due to certain criteria not being met.

COMPLETE:- The order has been successfully executed and completed.

TRIGGER_PENDING:- A specific condition must be met before the order can become active.

INVALID_STATUS_TYPE:- The provided order status is not recognized or valid.

The Orders will have a request status or report type for modify/cancel the possible values are as follows

NewAck :- acknowledgement that a new order request has been received.

ModAck :- acknowledgement that a modification request for an existing order has been received.

CanAck :- acknowledgement that a request to cancel an order has been received.

PendingNew :- The request to place a new order is pending further review.

PendingReplace :- The request to modify an existing order is pending further review.

PendingCancel :- The request to cancel an order is pending further review.

New :- Confirmation that a new order has been successfully placed.

Replaced :- confirmation that an existing order has been successfully modified.

Canceled :- confirmation that an order has been successfully canceled.

Fill :- notification that an order has been fully or partially executed.

Rejected :- notification that an order has been rejected and not executed.

ReplaceRejected :- Notification that a request to modify an order has been rejected.

CancelRejected :- Notification that a request to cancel an order has been rejected.

INVALID_REPORT_TYPE :- The provided report type for modification/cancellation is not recognized or valid.

Example - Getting Started

First configure the endpoints in the api_helper constructor. Thereon provide your credentials and login as follows.

from api_helper import ShoonyaApiPy
import logging

#enable dbug to see request and responses
logging.basicConfig(level=logging.DEBUG)

#start of our program
api = ShoonyaApiPy()

#credentials
user        = '< user id>'
u_pwd       = '< password >'
factor2     = 'OTP/TOTP'
vc          = 'vendor code'
app_key     = 'API key'
imei        = 'uniq identifier'


ret = api.login(userid=user, password=pwd, twoFA=factor2, vendor_code=vc, api_secret=app_key, imei=imei)
print(ret)

Example Symbol/Contract : Example_market.py

This Example shows API usage for finding scrips and its properties

Search Scrips

The call can be made to get the exchange provided token for a scrip or alternately can search for a partial string to get a list of matching scrips Trading Symbol:

SymbolName + ExpDate + 'F' for all data having InstrumentName starting with FUT

SymbolName + ExpDate + 'P' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType PE

SymbolName + ExpDate + 'C' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType C

For MCX, F to be ignored for FUT instruments

api.searchscrip(exchange='NSE', searchtext='REL')

This will reply as following

{
    "stat": "Ok",
    "values": [
        {
            "exch": "NSE",
            "token": "18069",
            "tsym": "REL100NAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "24225",
            "tsym": "RELAXO-EQ"
        },
        {
            "exch": "NSE",
            "token": "4327",
            "tsym": "RELAXOFOOT-EQ"
        },
        {
            "exch": "NSE",
            "token": "18068",
            "tsym": "RELBANKNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "2882",
            "tsym": "RELCAPITAL-EQ"
        },
        {
            "exch": "NSE",
            "token": "18070",
            "tsym": "RELCONSNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "18071",
            "tsym": "RELDIVNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "18072",
            "tsym": "RELGOLDNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "2885",
            "tsym": "RELIANCE-EQ"
        },
        {
            "exch": "NSE",
            "token": "15068",
            "tsym": "RELIGARE-EQ"
        },
        {
            "exch": "NSE",
            "token": "553",
            "tsym": "RELINFRA-EQ"
        },
        {
            "exch": "NSE",
            "token": "18074",
            "tsym": "RELNV20NAV-EQ"
        }
    ]
}

Security Info

This call is done to get the properties of the scrip such as freeze qty and margins

api.get_security_info(exchange='NSE', token='22')

The response for the same would be

{
   "request_time": "17:43:38 31-10-2020",
   "stat": "Ok",
   "exch": "NSE",
   "tsym": "ACC-EQ",
   "cname": "ACC LIMITED",
   "symname": "ACC",
   "seg": "EQT",
   "instname": "EQ",
   "isin": "INE012A01025",
   "pp": "2",
   "ls": "1",
   "ti": "0.05",
   "mult": "1",
   "prcftr_d": "(1 / 1 ) * (1 / 1)",
   "trdunt": "ACC.BO",
   "delunt": "ACC",
   "token": "22",
   "varmrg": "40.00"
}

Subscribe to a live feed

Subscribe to a single token as follows

api.subscribe('NSE|13')

Subscribe to a list of tokens as follows

api.subscribe(['NSE|22', 'BSE|522032'])

First we need to connect to the WebSocket and then subscribe as follows

feed_opened = False

def event_handler_feed_update(tick_data):
    print(f"feed update {tick_data}")

def open_callback():
    global feed_opened
    feed_opened = True


api.start_websocket( order_update_callback=event_handler_order_update,
                     subscribe_callback=event_handler_feed_update, 
                     socket_open_callback=open_callback)

while(feed_opened==False):
    pass

# subscribe to a single token 
api.subscribe('NSE|13')

#subscribe to multiple tokens
api.subscribe(['NSE|22', 'BSE|522032'])

Example - Orders and Trades : example_orders.py

Place Order

Place a Limit order as follows
    api.place_order(buy_or_sell='B', product_type='C',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None,
                        retention='DAY', remarks='my_order_001')
Place a Market Order as follows
    api.place_order(buy_or_sell='B', product_type='C',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='MKT', price=0, trigger_price=None,
                        retention='DAY', remarks='my_order_001')
Place a StopLoss Order as follows
    api.place_order(buy_or_sell='B', product_type='C',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='SL-LMT', price=1500, trigger_price=1450,
                        retention='DAY', remarks='my_order_001')
Place a Cover Order as follows
    api.place_order(buy_or_sell='B', product_type='H',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None,
                        retention='DAY', remarks='my_order_001', bookloss_price = 1490)
Place a Bracket Order as follows
    api.place_order(buy_or_sell='B', product_type='B',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None,
                        retention='DAY', remarks='my_order_001', bookloss_price = 1490, bookprofit_price = 1510)

Modify Order

Modify a New Order by providing the OrderNumber
    api.modify_order(exchange='NSE', tradingsymbol='INFY-EQ', orderno=orderno,
                                   newquantity=2, newprice_type='LMT', newprice=1505)

Cancel Order

Cancel a New Order by providing the Order Number
    api.cancel_order(orderno=orderno)

Subscribe to Order Updates

Connecting to the Websocket will automatically subscribe and provide the order updates in the call back as follows Note: Feed and Order updates are received from the same websocket and needs to be connected once only.

feed_opened = False

def event_handler_order_update(order):
    print(f"order feed {order}")

def open_callback():
    global feed_opened
    feed_opened = True


api.start_websocket( order_update_callback=event_handler_order_update,
                     subscribe_callback=event_handler_feed_update, 
                     socket_open_callback=open_callback)

while(feed_opened==False):
    pass



Contact Us

For any queries, feel free to reach us, by email at apisupport@shoonya.com or call at 0172-4740000 & Also Just visit our website there is a Live chat option.


Author

Kumar Anand


License

Copyright (C) 2021 Kambala Solutions Pvt Ltd- All Rights Reserved Copying of this file, via any medium is strictly prohibited. Proprietary and confidential. All file transfers are logged.


Contributors

kambalatech

48 commits

Shoonya-Dev

21 commits

Nikhesh

18 commits

Shoonya-Dev/ShoonyaApi-py

166

stars

87

commits

Python

primary language

Jul 29, 2024

updated

README

Shoonya API

Api used to connect to Shoonya OMS.

This is a python wrapper or connector to the RestAPI and websocket of Shoonya.

More details are found here https://www.shoonya.com/api-documentation


Build

to build this package and install it on your server please use

pip install -r requirements.txt


API

ShoonyaApi

Symbols

Orders and Trades

Holdings and Limits

Calculators

Websocket API

Example

login(userid, password, twoFA, vendor_code, api_secret, imei)

connect to the broker, only once this function has returned successfully can any other operations be performed Example: #For TOTP Automation, Reffer below Mentioned Command #TOKEN = 'Q65C5R7WJ2AR77VA623OC2SI5D5KM447' #otp = pyotp.TOTP(TOKEN).now()

#credentials
user    = <uid>
pwd     = <password>
factor2 = <OTP/TOTP>
vc      = <vendor code>
app_key = <API key>
imei    = <imei>

ret = api.login(userid=uid, password=pwd, twoFA=factor2, vendor_code=vc, api_secret=app_key, imei=imei)

Request Details :

Json FieldsPossible valueDescription
apkversion*Application version.For Ex. 1.0.0
uid*User Id of the login user
pwd*Shoonya login password.
factor2*OTP or TOTP as entered by the user. (User Needs to be generated from the Shoonya app)
vc*Vendor code provided by noren team, along with connection URLs
appkey*Prism Generated API key
imei*Send mac if users logs in for desktop, imei is from mobile
addldivinfOptional field, Value must be in below format:
ipaddrOptional field
sourceAPI

Response Details :

Json FieldsPossible valueDescription
statOk or Not_OkLogin Success Or failure status
susertokenIt will be present only on login success. This data to be sent in subsequent requests in jKey field and web socket connection while connecting.
lastaccesstimeIt will be present only on login success.
spasswordresetYIf Y Mandatory password reset to be enforced. Otherwise the field will be absent.
exarrJson array of strings with enabled exchange names
unameUser name
prarrJson array of Product Obj with enabled products, as defined below.
actidAccount id
emailEmail Id
brknameBroker id
emsgThis will be present only if Login fails.

Sample Success Response : { "request_time": "20:18:47 19-05-2020", "stat": "Ok", "susertoken": "3b97f4c67762259a9ded6dbd7bfafe2787e662b3870422ddd343a59895f423a0", "lastaccesstime": "1589899727" }

Sample Failure Response : { "request_time": "20:32:14 19-05-2020", "stat": "Not_Ok", "emsg": "Invalid Input : Wrong Password" }

logout()

Terminate the session

Example:

ret = api.logout()

Request Details :

Json FieldsPossible valueDescription
uid*User Id of the login user

Response Details : Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkLogout Success Or failure status
request_timeIt will be present only on successful logout.
emsgThis will be present only if Logout fails.

Sample Success Response : { "stat":"Ok", "request_time":"10:43:41 28-05-2020" }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Server Timeout : " }

place_order(buy_or_sell, product_type,exchange, tradingsymbol, quantity, discloseqty, price_type, price=0.0, trigger_price=None, retention='DAY', amo='NO', remarks=None)

place an order to oms

Example:

ret = api.place_order(buy_or_sell='B', product_type='C',
                        exchange='NSE', tradingsymbol='CANBK-EQ', 
                        quantity=1, discloseqty=0,price_type='SL-LMT', price=200.00, trigger_price=199.50,
                        retention='DAY', remarks='my_order_001')

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
actid*Login users account ID
exch*NSE / NFO / CDS / MCX / BSEExchange (Select from ‘exarr’ Array provided in User Details response)
tsym*RELIANCE-EQ / L&TFH29SEP22P97 / USDINR25NOV22C76 / CRUDEOIL16NOV22P5400 / WHIRLPOOLUnique id of contract on which order to be placed. (Use the Results from Search Script to get the trading symbol & use url encoding to avoid special char error for symbols like M&M)
qty*RELIANCE-EQ:-1 / NIFTY:-50 / BANKNIFTY:-25Order Quantity
prc*Order Price
trgprcOnly to be sent in case of SL / SL-M order.
dscqtyDisclosed quantity (Max 10% for NSE, and 50% for MCX)
prd*C / M / I / B / HProduct name (Select from ‘prarr’ Array provided in User Details response, and if same is allowed for selected, exchange. Show product display name, for user to select, and send corresponding prd in API call) "C" For CNC, "M" FOR NRML, "I" FOR MIS, "B" FOR BRACKET ORDER, "H" FOR COVER ORDER
trantype*B / SB -> BUY, S -> SELL
prctyp*LMT / MKT / SL-LMT / SL-MKT / DS / 2L / 3L
ret*DAY / EOS / IOCRetention type (Show options as per allowed exchanges)
remarksAny tag by user to mark order.
ordersourceMOB / WEB / TTUsed to generate exchange info fields.
bpprcBook Profit Price applicable only if product is selected as B (Bracket order )
blprcBook loss Price applicable only if product is selected as H and B (High Leverage and Bracket order )
trailprcTrailing Price applicable only if product is selected as H and B (High Leverage and Bracket order )
amoYes , If not sent, of Not “Yes”, will be treated as Regular order.
tsym2Trading symbol of second leg, mandatory for price type 2L and 3L (use url encoding to avoid special char error for symbols like M&M)
trantype2Transaction type of second leg, mandatory for price type 2L and 3L
qty2Quantity for second leg, mandatory for price type 2L and 3L
prc2Price for second leg, mandatory for price type 2L and 3L
tsym3Trading symbol of third leg, mandatory for price type 3L (use url encoding to avoid special char error for symbols like M&M)
trantype3Transaction type of third leg, mandatory for price type 3L
qty3Quantity for third leg, mandatory for price type 3L
prc3Price for third leg, mandatory for price type 3L

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkPlace order success or failure indication.
request_timeResponse received time.
norenordnoIt will be present only on successful Order placement to OMS.
emsgThis will be present only if Order placement fails

Sample Success Response: { "request_time": "10:48:03 20-05-2020", "stat": "Ok", "norenordno": "20052000000017" }

Sample Error Response : { "stat": "Not_Ok", "request_time": "20:40:01 19-05-2020", "emsg": "Error Occurred : 2 "invalid input"" }

modify_order(orderno, exchange, tradingsymbol, newquantity,newprice_type, newprice, newtrigger_price, amo):

modify the quantity pricetype or price of an order

Example:

orderno = ret['norenordno'] #from placeorder return value
ret = api.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno,
                                   newquantity=2, newprice_type='MKT', newprice=0.00)
## sl modification
ret = api.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno,
                                   newquantity=2, newprice_type='SL-LMT', newprice=201.00, newtrigger_price=200.00)

Request Details :

Json FieldsPossible valueDescription
exch*Exchange
norenordno*Noren order number, which needs to be modified
prctypLMT / MKT / SL-MKT / SL-LMTThis can be modified.
prcModified / New price
qtyModified / New Quantity
tsym*Unque id of contract on which order was placed. Can’t be modified, must be the same as that of original order. (use url encoding to avoid special char error for symbols like M&M)
retDAY / IOC / EOSNew Retention type of the order
trgprcNew trigger price in case of SL-MKT or SL-LMT
uid*User id of the logged in user.
bpprcBook Profit Price applicable only if product is selected as B (Bracket order )
blprcBook loss Price applicable only if product is selected as H and B (High Leverage and Bracket order )
trailprcTrailing Price applicable only if product is selected as H and B (High Leverage and Bracket order )

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkModify order success or failure indication.
resultNoren Order number of the order modified.
request_timeResponse received time.
emsgThis will be present only if Order modification fails

Sample Success Response : { "request_time":"14:14:08 26-05-2020", "stat":"Ok", "result":"20052600000103" }

Sample Failure Response : { "request_time":"16:03:29 28-05-2020", "stat":"Not_Ok", "emsg":"Rejected : ORA:Order not found" }

cancel_order(orderno)

cancel an order

Example:

orderno = ret['norenordno'] #from placeorder return value
ret = api.cancel_order(orderno=orderno)

Request Details :

Json FieldsPossible valueDescription
norenordno*Noren order number, which needs to be modified
uid*User id of the logged in user.

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkCancel order success or failure indication.
resultNoren Order number of the canceled order.
request_timeResponse received time.
emsgThis will be present only if Order cancelation fails

Sample Success Response : { "request_time":"14:14:10 26-05-2020", "stat":"Ok", "result":"20052600000103" }

Sample Failure Response : { "request_time":"16:01:48 28-05-2020", "stat":"Not_Ok", "emsg":"Rejected : ORA:Order not found to Cancel" }

exit_order(orderno)

exits a cover or bracket order

Request Details :

Json FieldsPossible valueDescription
norenordno*Noren order number, which needs to be modified
prd*H / BAllowed for only H and B products (Cover order and bracket order)
uid*User id of the logged in user.

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkCancel order success or failure indication.
dmsgDisplay message, (will be present only in case of success).
request_timeResponse received time.
emsgThis will be present only if Order cancelation fails

position_product_conversion(exchange, tradingsymbol, quantity, new_product_type, previous_product_type, buy_or_sell, day_or_cf)

Convert a product of a position

Example:

ret = api.get_positions()
#converts the first position from existing product to intraday
p = ret[0]
ret = api.position_product_conversion(p['exch'], p['tsym'], p['netqty'], 'I', p['prd'], 'B', 'DAY')

Request Details :

Json FieldsPossible valueDescription
exch*Exchange
tsym*Unique id of contract on which order was placed. Can’t be modified, must be the same as that of original order. (use url encoding to avoid special char error for symbols like M&M)
qty*Quantity to be converted.
uid*User id of the logged in user.
actid*Account id
prd*Product to which the user wants to convert position.
prevprd*Original product of the position.
trantype*Transaction type
postype*Day / CFConverting Day or Carry forward position
ordersourceMOBFor Logging

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkPosition conversion success or failure indication.
emsgThis will be present only if Position conversion fails.

Sample Success Response : { "request_time":"10:52:12 02-06-2020", "stat":"Ok" }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Invalid Input : Invalid Position Type" }

Order Book

List of Orders placed for the account

Example :

ret = api.get_order_book()
print(ret)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
prdH / M / ...Product name

Response Details :

Response data will be in json Array of objects with below fields in case of success.

Json FieldsPossible valueDescription
statOk or Not_OkOrder book success or failure indication.
exchExchange Segment
tsymTrading symbol / contract on which order is placed.
norenordnoNoren Order Number
prcOrder Price
qtyOrder Quantity
prdDisplay product alias name, using prarr returned in user details.
status
trantypeB / STransaction type of the order
prctypLMT / MKTPrice type
fillsharesTotal Traded Quantity of this order
avgprcAverage trade price of total traded quantity
rejreasonIf order is rejected, reason in text form
exchordidExchange Order Number
cancelqtyCanceled quantity for order which is in status cancelled.
remarksAny message Entered during order entry.
dscqtyOrder disclosed quantity.
trgprcOrder trigger price
retDAY / IOC / EOSOrder validity
uid
actid
bpprcBook Profit Price applicable only if product is selected as B (Bracket order )
blprcBook loss Price applicable only if product is selected as H and B (High Leverage and Bracket order )
trailprcTrailing Price applicable only if product is selected as H and B (High Leverage and Bracket order )
amoYes / No
ppPrice precision
tiTick size
lsLot size
tokenContract Token
norentm
ordenttm
exch_tm
snoordt0 for profit leg and 1 for stoploss leg
snonumThis field will be present for product H and B; and only if it is profit/sl order.

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkOrder book failure indication.
request_timeResponse received time.
emsgError message

Sample Success Output : Success response : [ { “stat” : “Ok”, “exch” : “NSE” , “tsym” : “ACC-EQ” , “norenordno” : “20062500000001223”, “prc” : “127230”, “qty” : “100”, “prd” : “C”, “status”: “Open”, “trantype” : “B”, “prctyp” : ”LMT”, “fillshares” : “0”, “avgprc” : “0”, “exchordid” : “250620000000343421”, “uid” : “VIDYA”, “actid” : “CLIENT1”, “ret” : “DAY”, “amo” : “Yes” }, { “stat” : “Ok”, “exch” : “NSE” , “tsym” : “ABB-EQ” , “norenordno” : “20062500000002543”, “prc” : “127830”, “qty” : “50”, “prd” : “C”, “status”: “REJECT”, “trantype” : “B”, “prctyp” : ”LMT”, “fillshares” : “0”, “avgprc” : “0”, “rejreason” : “Insufficient funds” “uid” : “VIDYA”, “actid” : “CLIENT1”, “ret” : “DAY”, “amo” : “No” } ]

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Session Expired : Invalid Session Key" }

Trade Book

List of Trades of the account

Example:

ret = api.get_trade_book()
print(ret)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
actid*Account Id of logged in user

Response Details :

Response data will be in json Array of objects with below fields in case of success.

Json FieldsPossible valueDescription
statOk or Not_OkOrder book success or failure indication.
exchExchange Segment
tsymTrading symbol / contract on which order is placed.
norenordnoNoren Order Number
qtyOrder Quantity
prdDisplay product alias name, using prarr returned in user details.
trantypeB / STransaction type of the order
prctypLMT / MKTPrice type
fillsharesTotal Traded Quantity of this order
avgprcAverage trade price of total traded quantity
exchordidExchange Order Number
remarksAny message Entered during order entry.
retDAY / IOC / EOSOrder validity
uid
actid
ppPrice precision
tiTick size
lsLot size
cstFrmCustom Firm
fltmFill Time
flidFill ID
flqtyFill Qty
flprcFill Price
ordersourceOrder Source
tokenToken

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkOrder book failure indication.
request_timeResponse received time.
emsgError message

Sample Success Output :

[ { "stat": "Ok", "norenordno": "20121300065715", "uid": "FA12345", "actid": "FA12345", "exch": "NSE", "prctyp": "LMT", "ret": "DAY", "prd": "M", "flid": "102", "fltm": "01-01-1980 00:00:00", "trantype": "S", "tsym": "ACCELYA-EQ", "qty": "180", "token": "7053", "fillshares": "180", "flqty": "180", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "flprc": "800.00", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6857" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "FA12345", "actid": "FA12345", "exch": "NSE", "prctyp": "LMT", "ret": "DAY", "prd": "M", "flid": "101", "fltm": "01-01-1980 00:00:00", "trantype": "B", "tsym": "ACCELYA-EQ", "qty": "180", "token": "7053", "fillshares": "180", "flqty": "180", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "flprc": "800.00", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6858" } ]

single order history(orderno)

history an order

orderno = ret['norenordno'] #from placeorder return value
ret = api.single_order_history(orderno=orderno)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
norenordno*Noren Order Number

Response Details :

Response data will be in json Array of objects with below fields in case of success.

Json FieldsPossible valueDescription
statOk or Not_OkOrder book success or failure indication.
exchExchange Segment
tsymTrading symbol / contract on which order is placed.
norenordnoNoren Order Number
prcOrder Price
qtyOrder Quantity
prdDisplay product alias name, using prarr returned in user details.
status
rpt(fill/complete etc)
trantypeB / STransaction type of the order
prctypLMT / MKTPrice type
fillsharesTotal Traded Quantity of this order
avgprcAverage trade price of total traded quantity
rejreasonIf order is rejected, reason in text form
exchordidExchange Order Number
cancelqtyCanceled quantity for order which is in status cancelled.
remarksAny message Entered during order entry.
dscqtyOrder disclosed quantity.
trgprcOrder trigger price
retDAY / IOC / EOSOrder validity
uid
actid
bpprcBook Profit Price applicable only if product is selected as B (Bracket order )
blprcBook loss Price applicable only if product is selected as H and B (High Leverage and Bracket order )
trailprcTrailing Price applicable only if product is selected as H and B (High Leverage and Bracket order )
amoYes / No
ppPrice precision
tiTick size
lsLot size
tokenContract Token
norentm
ordenttm
exch_tm

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkOrder book failure indication.
request_timeResponse received time.
emsgError message

Sample Success Output :

[ { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO01", "actid": "DEMO01", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "avgprc": "800.00", "dscqty": "0", "prd": "M", "status": "COMPLETE", "rpt": "Fill", "fillshares": "180", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6858" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO01", "actid": "DEMO01", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "dscqty": "0", "prd": "M", "status": "OPEN", "rpt": "New", "norentm": "19:59:32 13-12-2020", "exch_tm": "00:00:00 01-01-1980", "remarks": "WC TEST Order", "exchordid": "6858" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO1", "actid": "DEMO1", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "dscqty": "0", "prd": "M", "status": "PENDING", "rpt": "PendingNew", "norentm": "19:59:32 13-12-2020", "remarks": "WC TEST Order" }, { "stat": "Ok", "norenordno": "20121300065716", "uid": "DEMO1", "actid": "DEMO1", "exch": "NSE", "tsym": "ACCELYA-EQ", "qty": "180", "trantype": "B", "prctyp": "LMT", "ret": "DAY", "token": "7053", "pp": "2", "ls": "1", "ti": "0.05", "prc": "800.00", "prd": "M", "status": "PENDING", "rpt": "NewAck", "norentm": "19:59:32 13-12-2020", "remarks": "WC TEST Order" } ]

get_holdings(product_type)

retrieves the holdings as a list

Example:

ret = api.get_holdings()

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
actid*Account id of the logged in user.
prd*Product name

Response Details : Response data will be in json format with below fields in case of Success:

Json FieldsPossible valueDescription
statOk or Not_OkHolding request success or failure indication.
exch_tsymArray of objects exch_tsym objects as defined below.
holdqtyHolding quantity
dpqtyDP Holding quantity
npoadqtyNon Poa display quantity
colqtyCollateral quantity
benqtyBeneficiary quantity
unplgdqtyUnpledged quantity
brkcolqtyBroker Collateral
btstqtyBTST quantity
btstcolqtyBTST Collateral quantity
usedqtyHolding used today
upldprcAverage price uploaded along with holdings
Notes:
Valuation : btstqty + holdqty + brkcolqty + unplgdqty + benqty + Max(npoadqty, dpqty) - usedqty
Salable: btstqty + holdqty + unplgdqty + benqty + dpqty - usedqty

Exch_tsym object:

Json Fields of object in values ArrayPossible valueDescription
exchNSE, BSE, NFO ...Exchange
tsymTrading symbol of the scrip (contract)
tokenToken of the scrip (contract)
ppPrice precision
tiTick size
lsLot size

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkPosition book request failure indication.
request_timeResponse received time.
emsgError message

Sample Success Response : [
{ "stat":"Ok", "exch_tsym":[ { "exch":"NSE", "token":"13", "tsym":"ABB-EQ" } ], "holdqty":"2000000", "colqty":"200", "btstqty":"0", "btstcolqty":"0", "usedqty":"0", "upldprc" : "1800.00" }, { "stat":"Ok", "exch_tsym":[ { "exch":"NSE", "token":"22", "tsym":"ACC-EQ" } ], "holdqty":"2000000", "colqty":"200", "btstqty":"0", "btstcolqty":"0", "usedqty":"0", "upldprc" : "1400.00" } ]

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Invalid Input : Missing uid or actid or prd." }

get_positions()

retrieves the overnight and day positions as a list

Example:

ret = api.get_positions()
mtm = 0
pnl = 0
for i in ret:
    mtm += float(i['urmtom'])
    pnl += float(i['rpnl'])
    day_m2m = mtm + pnl
print(f'{day_m2m} is your Daily MTM')

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
actid*Account id of the logged in user.

Response Details :

Response data will be in json format with Array of Objects with below fields in case of success.

Json FieldsPossible valueDescription
statOk or Not_OkPosition book success or failure indication.
exchExchange segment
tsymTrading symbol / contract.
tokenContract token
uidUser Id
actidAccount Id
prdProduct name to be shown.
netqtyNet Position quantity
netavgprcNet position average price
daybuyqtyDay Buy Quantity
daysellqtyDay Sell Quantity
daybuyavgprcDay Buy average price
daysellavgprcDay buy average price
daybuyamtDay Buy Amount
daysellamtDay Sell Amount
cfbuyqtyCarry Forward Buy Quantity
cforgavgprcOriginal Avg Price
cfsellqtyCarry Forward Sell Quantity
cfbuyavgprcCarry Forward Buy average price
cfsellavgprcCarry Forward Buy average price
cfbuyamtCarry Forward Buy Amount
cfsellamtCarry Forward Sell Amount
lpLTP
rpnlRealizedPNL
urmtomUnrealizedMTOM.
bepBreak even price
openbuyqty
opensellqty
openbuyamt
opensellamt
openbuyavgprc
opensellavgprc
mult
pp
prcftrgnpn/(gdpd).
tiTick size
lsLot size
request_timeThis will be present only in a failure response.

Response data will be in json format with below fields in case of failure:

Json FieldsPossible valueDescription
statNot_OkPosition book request failure indication.
request_timeResponse received time.
emsgError message

Sample Success Response : [ { "stat":"Ok", "uid":"POORNA", "actid":"POORNA", "exch":"NSE", "tsym":"ACC-EQ", "prarr":"C", "pp":"2", "ls":"1", "ti":"5.00", "mult":"1", "prcftr":"1.000000", "daybuyqty":"2", "daysellqty":"2", "daybuyamt":"2610.00", "daybuyavgprc":"1305.00", "daysellamt":"2610.00", "daysellavgprc":"1305.00", "cfbuyqty":"0", "cfsellqty":"0", "cfbuyamt":"0.00", "cfbuyavgprc":"0.00", "cfsellamt":"0.00", "cfsellavgprc":"0.00", "openbuyqty":"0", "opensellqty":"23", "openbuyamt":"0.00", "openbuyavgprc":"0.00", "opensellamt":"30015.00", "opensellavgprc":"1305.00", "netqty":"0", "netavgprc":"0.00", "lp":"0.00", "urmtom":"0.00", "rpnl":"0.00", "cforgavgprc":"0.00"

}

]

Sample Failure Response : { "stat":"Not_Ok", "request_time":"14:14:11 26-05-2020", "emsg":"Error Occurred : 5 "no data"" }

get_limits

retrieves the margin and limits set

Request Details:

ParamTypeOptionalDescription
product_typestringTrueretreives the delivery holdings or for a given product
segmentstringTrueCM / FO / FX
exchangestringTrueExchange NSE/BSE/MCX

the response is as follows,

ParamTypeOptionalDescription
statOk or Not_OkFalseLimits request success or failure indication.
actidstringTrueAccount id
prdstringTrueProduct name
segstringTrueSegment CM / FO / FX
exchstringTrueExchange
-------------------------Cash Primary Fields-------------------------------
cashstringTrueCash Margin available
payinstringTrueTotal Amount transferred using Payins today
payoutstringTrueTotal amount requested for withdrawal today
-------------------------Cash Additional Fields-------------------------------
brkcollamtstringTruePrevalued Collateral Amount
unclearedcashstringTrueUncleared Cash (Payin through cheques)
daycashstringTrueAdditional leverage amount / Amount added to handle system errors - by broker.
-------------------------Margin Utilized----------------------------------
marginusedstringTrueTotal margin / fund used today
mtomcurperstringTrueMtom current percentage
-------------------------Margin Used components---------------------
cbustringTrueCAC Buy used
cscstringTrueCAC Sell Credits
rpnlstringTrueCurrent realized PNL
unmtomstringTrueCurrent unrealized mtom
marprtstringTrueCovered Product margins
spanstringTrueSpan used
expostringTrueExposure margin
premiumstringTruePremium used
varelmstringTrueVar Elm Margin
grexpostringTrueGross Exposure
greexpo_dstringTrueGross Exposure derivative
scripbskmarstringTrueScrip basket margin
addscripbskmrgstringTrueAdditional scrip basket margin
brokeragestringTrueBrokerage amount
collateralstringTrueCollateral calculated based on uploaded holdings
grcollstringTrueValuation of uploaded holding pre haircut
-------------------------Additional Risk Limits---------------------------
turnoverlmtstringTrue
pendordvallmtstringTrue
-------------------------Additional Risk Indicators---------------------------
turnoverstringTrueTurnover
pendordvalstringTruePending Order value
-------------------------Margin used detailed breakup fields-------------------------
rzpnl_e_istringTrueCurrent realized PNL (Equity Intraday)
rzpnl_e_mstringTrueCurrent realized PNL (Equity Margin)
rzpnl_e_cstringTrueCurrent realized PNL (Equity Cash n Carry)
rzpnl_d_istringTrueCurrent realized PNL (Derivative Intraday)
rzpnl_d_mstringTrueCurrent realized PNL (Derivative Margin)
rzpnl_f_istringTrueCurrent realized PNL (FX Intraday)
rzpnl_f_mstringTrueCurrent realized PNL (FX Margin)
rzpnl_c_istringTrueCurrent realized PNL (Commodity Intraday)
rzpnl_c_mstringTrueCurrent realized PNL (Commodity Margin)
uzpnl_e_istringTrueCurrent unrealized MTOM (Equity Intraday)
uzpnl_e_mstringTrueCurrent unrealized MTOM (Equity Margin)
uzpnl_e_cstringTrueCurrent unrealized MTOM (Equity Cash n Carry)
uzpnl_d_istringTrueCurrent unrealized MTOM (Derivative Intraday)
uzpnl_d_mstringTrueCurrent unrealized MTOM (Derivative Margin)
uzpnl_f_istringTrueCurrent unrealized MTOM (FX Intraday)
uzpnl_f_mstringTrueCurrent unrealized MTOM (FX Margin)
uzpnl_c_istringTrueCurrent unrealized MTOM (Commodity Intraday)
uzpnl_c_mstringTrueCurrent unrealized MTOM (Commodity Margin)
span_d_istringTrueSpan Margin (Derivative Intraday)
span_d_mstringTrueSpan Margin (Derivative Margin)
span_f_istringTrueSpan Margin (FX Intraday)
span_f_mstringTrueSpan Margin (FX Margin)
span_c_istringTrueSpan Margin (Commodity Intraday)
span_c_mstringTrueSpan Margin (Commodity Margin)
expo_d_istringTrueExposure Margin (Derivative Intraday)
expo_d_mstringTrueExposure Margin (Derivative Margin)
expo_f_istringTrueExposure Margin (FX Intraday)
expo_f_mstringTrueExposure Margin (FX Margin)
expo_c_istringTrueExposure Margin (Commodity Intraday)
expo_c_mstringTrueExposure Margin (Commodity Margin)
premium_d_istringTrueOption premium (Derivative Intraday)
premium_d_mstringTrueOption premium (Derivative Margin)
premium_f_istringTrueOption premium (FX Intraday)
premium_f_mstringTrueOption premium (FX Margin)
premium_c_istringTrueOption premium (Commodity Intraday)
premium_c_mstringTrueOption premium (Commodity Margin)
varelm_e_istringTrueVar Elm (Equity Intraday)
varelm_e_mstringTrueVar Elm (Equity Margin)
varelm_e_cstringTrueVar Elm (Equity Cash n Carry)
marprt_e_hstringTrueCovered Product margins (Equity High leverage)
marprt_e_bstringTrueCovered Product margins (Equity Bracket Order)
marprt_d_hstringTrueCovered Product margins (Derivative High leverage)
marprt_d_bstringTrueCovered Product margins (Derivative Bracket Order)
marprt_f_hstringTrueCovered Product margins (FX High leverage)
marprt_f_bstringTrueCovered Product margins (FX Bracket Order)
marprt_c_hstringTrueCovered Product margins (Commodity High leverage)
marprt_c_bstringTrueCovered Product margins (Commodity Bracket Order)
scripbskmar_e_istringTrueScrip basket margin (Equity Intraday)
scripbskmar_e_mstringTrueScrip basket margin (Equity Margin)
scripbskmar_e_cstringTrueScrip basket margin (Equity Cash n Carry)
addscripbskmrg_d_istringTrueAdditional scrip basket margin (Derivative Intraday)
addscripbskmrg_d_mstringTrueAdditional scrip basket margin (Derivative Margin)
addscripbskmrg_f_istringTrueAdditional scrip basket margin (FX Intraday)
addscripbskmrg_f_mstringTrueAdditional scrip basket margin (FX Margin)
addscripbskmrg_c_istringTrueAdditional scrip basket margin (Commodity Intraday)
addscripbskmrg_c_mstringTrueAdditional scrip basket margin (Commodity Margin)
brkage_e_istringTrueBrokerage (Equity Intraday)
brkage_e_mstringTrueBrokerage (Equity Margin)
brkage_e_cstringTrueBrokerage (Equity CAC)
brkage_e_hstringTrueBrokerage (Equity High Leverage)
brkage_e_bstringTrueBrokerage (Equity Bracket Order)
brkage_d_istringTrueBrokerage (Derivative Intraday)
brkage_d_mstringTrueBrokerage (Derivative Margin)
brkage_d_hstringTrueBrokerage (Derivative High Leverage)
brkage_d_bstringTrueBrokerage (Derivative Bracket Order)
brkage_f_istringTrueBrokerage (FX Intraday)
brkage_f_mstringTrueBrokerage (FX Margin)
brkage_f_hstringTrueBrokerage (FX High Leverage)
brkage_f_bstringTrueBrokerage (FX Bracket Order)
brkage_c_istringTrueBrokerage (Commodity Intraday)
brkage_c_mstringTrueBrokerage (Commodity Margin)
brkage_c_hstringTrueBrokerage (Commodity High Leverage)
brkage_c_bstringTrueBrokerage (Commodity Bracket Order)
peak_marstringTruePeak margin used by the client
request_timestringTrueThis will be present only in a successful response.
emsgstringTrueThis will be present only in a failure response.

Sample Success Response : { "request_time":"18:07:31 29-05-2020", "stat":"Ok", "cash":"1500000000000000.00", "payin":"0.00", "payout":"0.00", "brkcollamt":"0.00", "unclearedcash":"0.00", "daycash":"0.00", "turnoverlmt":"50000000000000.00", "pendordvallmt":"2000000000000000.00", "turnover":"3915000.00", "pendordval":"2871000.00", "marginused":"3945540.00", "mtomcurper":"0.00", "urmtom":"30540.00", "grexpo":"3915000.00", "uzpnl_e_i":"15270.00", "uzpnl_e_m":"61080.00", "uzpnl_e_c":"-45810.00" }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Server Timeout : " } Market Info

span_calculator(actid,positionlist)

This calculates the margin requirement for a list of input positions.

Example:

ret = api.span_calculator(actid,positionlist)

Request Details :

Json FieldsPossible valueDescription
actid*Any Account id, preferably actual account id if sending from post login screen.
pos*Array of json objects. (object fields given in below table)

Position structure as follows:

Json FieldsPossible valueDescription
prdC / M / HProduct
exchNFO, CDS, MCX ...Exchange
instnameFUTSTK, FUTIDX, OPTSTK, FUTCUR...Instrument name
symnameUSDINR, ACC, ABB,NIFTY..Symbol name
exd29-DEC-2022DD-MMM-YYYY format
opttCE, PEOption Type
strprc11900.00, 71.0025Strike price
buyqtyBuy Open Quantity
sellqtySell Open Quantity
netqtyNet traded quantity

Response Details :

Json FieldsPossible valueDescription
statOk or Not_OkMarket watch success or failure indication.
spanSpan value
expoIExposure margin
span_tradeSpan value ignoring input fields buyqty, sellqty
expo_tradeExposure margin ignoring input fields buyqty, sellqty

Sample Success Response : { "request_time": "11:01:59 25-11-2022", "stat": "Ok", "span": "19416.00", "expo": "4338.34", "span_trade": "19416.00", "expo_trade": "4338.34" }

get_option_greek(expiredate,StrikePrice,SpotPrice,InitRate,Volatility,OptionType)

Options greeeks computed the delta, thetha, vega , rho values.

Example:

ret = api.option_greek(expiredate ='24-NOV-2022',StrikePrice='150',SpotPrice  = '200',InitRate  = '100',Volatility = '10',OptionType='CE')

Request Details :

Json FieldsPossible valueDescription
exd*Expiry Date
strprc*Strike Price
sptprc*Spot Price
int_rate*Init Rate
volatility*Volatility
opttCE or PEOption Type

Response Details :

Json FieldsPossible valueDescription
statOk or Not_Oksuccess or failure indication.
request_timeThis will be present only in a successful response.
cal_priceCal Price
put_pricePut Price
cal_deltaCal Delta
put_deltaPut Delta
cal_gammaCal Gamma
put_gammaPut Gamma
cal_thetaCal Theta
put_thetaPut Theta
cal_deltaCal Delta
cal_rhoCal Rho
put_rhoPut Rho
cal_vegoCal Vego
put_vegoPut Vego

Sample Success Response : { "request_time":"17:22:58 28-07-2021", "stat":"OK", "cal_price":"1441", "put_price":"0.417071", "cal_delta":"0.997304", "put_delta":"-0.002696", "cal_gamma":"0.000001", "put_gamma":"0.000001", "cal_theta":"-31.535015", "put_theta":"-31.401346", "cal_rho":"0.000119", "put_rho":"-0.016590", "cal_vego":"0.006307", put_vego":"0.006307" }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Invalid Input : jData is Missing." }

scripmasters:

The scrip masters can be downloaded from the following links

https://api.shoonya.com/NSE_symbols.txt.zip

https://api.shoonya.com/NFO_symbols.txt.zip

https://api.shoonya.com/CDS_symbols.txt.zip

https://api.shoonya.com/MCX_symbols.txt.zip

https://api.shoonya.com/BSE_symbols.txt.zip

https://api.shoonya.com/BFO_symbols.txt.zip

example is provided in test/test_download_masters.py

##Since this is a huge file, users are recommended to download it once a day and store it locally.

searchscrip(exchange, searchtext):

Search for scrip or contract and its properties

The call can be made to get the exchange provided token for a scrip or alternately can search for a partial string to get a list of matching scrips Trading Symbol:

SymbolName + ExpDate + 'F' for all data having InstrumentName starting with FUT

SymbolName + ExpDate + 'P' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType PE

SymbolName + ExpDate + 'C' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType C

For MCX, F to be ignored for FUT instruments

Example:

exch  = 'NFO'
query = 'BANKNIFTY 30DEC CE' # multiple criteria to narrow results 
ret = api.searchscrip(exchange=exch, searchtext=query)

if ret != None:
    symbols = ret['values']
    for symbol in symbols:
        print('{0} token is {1}'.format(symbol['tsym'], symbol['token']))

Example 2:

api.searchscrip(exchange='NSE', searchtext='REL')

This will reply as following

{
    "stat": "Ok",
    "values": [
        {
            "exch": "NSE",
            "token": "18069",
            "tsym": "REL100NAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "24225",
            "tsym": "RELAXO-EQ"
        },
        {
            "exch": "NSE",
            "token": "4327",
            "tsym": "RELAXOFOOT-EQ"
        },
        {
            "exch": "NSE",
            "token": "18068",
            "tsym": "RELBANKNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "2882",
            "tsym": "RELCAPITAL-EQ"
        },
        {
            "exch": "NSE",
            "token": "18070",
            "tsym": "RELCONSNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "18071",
            "tsym": "RELDIVNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "18072",
            "tsym": "RELGOLDNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "2885",
            "tsym": "RELIANCE-EQ"
        },
        {
            "exch": "NSE",
            "token": "15068",
            "tsym": "RELIGARE-EQ"
        },
        {
            "exch": "NSE",
            "token": "553",
            "tsym": "RELINFRA-EQ"
        },
        {
            "exch": "NSE",
            "token": "18074",
            "tsym": "RELNV20NAV-EQ"
        }
    ]
}

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
stext*Search Text
exchExchange (Select from ‘exarr’ Array provided in User Details response)

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkMarket watch success or failure indication.
valuesArray of json objects. (object fields given in below table)
emsgThis will be present only in case of errors.
Json Fields of object in values ArrayPossible valueDescription
exchNSE, BSE, NFO ...Exchange
tsymTrading symbol of the scrip (contract)
tokenToken of the scrip (contract)
ppPrice precision
tiTick size
lsLot size

Sample Success Response :

{ "stat": "Ok", "values": [ { "exch": "NSE", "token": "18069", "tsym": "REL100NAV-EQ" }, { "exch": "NSE", "token": "24225", "tsym": "RELAXO-EQ" }, { "exch": "NSE", "token": "4327", "tsym": "RELAXOFOOT-EQ" }, { "exch": "NSE", "token": "18068", "tsym": "RELBANKNAV-EQ" }, { "exch": "NSE", "token": "2882", "tsym": "RELCAPITAL-EQ" }, { "exch": "NSE", "token": "18070", "tsym": "RELCONSNAV-EQ" }, { "exch": "NSE", "token": "18071", "tsym": "RELDIVNAV-EQ" }, { "exch": "NSE", "token": "18072", "tsym": "RELGOLDNAV-EQ" }, { "exch": "NSE", "token": "2885", "tsym": "RELIANCE-EQ" }, { "exch": "NSE", "token": "15068", "tsym": "RELIGARE-EQ" }, { "exch": "NSE", "token": "553", "tsym": "RELINFRA-EQ" }, { "exch": "NSE", "token": "18074", "tsym": "RELNV20NAV-EQ" } ] }

Sample Failure Response : { "stat":"Not_Ok", "emsg":"No Data : " }

get_security_info(exchange, token):

gets the complete details and its properties

Example:

exch  = 'NSE'
token = '22'
ret = api.get_security_info(exchange=exch, token=token)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
exchExchange
tokenContract Token

Response Details :

Response data will have below fields.

Json FieldsPossible valueDescription
request_timeIt will be present only in a successful response.
statOk or Not_OkMarket watch success or failure indication.
exchNSE, BSE, NFO ...Exchange
tsymTrading Symbol
cnameCompany Name
symnamSymbol Name
segSegment
exdExpiry Date
instnameIntrument Name
strprcStrike Price
opttOption Type
isinISIN
tiTick Size
lsLot Size
ppPrice precision
multMultiplier
gp_ndgn/gd * pn/pd
prcuntPrice Units
prcqqtyPrice Quote Qty
trduntTrade Units
deluntDelivery Units
frzqtyFreeze Qty
gsmindscripupdate Gsm Ind
elmbmrgElm Buy Margin
elmsmrgElm Sell Margin
addbmrgAdditional Long Margin
addsmrgAdditional Short Margin
splbmrgSpecial Long Margin
splsmrgSpecial Short Margin
delmrgDelivery Margin
tenmrgTender Margin
tenstrdTender Start Date
tenenddTender End Eate
exestrdExercise Start Date
exeenddExercise End Date
elmmrgElm Margin
varmrgVar Margin
expmrgExposure Margin
tokenContract Token
prcftr_d((GN / GD) * (PN/PD))

Sample Success Response : { "request_time": "17:43:38 31-10-2020", "stat": "Ok", "exch": "NSE", "tsym": "ACC-EQ", "cname": "ACC LIMITED", "symname": "ACC", "seg": "EQT", "instname": "EQ", "isin": "INE012A01025", "pp": "2", "ls": "1", "ti": "0.05", "mult": "1", "prcftr_d": "(1 / 1 ) * (1 / 1)", "trdunt": "", "delunt": "ACC", "token": "22", "varmrg": "40.00" }

Sample Failure Response : { "stat":"Not_Ok", "request_time":"10:50:54 10-12-2020", "emsg":"Error Occurred : 5 "no data"" }

get_quotes(exchange, token):

gets the complete details and its properties

Example:

exch  = 'NSE'
token = '22'
ret = api.get_quotes(exchange=exch, token=token)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
exchExchange
tokenContract Token

Response Details :

Response data will be in json format with below fields.

Json FieldsPossible valueDescription
statOk or Not_OkWatch list update success or failure indication.
request_timeIt will be present only in a successful response.
exchNSE, BSE, NFO ...Exchange
tsymTrading Symbol
cnameCompany Name
symnameSymbol Name
segSegment
instnameInstrument Name
isinISIN
ppPrice precision
lsLot Size
tiTick Size
multMultiplier
ucUpper circuit limitlc
lcLower circuit limit
prcftr_dPrice factor
tokenToken
lpLTP
oOpen Price
hDay High Price
lDay Low Price
vVolume
ltqLast trade quantity
lttLast trade time
bp1Best Buy Price 1
sp1Best Sell Price 1
bp2Best Buy Price 2
sp2Best Sell Price 2
bp3Best Buy Price 3
sp3Best Sell Price 3
bp4Best Buy Price 4
sp4Best Sell Price 4
bp5Best Buy Price 5
sp5Best Sell Price 5
bq1Best Buy Quantity 1
sq1Best Sell Quantity 1
bq2Best Buy Quantity 2
sq2Best Sell Quantity 2
bq3Best Buy Quantity 3
sq3Best Sell Quantity 3
bq4Best Buy Quantity 4
sq4Best Sell Quantity 4
bq5Best Buy Quantity 5
sq5Best Sell Quantity 5
bo1Best Buy Orders 1
so1Best Sell Orders 1
bo2Best Buy Orders 2
so2Best Sell Orders 2
bo3Best Buy Orders 3
so3Best Sell Orders 3
bo4Best Buy Orders 4
so4Best Sell Orders 4
bo5Best Buy Orders 5
so5Best Sell Orders 5

Sample Success Response : { "request_time":"12:05:21 18-05-2021", "stat":"Ok" ,"exch":"NSE", "tsym":"ACC-EQ", "cname":"ACC LIMITED", "symname":"ACC", "seg":"EQT", "instname":"EQ", "isin":"INE012A01025", "pp":"2", "ls":"1", "ti":"0.05", "mult":"1", "uc":"2093.95", "lc":"1713.25", "prcftr_d":"(1 / 1 ) * (1 / 1)", "token":"22", "lp":"0.00", "h":"0.00", "l":"0.00", "v":"0", "ltq":"0", "ltt":"05:30:00", "bp1":"2000.00", "sp1":"0.00", "bp2":"0.00", "sp2":"0.00", "bp3":"0.00", "sp3":"0.00", "bp4":"0.00", "sp4":"0.00", "bp5":"0.00", "sp5":"0.00", "bq1":"2", "sq1":"0", "bq2":"0", "sq2":"0", "bq3":"0", "sq3":"0", "bq4":"0", "sq4":"0", "bq5":"0", "sq5":"0", "bo1":"2", "so1":"0", "bo2":"0", "so2":"0", "bo3":"0", "so3":"0", "bo4":"0", "so4":"0", "bo5":"0", "So5":"0" }

Sample Failure Response : { "stat":"Not_Ok", "request_time":"10:50:54 10-12-2020", "emsg":"Error Occurred : 5 "no data"" }

get_time_price_series(exchange, token, starttime, endtime, interval):

gets the chart data for the symbol

Example:

lastBusDay = datetime.datetime.today()
lastBusDay = lastBusDay.replace(hour=0, minute=0, second=0, microsecond=0)
ret = api.get_time_price_series(exchange='NSE', token='22', starttime=lastBusDay.timestamp(), interval=5)

Request Details :

Json FieldsPossible valueDescription
uid*Logged in User Id
exch*Exchange
token*
stStart time (seconds since 1 jan 1970)
etEnd Time (seconds since 1 jan 1970)
intrv“1”, ”3”, “5”, “10”, “15”, “30”, “60”, “120”, “240”Candle size in minutes (optional field, if not given assume to be “1”)

Response Details :

Response data will be in json format in case for failure.

Json FieldsPossible valueDescription
statNot_OkTPData failure indication.
emsgThis will be present only in case of errors.

Response data will be in json format in case for success.

Json FieldsPossible valueDescription
statOkTPData success indication.
timeDD/MM/CCYY hh:mm:ss
intoInterval open
inthInterval high
intlInterval low
intcInterval close
intvwapInterval vwap
intvInterval volume
vvolume
intoiInterval io change
oioi

Sample Success Response : [ { "stat":"Ok", "time":"02-06-2020 15:46:23", "into":"0.00", "inth":"0.00", "intl":"0.00", "intc":"0.00", "intvwap":"0.00", "intv":"0", "intoi":"0", "v":"980515", "oi":"128702" }, { "stat":"Ok", "time":"02-06-2020 15:45:23", "into":"0.00", "inth":"0.00", "intl":"0.00", "intc":"0.00", "intvwap":"0.00", "intv":"0", "intoi":"0", "v":"980515", "oi":"128702" }, { "stat":"Ok", "time":"02-06-2020 15:44:23", "into":"0.00", "inth":"0.00", "intl":"0.00", "intc":"0.00", "intvwap":"0.00", "intv":"0", "intoi":"0", "v":"980515", "oi":"128702" }, { "stat":"Ok", "time":"02-06-2020 15:43:23", "into":"1287.00", "inth":"1287.00", "intl":"0.00", "intc":"1287.00", "intvwap":"128702.00", "intv":"4", "intoi":"128702", "v":"980515", "oi":"128702" }, { "stat":"Ok", "time":"02-06-2020 15:42:23", "into":"0.00", "inth":"0.00", "intl":"0.00", "intc":"0.00", "intvwap":"0.00", "intv":"0", "intoi":"0", "v":"980511", "oi":"128702" } ]

Sample Failure Response : { "stat":"Not_Ok", "emsg":"Session Expired : Invalid Session Key" }

get_daily_price_series(Symbol name, From date, To date):

gets the chart date for the symbol

Example:

ret =api.get_daily_price_series(exchange="NSE",tradingsymbol="PAYTM-EQ",startdate="457401600",enddate="480556800")

Request Details :

Json FieldsPossible valueDescription
sym*Symbol name
from*From date
to*To date

Response Details :

Json FieldsPossible valueDescription
statOkTPData success indication.
timeDD/MM/CCYY hh:mm:ss
intoInterval open
inthInterval high
intlInterval low
intcInterval close
ssboeDate,Seconds in 1970 format
intvInterval volume

Sample Success Response : [ "{ "time":"21-SEP-2022", "into":"2496.75", "inth":"2533.00", "intl":"2495.00", "intc":"2509.75", "ssboe":"1663718400", "intv":"4249172.00" }", "{ "time":"15-SEP-2022", "into":"2583.00", "inth":"2603.55", "intl":"2556.75", "intc":"2562.70", "ssboe":"1663200000", "intv":"4783723.00" }", "{ "time":"28-JUN-2021", "into":"2122.00", "inth":"2126.50", "intl":"2081.00", "intc":"2086.00", "ssboe":"1624838400", "intv":"9357852.00" }" ]

get_option_chain(exchange, tradingsymbol, strikeprice, count):

gets the contracts of related strikes

ParamTypeOptionalDescription
exchangestringFalseExchange (UI need to check if exchange in NFO / CDS / MCX / or any other exchange which has options, if not don't allow)
tradingsymbolstringFalseTrading symbol of any of the option or future. Option chain for that underlying will be returned. (use url encoding to avoid special char error for symbols like M&M)
strikepricefloatFalseMid price for option chain selection
countintTrueNumber of strike to return on one side of the mid price for PUT and CALL. (example cnt is 4, total 16 contracts will be returned, if cnt is is 5 total 20 contract will be returned)

the response is as follows,

ParamTypeOptionalDescription
statstringTrueok or Not_ok
valuesstringTrueproperties of the scrip
emsgstringFalseError Message
ParamTypeOptionalDescription
exchstringFalseExchange
tsymstringFalseTrading Symbol of Contract
tokenstringFalseContract token
opttstringFalseOption type
strprcstringFalseStrike Price
ppstringFalsePrice Precision
tistringFalseTick Size
lsstringFalseLot Size

start_websocket()

Note: Please ensure that only a single web-socket connection is started. Opening multiple web-socket connections is not supported by the API. starts the websocket, WebSocket feed has 2 types of ticks( t=touchline d=depth)and 2 stages (k=acknowledgement, f=further change in tick).

ParamTypeOptionalDescription
subscribe_callbackfunctionFalsecallback for market updates
order_update_callbackfunctionFalsecallback for order updates
socket_open_callbackfunctionFalsecallback when socket is open (reconnection also)
socket_close_callbackfunctionFalsecallback when socket is closed

subscribe_orders()

get order and trade update callbacks

Subscription Acknowledgement:

Json FieldsPossible valueDescription
tok‘ok’ represents order update subscription acknowledgement

Order Update subscription Updates :

Json FieldsPossible valueDescription
tom‘om’ represents touchline feed
norenordnoNoren Order Number
uidUser Id
actidAccount ID
exchExchange
tsymTrading symbol
qtyOrder quantity
prcOrder Price
prdProduct
statusOrder status (New, Replaced, Complete, Rejected etc)
reporttypeOrder event for which this message is sent out. (Fill, Rejected, Canceled)
trantypeOrder transaction type, buy or sell
prctypOrder price type (LMT, MKT, SL-LMT, SL-MKT)
retOrder retention type (DAY, EOS, IOC,...)
fillsharesTotal Filled shares for this order
avgprcAverage fill price
fltmFill Time(present only when reporttype is Fill)
flidFill ID (present only when reporttype is Fill)
flqtyFill Qty(present only when reporttype is Fill)
flprcFill Price(present only when reporttype is Fill)
rejreasonOrder rejection reason, if rejected
exchordidExchange Order ID
cancelqtyCanceled quantity, in case of canceled order
remarksUser added tag, while placing order
dscqtyDisclosed quantity
trgprcTrigger price for SL orders
snonumThis will be present for child orders in case of cover and bracket orders, if present needs to be sent during exit
snoordtThis will be present for child orders in case of cover and bracket orders, it will indicate whether the order is profit or stoploss
blprcThis will be present for cover and bracket parent order. This is the differential stop loss trigger price to be entered.
bpprcThis will be present for bracket parent order. This is the differential profit price to be entered.
trailprcThis will be present for cover and bracket parent order. This is required if trailing ticks is to be enabled.
exch_tmThis will have the exchange update time

subscribe([instruments])

send a list of instruments to watch, feed_type specifies the type of data requested ( t=touchline d=depth)

t='tk' is sent once on subscription for each instrument. this will have all the fields with the most recent value thereon t='tf' is sent for fields that have changed.

For example
quote event: 03-12-2021 11:54:44{'t': 'tk', 'e': 'NSE', 'tk': '11630', 'ts': 'NTPC-EQ', 'pp': '2', 'ls': '1', 'ti': '0.05', 'lp': '118.55', 'h': '118.65', 'l': '118.10', 'ap': '118.39', 'v': '162220', 'bp1': '118.45', 'sp1': '118.50', 'bq1': '26', 'sq1': '6325'}
quote event: 03-12-2021 11:54:45{'t': 'tf', 'e': 'NSE', 'tk': '11630', 'lp': '118.45', 'ap': '118.40', 'v': '166637', 'sp1': '118.55', 'bq1': '3135', 'sq1': '30'}
quote event: 03-12-2021 11:54:46{'t': 'tf', 'e': 'NSE', 'tk': '11630', 'lp': '118.60'}

in the example above we see first message t='tk' with all the values, 2nd message has lasttradeprice avg price and few other fields with value changed.. note bp1 isnt sent as its still 118.45 in the next tick ( 3rd message) only last price is changed to 118.6

This method can be used to subscribe indices as well such as Nifty-50 [NSE|26000], BankNifty[NSE|26009]

ParamTypeOptionalDescription
instrumentslistFalselist of instruments [NSE|22,CDS|1]

Subscription Acknowledgement:

Number of Acknowledgements for a single subscription will be the same as the number of scrips mentioned in the key (k) field.

Json FieldsPossible valueDescription
ttk‘tk’ represents touchline acknowledgement
eNSE, BSE, NFO ..Exchange name
tk22Scrip Token
pp2 for NSE, BSE & 4 for CDS USDINRPrice precision
tsTrading Symbol
tiTick size
lsLot size
lpLTP
pcPercentage change
vvolume
oOpen price
hHigh price
lLow price
cClose price
apAverage trade price
oiOpen interest
poiPrevious day closing Open Interest
toiTotal open interest for underlying
bq1Best Buy Quantity 1
bp1Best Buy Price 1
sq1Best Sell Quantity 1
sp1Best Sell Price 1

TouchLine subscription Updates : Accept for t, e, and tk other fields may / may not be present.

Json FieldsPossible valueDescription
ttf‘tf’ represents touchline acknowledgement
eNSE, BSE, NFO ..Exchange name
tk22Scrip Token
lpLTP
pcPercentage change
vvolume
oOpen price
hHigh price
lLow price
cClose price
apAverage trade price
oiOpen interest
poiPrevious day closing Open Interest
toiTotal open interest for underlying
bq1Best Buy Quantity 1
bp1Best Buy Price 1
sq1Best Sell Quantity 1
sp1Best Sell Price 1

Depth Messages will be as below

Json FieldsPossible valueDescription
tdk?dk? represents depth acknowledgement
eNSE, BSE, NFO ..Exchange name
tk22Scrip Token
lpLTP
pcPercentage change
vvolume
oOpen price
hHigh price
lLow price
cClose price
apAverage trade price
lttLast trade time
ltqLast trade quantity
tbqTotal Buy Quantity
tsqTotal Sell Quantity
bq1Best Buy Quantity 1
bq2Best Buy Quantity 2
bq3Best Buy Quantity 3
bq4Best Buy Quantity 4
bq5Best Buy Quantity 5
bp1Best Buy Price 1
bp2Best Buy Price 2
bp3Best Buy Price 3
bp4Best Buy Price 4
bp5Best Buy Price 5
bo1Best Buy Orders 1
bo2Best Buy Orders 2
bo3Best Buy Orders 3
bo4Best Buy Orders 4
bo5Best Buy Orders 5
sq1Best Sell Quantity 1
sq2Best Sell Quantity 2
sq3Best Sell Quantity 3
sq4Best Sell Quantity 4
sq5Best Sell Quantity 5
sp1Best Sell Price 1
sp2Best Sell Price 2
sp3Best Sell Price 3
sp4Best Sell Price 4
sp5Best Sell Price 5
so1Best Sell Orders 1
so2Best Sell Orders 2
so3Best Sell Orders 3
so4Best Sell Orders 4
so5Best Sell Orders 5
lcLower Circuit Limit
ucUpper Circuit Limit
52h52 week high low in other exchanges, Life time high low in mcx
52l52 week high low in other exchanges, Life time high low in mcx
oiOpen interest
poiPrevious day closing Open Interest
toiTotal open interest for underlying
ftFeed time

unsubscribe()

send a list of instruments to stop watch


Order States and Report Types

Possible Values for Order States are as follows

PENDING :- The order has been submitted but is awaiting further processing.

CANCELED :- The order has been canceled by the trader before being executed.

OPEN:- The order is active and waiting to be matched with a counterparty.

REJECTED:- The order has been declined due to certain criteria not being met.

COMPLETE:- The order has been successfully executed and completed.

TRIGGER_PENDING:- A specific condition must be met before the order can become active.

INVALID_STATUS_TYPE:- The provided order status is not recognized or valid.

The Orders will have a request status or report type for modify/cancel the possible values are as follows

NewAck :- acknowledgement that a new order request has been received.

ModAck :- acknowledgement that a modification request for an existing order has been received.

CanAck :- acknowledgement that a request to cancel an order has been received.

PendingNew :- The request to place a new order is pending further review.

PendingReplace :- The request to modify an existing order is pending further review.

PendingCancel :- The request to cancel an order is pending further review.

New :- Confirmation that a new order has been successfully placed.

Replaced :- confirmation that an existing order has been successfully modified.

Canceled :- confirmation that an order has been successfully canceled.

Fill :- notification that an order has been fully or partially executed.

Rejected :- notification that an order has been rejected and not executed.

ReplaceRejected :- Notification that a request to modify an order has been rejected.

CancelRejected :- Notification that a request to cancel an order has been rejected.

INVALID_REPORT_TYPE :- The provided report type for modification/cancellation is not recognized or valid.

Example - Getting Started

First configure the endpoints in the api_helper constructor. Thereon provide your credentials and login as follows.

from api_helper import ShoonyaApiPy
import logging

#enable dbug to see request and responses
logging.basicConfig(level=logging.DEBUG)

#start of our program
api = ShoonyaApiPy()

#credentials
user        = '< user id>'
u_pwd       = '< password >'
factor2     = 'OTP/TOTP'
vc          = 'vendor code'
app_key     = 'API key'
imei        = 'uniq identifier'


ret = api.login(userid=user, password=pwd, twoFA=factor2, vendor_code=vc, api_secret=app_key, imei=imei)
print(ret)

Example Symbol/Contract : Example_market.py

This Example shows API usage for finding scrips and its properties

Search Scrips

The call can be made to get the exchange provided token for a scrip or alternately can search for a partial string to get a list of matching scrips Trading Symbol:

SymbolName + ExpDate + 'F' for all data having InstrumentName starting with FUT

SymbolName + ExpDate + 'P' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType PE

SymbolName + ExpDate + 'C' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType C

For MCX, F to be ignored for FUT instruments

api.searchscrip(exchange='NSE', searchtext='REL')

This will reply as following

{
    "stat": "Ok",
    "values": [
        {
            "exch": "NSE",
            "token": "18069",
            "tsym": "REL100NAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "24225",
            "tsym": "RELAXO-EQ"
        },
        {
            "exch": "NSE",
            "token": "4327",
            "tsym": "RELAXOFOOT-EQ"
        },
        {
            "exch": "NSE",
            "token": "18068",
            "tsym": "RELBANKNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "2882",
            "tsym": "RELCAPITAL-EQ"
        },
        {
            "exch": "NSE",
            "token": "18070",
            "tsym": "RELCONSNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "18071",
            "tsym": "RELDIVNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "18072",
            "tsym": "RELGOLDNAV-EQ"
        },
        {
            "exch": "NSE",
            "token": "2885",
            "tsym": "RELIANCE-EQ"
        },
        {
            "exch": "NSE",
            "token": "15068",
            "tsym": "RELIGARE-EQ"
        },
        {
            "exch": "NSE",
            "token": "553",
            "tsym": "RELINFRA-EQ"
        },
        {
            "exch": "NSE",
            "token": "18074",
            "tsym": "RELNV20NAV-EQ"
        }
    ]
}

Security Info

This call is done to get the properties of the scrip such as freeze qty and margins

api.get_security_info(exchange='NSE', token='22')

The response for the same would be

{
   "request_time": "17:43:38 31-10-2020",
   "stat": "Ok",
   "exch": "NSE",
   "tsym": "ACC-EQ",
   "cname": "ACC LIMITED",
   "symname": "ACC",
   "seg": "EQT",
   "instname": "EQ",
   "isin": "INE012A01025",
   "pp": "2",
   "ls": "1",
   "ti": "0.05",
   "mult": "1",
   "prcftr_d": "(1 / 1 ) * (1 / 1)",
   "trdunt": "ACC.BO",
   "delunt": "ACC",
   "token": "22",
   "varmrg": "40.00"
}

Subscribe to a live feed

Subscribe to a single token as follows

api.subscribe('NSE|13')

Subscribe to a list of tokens as follows

api.subscribe(['NSE|22', 'BSE|522032'])

First we need to connect to the WebSocket and then subscribe as follows

feed_opened = False

def event_handler_feed_update(tick_data):
    print(f"feed update {tick_data}")

def open_callback():
    global feed_opened
    feed_opened = True


api.start_websocket( order_update_callback=event_handler_order_update,
                     subscribe_callback=event_handler_feed_update, 
                     socket_open_callback=open_callback)

while(feed_opened==False):
    pass

# subscribe to a single token 
api.subscribe('NSE|13')

#subscribe to multiple tokens
api.subscribe(['NSE|22', 'BSE|522032'])

Example - Orders and Trades : example_orders.py

Place Order

Place a Limit order as follows
    api.place_order(buy_or_sell='B', product_type='C',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None,
                        retention='DAY', remarks='my_order_001')
Place a Market Order as follows
    api.place_order(buy_or_sell='B', product_type='C',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='MKT', price=0, trigger_price=None,
                        retention='DAY', remarks='my_order_001')
Place a StopLoss Order as follows
    api.place_order(buy_or_sell='B', product_type='C',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='SL-LMT', price=1500, trigger_price=1450,
                        retention='DAY', remarks='my_order_001')
Place a Cover Order as follows
    api.place_order(buy_or_sell='B', product_type='H',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None,
                        retention='DAY', remarks='my_order_001', bookloss_price = 1490)
Place a Bracket Order as follows
    api.place_order(buy_or_sell='B', product_type='B',
                        exchange='NSE', tradingsymbol='INFY-EQ', 
                        quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None,
                        retention='DAY', remarks='my_order_001', bookloss_price = 1490, bookprofit_price = 1510)

Modify Order

Modify a New Order by providing the OrderNumber
    api.modify_order(exchange='NSE', tradingsymbol='INFY-EQ', orderno=orderno,
                                   newquantity=2, newprice_type='LMT', newprice=1505)

Cancel Order

Cancel a New Order by providing the Order Number
    api.cancel_order(orderno=orderno)

Subscribe to Order Updates

Connecting to the Websocket will automatically subscribe and provide the order updates in the call back as follows Note: Feed and Order updates are received from the same websocket and needs to be connected once only.

feed_opened = False

def event_handler_order_update(order):
    print(f"order feed {order}")

def open_callback():
    global feed_opened
    feed_opened = True


api.start_websocket( order_update_callback=event_handler_order_update,
                     subscribe_callback=event_handler_feed_update, 
                     socket_open_callback=open_callback)

while(feed_opened==False):
    pass



Contact Us

For any queries, feel free to reach us, by email at apisupport@shoonya.com or call at 0172-4740000 & Also Just visit our website there is a Live chat option.


Author

Kumar Anand


License

Copyright (C) 2021 Kambala Solutions Pvt Ltd- All Rights Reserved Copying of this file, via any medium is strictly prohibited. Proprietary and confidential. All file transfers are logged.


Contributors

kambalatech

48 commits

Shoonya-Dev

21 commits

Nikhesh

18 commits

Languages

Python

100.0%