1.0.0 • Published 2 years ago

@quantiply/shoonya-api v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

ShoonyaAPI

Api used to connect to Shoonya Server


Build

install the npm packages mention in package.json

To run the application enter as follows,

node app.js


API

bashoonyaApi

Symbols

Orders and Trades

Holdings and Limits

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

ParamTypeOptionalDescription
useridstringFalseuser credentials
passwordstringFalsepassword encrypted
twoFAstringFalsedob/pan
vendor_codestringFalsevendor code shared
api_secretstringFalseyour secret
imeistringFalseimei identification

logout()

Terminate the session

ParamTypeOptionalDescription
No Parameters

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

ParamTypeOptionalDescription
buy_or_sellstringFalseB -> BUY, S -> SELL
product_typestringFalseC / M / H Product 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)
exchangestringFalseExchange NSE / NFO / BSE / CDS
tradingsymbolstringFalseUnique id of contract on which order to be placed. (use url encoding to avoid special char error for symbols like M&M
quantityintegerFalseorder quantity
discloseqtyintegerFalseorder disc qty
price_typestringFalsePriceType enum class
pricedoubleFalsePrice
trigger_pricedoubleFalseTrigger Price
retentionstringFalseDAY / IOC / EOS
amostringTrueFlag for After Market Order, YES/NO
remarksstringTrueclient order id or free text

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

modify the quantity pricetype or price of an order

ParamTypeOptionalDescription
ordernostringFalseorderno to be modified
exchangestringFalseExchange NSE / NFO / BSE / CDS
tradingsymbolstringFalseUnique id of contract on which order to be placed. (use url encoding to avoid special char error for symbols like M&M
newquantityintegerFalsenew order quantity
newprice_typestringFalsePriceType enum class
newpricedoubleFalsePrice
newtrigger_pricedoubleFalseTrigger Price

cancel_order(orderno)

cancel an order

ParamTypeOptionalDescription
ordernostringFalseorderno with status open

exit_order(orderno)

exits a cover or bracket order

ParamTypeOptionalDescription
ordernostringFalseorderno with status open
prdstringFalseAllowed for only H and B products (Cover order and bracket order)

Order Book

List of Orders placed for the account

ParamTypeOptionalDescription
No Parameters

Trade Book

List of Trades of the account

ParamTypeOptionalDescription
No Parameters

single order history(orderno)

history an order

ParamTypeOptionalDescription
ordernostringFalseorderno

get_holdings(product_type)

retrieves the holdings as a list

ParamTypeOptionalDescription
product_typestringTrueretreives the delivery holdings or for a given product

the response is as follows,

ParamTypeOptionalDescription
statstringFalseHolding request success or failure indication.

get_positions()

retrieves the positions cf and day as a list

ParamTypeOptionalDescription
No Parameters

the response is as follows,

ParamTypeOptionalDescription
statstringFalsePosition book success or failure indication.
exchstringFalseExchange segment
tsymstringFalseTrading symbol / contract.
tokenstringFalseContract Token
uidstringFalseUser Id
actidstringFalseAccount Id
prdstringFalseProduct name
netqtystringFalseNet Position Quantity
netavgprcstringFalseNet Position Average Price
daybuyqtystringFalseDay Buy Quantity
daysellqtystringFalseDay Sell Quantity
daybuyavgprcstringFalseDay Buy Average Price
daysellavgprcstringFalseDay Sell Average Price
daybuyamtstringFalseDay Buy Amount
daysellamtstringFalseDay Sell Amount
cfbuyqtystringFalseCarry Forward Sell Quantity
cforgavgprcstringFalseOriginal Average Price
cfsellqtystringFalseCarry Forward Sell Quantity
cfbuyavgprcstringFalseCarry Forward Buy Average Price
cfsellavgprcstringFalseCarry Forward Sell Average Price
cfbuyamtstringFalseCarry Forward Buy Amount
cfsellamtstringFalseCarry Forward Sell Amount
lpstringFalseLTP
rpnlstringFalseRealized Profit and Loss
urmtomstringFalseUnRealized Mark To Market (Can be recalculated in LTP update : = netqty (lp from web socket - netavgprc) prcftr
bepstringFalseBreakeven Price
openbuyqtystringFalseOpen Buy Order Quantity
opensellqtystringFalseOpen Sell Order Quantity
openbuyamtstringFalseOpen Buy Order Amount
opensellamtstringFalseOpen Sell Order Amount
openbuyavgprcstringFalse
opensellavgprcstringFalse
multstringFalse
ppstringFalse
prcftrstringFalse
tistringFalse
lsstringFalse
request_timestringFalse

get_limits

retrieves the margin and limits set

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.

searchscrip(exchange, searchtext):

search for scrip or contract and its properties

ParamTypeOptionalDescription
exchangestringTrueExchange NSE / NFO / BSE / CDS
searchtextstringTrueSearch Text ie partial or complete text ex: INFY-EQ, INF..

the response is as follows,

ParamTypeOptionalDescription
statstringTrueok or Not_ok
valuesstringTrueproperties of the scrip
emsgstringFalseError Message
ParamTypeOptionalDescription
exchstringTrueExchange NSE / NFO / BSE / CDS
tsymstringTrueTrading Symbol is the readable Unique id of contract/scrip
tokenstringTrueUnique Code of contract/scrip
ppstringTrueprice precision, in case of cds its 4 ie 100.1234
tistringTruetick size minimum increments of paise for price
lsstringTrueLot Size

get_security_info(exchange, token):

gets the complete details and its properties

ParamTypeOptionalDescription
exchangestringTrueExchange NSE / NFO / BSE / CDS
tokenstringTruetoken number of the contract

the response is as follows,

ParamTypeOptionalDescription
statstringTrueok or Not_ok
valuesstringTrueproperties of the scrip
emsgstringFalseError Message
ParamTypeOptionalDescription
exchstringTrueExchange NSE / NFO / BSE / CDS
tsymstringTrueTrading Symbol is the readable Unique id of contract/scrip
cnamestringTrueCompany Name
symnamstringTrueSymbol Name
segstringTrueSegment
exdstringTrueExpiry Date
instnamestringTrueInstrument Name
strprcstringTrueStrike Price
opttstringTrueOption Type
isinstringTrueISIN
tistringTrueTick Size
lsstringTrueLot Size
ppstringTruePrice Precision
multstringTrueMultiplier
gp_ndstringTrueGN/GD * PN/PD
prcuntstringTruePrice Units
prcqqtystringTruePrice Quote Qty
trduntstringTrueTrade Units
deluntstringTrueDelivery Units
frzqtystringTrueFreeze Qty
gsmindstringTrueGSM indicator
elmbmrgstringTrueELM Buy Margin
elmsmrgstringTrueELM Sell Margin
addbmrgstringTrueAdditional Long Margin
addsmrgstringTrueAdditional Short Margin
splbmrgstringTrueSpecial Long Margin
splsmrgstringTrueSpecial Short Margin
delmrgstringTrueDelivery Margin
tenmrgstringTrueTender Margin
tenstrdstringTrueTender Start Date
tenenddstringTrueTender End Date
exestrdstringTrueExercise Start Date
exeenddstringTrueExercise End Date
elmmrgstringTrueELM Margin
varmrgstringTrueVAR Margin
expmrgstringTrueExposure Margin
tokenstringTrueContract Token
prcftr_dstringTrue((GN / GD) * (PN/PD))

get_quotes(exchange, token):

gets the complete details and its properties

ParamTypeOptionalDescription
exchangestringTrueExchange NSE / NFO / BSE / CDS
tokenstringTruetoken number of the contract

the response is as follows,

ParamTypeOptionalDescription
statstringTrueok or Not_ok
valuesstringTrueproperties of the scrip
emsgstringFalseError Message
ParamTypeOptionalDescription
exchstringTrueExchange NSE / NFO / BSE / CDS
tsymstringTrueTrading Symbol is the readable Unique id of contract/scrip
cnamestringTrueCompany Name
symnamestringTrueSymbol Name
segstringTrueSegment
instnamestringTrueInstrument Name
isinstringTrueISIN
ppstringTruePrice precision
lsstringTrueLot Size
tistringTrueTick Size
multstringTrueMultiplier
ucstringTrueUpper circuit limitlc
lcstringTrueLower circuit limit
prcftr_dstringTruePrice factor((GN / GD) * (PN/PD))
tokenstringTrueToken
lpstringTrueLTP
ostringTrueOpen Price
hstringTrueDay High Price
lstringTrueDay Low Price
vstringTrueVolume
ltqstringTrueLast trade quantity
lttstringTrueLast trade time
bp1stringTrueBest Buy Price 1
sp1stringTrueBest Sell Price 1
bp2stringTrueBest Buy Price 2
sp2stringTrueBest Sell Price 2
bp3stringTrueBest Buy Price 3
sp3stringTrueBest Sell Price 3
bp4stringTrueBest Buy Price 4
sp4stringTrueBest Sell Price 4
bp5stringTrueBest Buy Price 5
sp5stringTrueBest Sell Price 5
bq1stringTrueBest Buy Quantity 1
sq1stringTrueBest Sell Quantity 1
bq2stringTrueBest Buy Quantity 2
sq2stringTrueBest Sell Quantity 2
bq3stringTrueBest Buy Quantity 3
sq3stringTrueBest Sell Quantity 3
bq4stringTrueBest Buy Quantity 4
sq4stringTrueBest Sell Quantity 4
bq5stringTrueBest Buy Quantity 5
sq5stringTrueBest Sell Quantity 5
bo1stringTrueBest Buy Orders 1
so1stringTrueBest Sell Orders 1
bo2stringTrueBest Buy Orders 2
so2stringTrueBest Sell Orders 2
bo3stringTrueBest Buy Orders 3
so3stringTrueBest Sell Orders 3
bo4stringTrueBest Buy Orders 4
so4stringTrueBest Sell Orders 4
bo5stringTrueBest Buy Orders 5
so5stringTrueBest Sell Orders 5

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

gets the chart data for the symbol

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

the response is as follows,

ParamTypeOptionalDescription
statstringTrueok or Not_ok
valuesstringTrueproperties of the scrip
emsgstringFalseError Message
ParamTypeOptionalDescription
timestringTrueDD/MM/CCYY hh:mm:ss
intostringTrueInterval Open
inthstringTrueInterval High
intlstringTrueInterval Low
intcstringTrueInterval Close
intvwapstringTrueInterval vwap
intvstringTrueInterval volume
vstringTruevolume
inoistringTrueInterval oi change
oistringTrueoi

get_option_chain(exchange, tradingsymbol, strikeprice, count):

gets the chart date for the symbol

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()

starts the websocket

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

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

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

unsubscribe()

send a list of instruments to stop watch


Example - Getting Started

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

const Api = require("./lib/RestApi");

authparams = {
'userid'   : 'USER',
'password' : 'Abc123',
'twoFA'    : '01011920',
'vendor_code' : 'vc',
'api_secret' : 'secret shared',
'imei'       : 'machine identifier'
}

api = new Api({});

api.login(authparams)

.then((res) => {        
        
        console.log('Reply: ', res);
        return;

    }).catch((err) => {
        console.error(err);
    });

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

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.