├── README.md ├── api_helper.py ├── dist └── NorenRestApi-0.0.29-py3-none-any.whl ├── example_market.py ├── example_orders.py ├── requirements.txt ├── test_api.py ├── tests ├── option_chain.xlsx ├── test_basket_order.py ├── test_optionchain_excel.py ├── test_place_order.py ├── test_product_convertion.py ├── test_tpseries.py ├── test_watchlist.py └── test_websocket_feed.py └── token_generator ├── gettoken.py ├── requirements.txt └── setup.md /README.md: -------------------------------------------------------------------------------- 1 | # 🚀 FLATTRADE Python API 2 | 3 | > A powerful Python interface to connect with **`FLATTRADE OMS`** – place orders, fetch quotes, stream market data, and more. 4 | 5 | --- 6 | 7 | ## 📦 Getting Started 8 | 9 | ⚡ **Start Here:** **[`Set Up Flattrade API & Generate Token Fast`](token_generator/setup.md)** 10 | *Step-by-step guide to install, configure, and authenticate your API connection in minutes!* 11 | 12 | --- 13 | 14 | ## 📚 API Reference 15 | 16 | ### 📊 Symbols 17 | 18 | * 🔍 [`searchscrip`](#md-searchscrip) – Search instruments 19 | * 🧾 [`get_security_info`](#md-get_security_info) – Get instrument metadata 20 | * 💬 [`get_quotes`](#md-get_quotes) – Live market quotes 21 | * ⏱️ [`get_time_price_series`](#md-get_time_price_series) – Intraday price data 22 | * 📅 [`get_daily_price_series`](#md-get_daily_price_series) – Daily price history 23 | * 🧠 [`get_option_chain`](#md-get_optionchain) – Option chain data 24 | 25 | --- 26 | 27 | ### 📈 Orders & Trades 28 | 29 | * 🛒 [`place_order`](#md-place_order) – Place a new order 30 | * ✏️ [`modify_order`](#md-modify_order) – Edit existing order 31 | * ❌ [`cancel_order`](#md-cancel_order) – Cancel open order 32 | * 🚪 [`exit_order`](#md-exit_order) – Exit existing position 33 | * 🔄 [`product_convertion`](#md-prd_convert) – Convert product type 34 | * 📑 [`get_orderbook`](#md-get_orderbook) – View all orders 35 | * 📘 [`get_tradebook`](#md-get_tradebook) – View all trades 36 | * 🧾 [`get_singleorderhistory`](#md-get_singleorderhistory) – Full order history 37 | 38 | --- 39 | 40 | ### 🗃️ Holdings & Limits 41 | 42 | * 📦 [`get_holdings`](#md-get_holdings) – View stock holdings 43 | * 📊 [`get_positions`](#md-get_positions) – Check open positions 44 | * 💰 [`get_limits`](#md-get_limits) – View available margins 45 | 46 | --- 47 | 48 | ### 🌐 WebSocket API 49 | 50 | * 🔌 [`start_websocket`](#md-start_websocket) – Initialize socket connection 51 | * 📡 [`subscribe`](#md-subscribe) – Subscribe to live feeds 52 | * 📴 [`unsubscribe`](#md-unsubscribe) – Unsubscribe from feeds 53 | 54 | --- 55 | 56 | ### 💡 Examples 57 | 58 | * 🚀 [`getting started`](#md-example-basic) – Quick usage demo 59 | * 📈 [`Market Functions`](#md-example-market) – Quote & data examples 60 | * 🛒 [`Orders and Trade`](#md-example-orders) – Order placement & tracking 61 | 62 | --- 63 | #### 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) 64 | place an order to oms 65 | 66 | Example: 67 | 68 | ``` 69 | ret = api.place_order(buy_or_sell='B', product_type='C', 70 | exchange='NSE', tradingsymbol='CANBK-EQ', 71 | quantity=1, discloseqty=0,price_type='SL-LMT', price=200.00, trigger_price=199.50, 72 | retention='DAY', remarks='my_order_001') 73 | ``` 74 | Request Details : 75 | 76 | |Json Fields|Possible value|Description| 77 | | --- | --- | ---| 78 | |uid*||Logged in User Id| 79 | |actid*||Login users account ID| 80 | |exch*|NSE / NFO / BSE / MCX|Exchange (Select from ‘exarr’ Array provided in User Details response)| 81 | |tsym*||Unique id of contract on which order to be placed. (use url encoding to avoid special char error for symbols like M&M)| 82 | |qty*||Order Quantity | 83 | |prc*||Order Price| 84 | |trgprc||Only to be sent in case of SL / SL-M order.| 85 | |dscqty||Disclosed quantity (Max 10% for NSE, and 50% for MCX)| 86 | |prd*|C / 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)| 87 | |trantype*|B / S|B -> BUY, S -> SELL| 88 | |prctyp*|LMT / MKT / SL-LMT / SL-MKT / DS / 2L / 3L|||| 89 | |ret*|DAY / EOS / IOC |Retention type (Show options as per allowed exchanges) | 90 | |remarks||Any tag by user to mark order.| 91 | |ordersource|MOB / WEB / TT |Used to generate exchange info fields.| 92 | |bpprc||Book Profit Price applicable only if product is selected as B (Bracket order ) | 93 | |blprc||Book loss Price applicable only if product is selected as H and B (High Leverage and Bracket order ) | 94 | |trailprc||Trailing Price applicable only if product is selected as H and B (High Leverage and Bracket order ) | 95 | |amo||Yes , If not sent, of Not “Yes”, will be treated as Regular order. | 96 | |tsym2||Trading symbol of second leg, mandatory for price type 2L and 3L (use url encoding to avoid special char error for symbols like M&M)| 97 | |trantype2||Transaction type of second leg, mandatory for price type 2L and 3L| 98 | |qty2||Quantity for second leg, mandatory for price type 2L and 3L| 99 | |prc2||Price for second leg, mandatory for price type 2L and 3L| 100 | |tsym3||Trading symbol of third leg, mandatory for price type 3L (use url encoding to avoid special char error for symbols like M&M)| 101 | |trantype3||Transaction type of third leg, mandatory for price type 3L| 102 | |qty3||Quantity for third leg, mandatory for price type 3L| 103 | |prc3||Price for third leg, mandatory for price type 3L| 104 | 105 | 106 | Response Details : 107 | 108 | Response data will be in json format with below fields. 109 | 110 | |Json Fields|Possible value|Description| 111 | | --- | --- | ---| 112 | |stat|Ok or Not_Ok|Place order success or failure indication.| 113 | |request_time||Response received time.| 114 | |norenordno||It will be present only on successful Order placement to OMS.| 115 | |emsg||This will be present only if Order placement fails| 116 | 117 | Sample Success Response: 118 | { 119 | "request_time": "10:48:03 20-05-2020", 120 | "stat": "Ok", 121 | "norenordno": "20052000000017" 122 | } 123 | 124 | Sample Error Response : 125 | { 126 | "stat": "Not_Ok", 127 | "request_time": "20:40:01 19-05-2020", 128 | "emsg": "Error Occurred : 2 \"invalid input\"" 129 | } 130 | 131 | #### modify_order(orderno, exchange, tradingsymbol, newquantity,newprice_type, newprice, newtrigger_price, amo): 132 | modify the quantity pricetype or price of an order 133 | 134 | Example: 135 | 136 | ``` 137 | orderno = ret['norenordno'] #from placeorder return value 138 | ret = api.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno, 139 | newquantity=2, newprice_type='MKT', newprice=0.00) 140 | ## sl modification 141 | ret = api.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno, 142 | newquantity=2, newprice_type='SL-LMT', newprice=201.00, newtrigger_price=200.00) 143 | ``` 144 | 145 | Request Details : 146 | 147 | |Json Fields|Possible value|Description| 148 | | --- | --- | ---| 149 | |exch*||Exchange| 150 | |norenordno*||Noren order number, which needs to be modified| 151 | |prctyp|LMT / MKT / SL-MKT / SL-LMT|This can be modified.| 152 | |prc||Modified / New price| 153 | |qty||Modified / New Quantity||Quantity to Fill / Order Qty - This is the total qty to be filled for the order. Its Open Qty/Pending Qty plus Filled Shares (cumulative for the order) for the order.|* Please do not send only the pending qty in this field| 154 | |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)| 155 | |ret|DAY / IOC / EOS|New Retention type of the order | 156 | |||| 157 | |trgprc||New trigger price in case of SL-MKT or SL-LMT| 158 | |uid*||User id of the logged in user.| 159 | |bpprc||Book Profit Price applicable only if product is selected as B (Bracket order ) | 160 | |blprc||Book loss Price applicable only if product is selected as H and B (High Leverage and Bracket order ) | 161 | |trailprc||Trailing Price applicable only if product is selected as H and B (High Leverage and Bracket order ) | 162 | 163 | Response Details : 164 | 165 | Response data will be in json format with below fields. 166 | 167 | |Json Fields|Possible value|Description| 168 | | --- | --- | ---| 169 | |stat|Ok or Not_Ok|Modify order success or failure indication.| 170 | |result||Noren Order number of the order modified.| 171 | |request_time||Response received time.| 172 | |emsg||This will be present only if Order modification fails| 173 | 174 | Sample Success Response : 175 | { 176 | "request_time":"14:14:08 26-05-2020", 177 | "stat":"Ok", 178 | "result":"20052600000103" 179 | } 180 | 181 | Sample Failure Response : 182 | { 183 | "request_time":"16:03:29 28-05-2020", 184 | "stat":"Not_Ok", 185 | "emsg":"Rejected : ORA:Order not found" 186 | } 187 | 188 | #### cancel_order(orderno) 189 | cancel an order 190 | 191 | Example: 192 | 193 | ``` 194 | orderno = ret['norenordno'] #from placeorder return value 195 | ret = api.cancel_order(orderno=orderno) 196 | ``` 197 | 198 | Request Details : 199 | 200 | |Json Fields|Possible value|Description| 201 | | --- | --- | ---| 202 | |norenordno*||Noren order number, which needs to be modified| 203 | |uid*||User id of the logged in user.| 204 | 205 | Response Details : 206 | 207 | Response data will be in json format with below fields. 208 | 209 | |Json Fields|Possible value|Description| 210 | | --- | --- | ---| 211 | |stat|Ok or Not_Ok|Cancel order success or failure indication.| 212 | |result||Noren Order number of the canceled order.| 213 | |request_time||Response received time.| 214 | |emsg||This will be present only if Order cancelation fails| 215 | 216 | Sample Success Response : 217 | { 218 | "request_time":"14:14:10 26-05-2020", 219 | "stat":"Ok", 220 | "result":"20052600000103" 221 | } 222 | 223 | Sample Failure Response : 224 | { 225 | "request_time":"16:01:48 28-05-2020", 226 | "stat":"Not_Ok", 227 | "emsg":"Rejected : ORA:Order not found to Cancel" 228 | } 229 | 230 | 231 | #### exit_order(orderno) 232 | exits a cover or bracket order 233 | 234 | Request Details : 235 | 236 | |Json Fields|Possible value|Description| 237 | | --- | --- | ---| 238 | |norenordno*||Noren order number, which needs to be modified| 239 | |prd*|H / B |Allowed for only H and B products (Cover order and bracket order)| 240 | |uid*||User id of the logged in user.| 241 | 242 | Response Details : 243 | 244 | Response data will be in json format with below fields. 245 | 246 | |Json Fields|Possible value|Description| 247 | | --- | --- | ---| 248 | |stat|Ok or Not_Ok|Cancel order success or failure indication.| 249 | |dmsg||Display message, (will be present only in case of success).| 250 | |request_time||Response received time.| 251 | |emsg||This will be present only if Order cancelation fails| 252 | 253 | 254 | #### position_product_conversion(exchange, tradingsymbol, quantity, new_product_type, previous_product_type, buy_or_sell, day_or_cf) 255 | 256 | Convert a product of a position 257 | 258 | Example: 259 | 260 | ``` 261 | ret = api.get_positions() 262 | #converts the first position from existing product to intraday 263 | p = ret[0] 264 | ret = api.position_product_conversion(p['exch'], p['tsym'], p['netqty'], 'I', p['prd'], 'B', 'DAY') 265 | ``` 266 | 267 | Request Details : 268 | 269 | |Json Fields|Possible value|Description| 270 | | --- | --- | ---| 271 | |exch*||Exchange| 272 | |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)| 273 | |qty*||Quantity to be converted.| 274 | |uid*||User id of the logged in user.| 275 | |actid*||Account id| 276 | |prd*||Product to which the user wants to convert position. | 277 | |prevprd*||Original product of the position.| 278 | |trantype*||Transaction type| 279 | |postype*|Day / CF|Converting Day or Carry forward position| 280 | |ordersource|MOB |For Logging| 281 | 282 | Response Details : 283 | 284 | Response data will be in json format with below fields. 285 | 286 | |Json Fields|Possible value|Description| 287 | | --- | --- | ---| 288 | |stat|Ok or Not_Ok|Position conversion success or failure indication.| 289 | |emsg||This will be present only if Position conversion fails.| 290 | 291 | Sample Success Response : 292 | { 293 | "request_time":"10:52:12 02-06-2020", 294 | "stat":"Ok" 295 | } 296 | 297 | Sample Failure Response : 298 | { 299 | "stat":"Not_Ok", 300 | "emsg":"Invalid Input : Invalid Position Type" 301 | } 302 | 303 | #### Order Book 304 | List of Orders placed for the account 305 | 306 | Example : 307 | ``` 308 | ret = api.get_order_book() 309 | print(ret) 310 | ``` 311 | Request Details : 312 | 313 | |Json Fields|Possible value|Description| 314 | | --- | --- | ---| 315 | |uid*||Logged in User Id| 316 | |prd|H / M / ...|Product name| 317 | 318 | Response Details : 319 | 320 | Response data will be in json Array of objects with below fields in case of success. 321 | 322 | |Json Fields|Possible value|Description| 323 | | --- | --- | ---| 324 | |stat|Ok or Not_Ok|Order book success or failure indication.| 325 | |exch||Exchange Segment| 326 | |tsym||Trading symbol / contract on which order is placed.| 327 | |norenordno||Noren Order Number| 328 | |prc||Order Price| 329 | |qty||Order Quantity| 330 | |prd||Display product alias name, using prarr returned in user details.| 331 | |status||| 332 | |trantype|B / S|Transaction type of the order| 333 | |prctyp|LMT / MKT|Price type| 334 | |fillshares||Total Traded Quantity of this order| 335 | |avgprc||Average trade price of total traded quantity | 336 | |rejreason||If order is rejected, reason in text form| 337 | |exchordid||Exchange Order Number| 338 | |cancelqty||Canceled quantity for order which is in status cancelled.| 339 | |remarks||Any message Entered during order entry.| 340 | |dscqty||Order disclosed quantity.| 341 | |trgprc||Order trigger price| 342 | |ret|DAY / IOC / EOS|Order validity| 343 | |uid||| 344 | |actid||| 345 | |bpprc||Book Profit Price applicable only if product is selected as B (Bracket order ) | 346 | |blprc||Book loss Price applicable only if product is selected as H and B (High Leverage and Bracket order ) | 347 | |trailprc||Trailing Price applicable only if product is selected as H and B (High Leverage and Bracket order ) | 348 | |amo||Yes / No| 349 | |pp||Price precision| 350 | |ti||Tick size| 351 | |ls||Lot size| 352 | |token||Contract Token| 353 | |norentm||| 354 | |ordenttm||| 355 | |exch_tm||| 356 | |snoordt||0 for profit leg and 1 for stoploss leg| 357 | |snonum||This field will be present for product H and B; and only if it is profit/sl order.| 358 | 359 | Response data will be in json format with below fields in case of failure: 360 | 361 | |Json Fields|Possible value|Description| 362 | | --- | --- | ---| 363 | |stat|Not_Ok|Order book failure indication.| 364 | |request_time||Response received time.| 365 | |emsg||Error message| 366 | 367 | Sample Success Output : 368 | Success response : 369 | [ 370 | { 371 | “stat” : “Ok”, 372 | “exch” : “NSE” , 373 | “tsym” : “ACC-EQ” , 374 | “norenordno” : “20062500000001223”, 375 | “prc” : “127230”, 376 | “qty” : “100”, 377 | “prd” : “C”, 378 | “status”: “Open”, 379 | “trantype” : “B”, 380 | “prctyp” : ”LMT”, 381 | “fillshares” : “0”, 382 | “avgprc” : “0”, 383 | “exchordid” : “250620000000343421”, 384 | “uid” : “VIDYA”, 385 | “actid” : “CLIENT1”, 386 | “ret” : “DAY”, 387 | “amo” : “Yes” 388 | }, 389 | { 390 | “stat” : “Ok”, 391 | “exch” : “NSE” , 392 | “tsym” : “ABB-EQ” , 393 | “norenordno” : “20062500000002543”, 394 | “prc” : “127830”, 395 | “qty” : “50”, 396 | “prd” : “C”, 397 | “status”: “REJECT”, 398 | “trantype” : “B”, 399 | “prctyp” : ”LMT”, 400 | “fillshares” : “0”, 401 | “avgprc” : “0”, 402 | “rejreason” : “Insufficient funds” 403 | “uid” : “VIDYA”, 404 | “actid” : “CLIENT1”, 405 | “ret” : “DAY”, 406 | “amo” : “No” 407 | } 408 | ] 409 | 410 | Sample Failure Response : 411 | { 412 | "stat":"Not_Ok", 413 | "emsg":"Session Expired : Invalid Session Key" 414 | } 415 | 416 | #### Trade Book 417 | List of Trades of the account 418 | 419 | Example: 420 | ``` 421 | ret = api.get_trade_book() 422 | print(ret) 423 | ``` 424 | 425 | Request Details : 426 | 427 | |Json Fields|Possible value|Description| 428 | | --- | --- | ---| 429 | |uid*||Logged in User Id| 430 | |actid*||Account Id of logged in user| 431 | 432 | Response Details : 433 | 434 | Response data will be in json Array of objects with below fields in case of success. 435 | 436 | |Json Fields|Possible value|Description| 437 | | --- | --- | ---| 438 | |stat|Ok or Not_Ok|Order book success or failure indication.| 439 | |exch||Exchange Segment| 440 | |tsym||Trading symbol / contract on which order is placed.| 441 | |norenordno||Noren Order Number| 442 | |qty||Order Quantity| 443 | |prd||Display product alias name, using prarr returned in user details.| 444 | |trantype|B / S|Transaction type of the order| 445 | |prctyp|LMT / MKT|Price type| 446 | |fillshares||Total Traded Quantity of this order| 447 | |avgprc||Average trade price of total traded quantity | 448 | |exchordid||Exchange Order Number| 449 | |remarks||Any message Entered during order entry.| 450 | |ret|DAY / IOC / EOS|Order validity| 451 | |uid||| 452 | |actid||| 453 | |pp||Price precision| 454 | |ti||Tick size| 455 | |ls||Lot size| 456 | |cstFrm||Custom Firm| 457 | |fltm||Fill Time| 458 | |flid||Fill ID| 459 | |flqty||Fill Qty| 460 | |flprc||Fill Price| 461 | |ordersource||Order Source| 462 | |token||Token| 463 | 464 | Response data will be in json format with below fields in case of failure: 465 | 466 | |Json Fields|Possible value|Description| 467 | | --- | --- | ---| 468 | |stat|Not_Ok|Order book failure indication.| 469 | |request_time||Response received time.| 470 | |emsg||Error message| 471 | 472 | Sample Success Output : 473 | 474 | [ 475 | { 476 | "stat": "Ok", 477 | "norenordno": "20121300065715", 478 | "uid": "GURURAJ", 479 | "actid": "GURURAJ", 480 | "exch": "NSE", 481 | "prctyp": "LMT", 482 | "ret": "DAY", 483 | "prd": "M", 484 | "flid": "102", 485 | "fltm": "01-01-1980 00:00:00", 486 | "trantype": "S", 487 | "tsym": "ACCELYA-EQ", 488 | "qty": "180", 489 | "token": "7053", 490 | "fillshares": "180", 491 | "flqty": "180", 492 | "pp": "2", 493 | "ls": "1", 494 | "ti": "0.05", 495 | "prc": "800.00", 496 | "flprc": "800.00", 497 | "norentm": "19:59:32 13-12-2020", 498 | "exch_tm": "00:00:00 01-01-1980", 499 | "remarks": "WC TEST Order", 500 | "exchordid": "6857" 501 | }, 502 | { 503 | "stat": "Ok", 504 | "norenordno": "20121300065716", 505 | "uid": "GURURAJ", 506 | "actid": "GURURAJ", 507 | "exch": "NSE", 508 | "prctyp": "LMT", 509 | "ret": "DAY", 510 | "prd": "M", 511 | "flid": "101", 512 | "fltm": "01-01-1980 00:00:00", 513 | "trantype": "B", 514 | "tsym": "ACCELYA-EQ", 515 | "qty": "180", 516 | "token": "7053", 517 | "fillshares": "180", 518 | "flqty": "180", 519 | "pp": "2", 520 | "ls": "1", 521 | "ti": "0.05", 522 | "prc": "800.00", 523 | "flprc": "800.00", 524 | "norentm": "19:59:32 13-12-2020", 525 | "exch_tm": "00:00:00 01-01-1980", 526 | "remarks": "WC TEST Order", 527 | "exchordid": "6858" 528 | } 529 | ] 530 | 531 | #### single order history(orderno) 532 | history an order 533 | 534 | ``` 535 | orderno = ret['norenordno'] #from placeorder return value 536 | ret = api.single_order_history(orderno=orderno) 537 | ``` 538 | Request Details : 539 | 540 | |Json Fields|Possible value|Description| 541 | | --- | --- | ---| 542 | |uid*||Logged in User Id| 543 | |norenordno*||Noren Order Number| 544 | 545 | 546 | Response Details : 547 | 548 | Response data will be in json Array of objects with below fields in case of success. 549 | 550 | |Json Fields|Possible value|Description| 551 | | --- | --- | ---| 552 | |stat|Ok or Not_Ok|Order book success or failure indication.| 553 | |exch||Exchange Segment| 554 | |tsym||Trading symbol / contract on which order is placed.| 555 | |norenordno||Noren Order Number| 556 | |prc||Order Price| 557 | |qty||Order Quantity| 558 | |prd||Display product alias name, using prarr returned in user details.| 559 | |status||| 560 | |rpt|| (fill/complete etc)| 561 | |trantype|B / S|Transaction type of the order| 562 | |prctyp|LMT / MKT|Price type| 563 | |fillshares||Total Traded Quantity of this order| 564 | |avgprc||Average trade price of total traded quantity | 565 | |rejreason||If order is rejected, reason in text form| 566 | |exchordid||Exchange Order Number| 567 | |cancelqty||Canceled quantity for order which is in status cancelled.| 568 | |remarks||Any message Entered during order entry.| 569 | |dscqty||Order disclosed quantity.| 570 | |trgprc||Order trigger price| 571 | |ret|DAY / IOC / EOS|Order validity| 572 | |uid||| 573 | |actid||| 574 | |bpprc||Book Profit Price applicable only if product is selected as B (Bracket order ) | 575 | |blprc||Book loss Price applicable only if product is selected as H and B (High Leverage and Bracket order ) | 576 | |trailprc||Trailing Price applicable only if product is selected as H and B (High Leverage and Bracket order ) | 577 | |amo||Yes / No| 578 | |pp||Price precision| 579 | |ti||Tick size| 580 | |ls||Lot size| 581 | |token||Contract Token| 582 | |norentm||| 583 | |ordenttm||| 584 | |exch_tm||| 585 | 586 | Response data will be in json format with below fields in case of failure: 587 | 588 | |Json Fields|Possible value|Description| 589 | | --- | --- | ---| 590 | |stat|Not_Ok|Order book failure indication.| 591 | |request_time||Response received time.| 592 | |emsg||Error message| 593 | 594 | Sample Success Output : 595 | 596 | [ 597 | { 598 | "stat": "Ok", 599 | "norenordno": "20121300065716", 600 | "uid": "DEMO1", 601 | "actid": "DEMO1", 602 | "exch": "NSE", 603 | "tsym": "ACCELYA-EQ", 604 | "qty": "180", 605 | "trantype": "B", 606 | "prctyp": "LMT", 607 | "ret": "DAY", 608 | "token": "7053", 609 | "pp": "2", 610 | "ls": "1", 611 | "ti": "0.05", 612 | "prc": "800.00", 613 | "avgprc": "800.00", 614 | "dscqty": "0", 615 | "prd": "M", 616 | "status": "COMPLETE", 617 | "rpt": "Fill", 618 | "fillshares": "180", 619 | "norentm": "19:59:32 13-12-2020", 620 | "exch_tm": "00:00:00 01-01-1980", 621 | "remarks": "WC TEST Order", 622 | "exchordid": "6858" 623 | }, 624 | { 625 | "stat": "Ok", 626 | "norenordno": "20121300065716", 627 | "uid": "DEMO1", 628 | "actid": "DEMO1", 629 | "exch": "NSE", 630 | "tsym": "ACCELYA-EQ", 631 | "qty": "180", 632 | "trantype": "B", 633 | "prctyp": "LMT", 634 | "ret": "DAY", 635 | "token": "7053", 636 | "pp": "2", 637 | "ls": "1", 638 | "ti": "0.05", 639 | "prc": "800.00", 640 | "dscqty": "0", 641 | "prd": "M", 642 | "status": "OPEN", 643 | "rpt": "New", 644 | "norentm": "19:59:32 13-12-2020", 645 | "exch_tm": "00:00:00 01-01-1980", 646 | "remarks": "WC TEST Order", 647 | "exchordid": "6858" 648 | }, 649 | { 650 | "stat": "Ok", 651 | "norenordno": "20121300065716", 652 | "uid": "DEMO1", 653 | "actid": "DEMO1", 654 | "exch": "NSE", 655 | "tsym": "ACCELYA-EQ", 656 | "qty": "180", 657 | "trantype": "B", 658 | "prctyp": "LMT", 659 | "ret": "DAY", 660 | "token": "7053", 661 | "pp": "2", 662 | "ls": "1", 663 | "ti": "0.05", 664 | "prc": "800.00", 665 | "dscqty": "0", 666 | "prd": "M", 667 | "status": "PENDING", 668 | "rpt": "PendingNew", 669 | "norentm": "19:59:32 13-12-2020", 670 | "remarks": "WC TEST Order" 671 | }, 672 | { 673 | "stat": "Ok", 674 | "norenordno": "20121300065716", 675 | "uid": "DEMO1", 676 | "actid": "DEMO1", 677 | "exch": "NSE", 678 | "tsym": "ACCELYA-EQ", 679 | "qty": "180", 680 | "trantype": "B", 681 | "prctyp": "LMT", 682 | "ret": "DAY", 683 | "token": "7053", 684 | "pp": "2", 685 | "ls": "1", 686 | "ti": "0.05", 687 | "prc": "800.00", 688 | "prd": "M", 689 | "status": "PENDING", 690 | "rpt": "NewAck", 691 | "norentm": "19:59:32 13-12-2020", 692 | "remarks": "WC TEST Order" 693 | } 694 | ] 695 | 696 | #### get_holdings(product_type) 697 | retrieves the holdings as a list 698 | 699 | Example: 700 | ``` 701 | ret = api.get_holdings() 702 | ``` 703 | Request Details : 704 | 705 | |Json Fields|Possible value|Description| 706 | | --- | --- | ---| 707 | |uid*||Logged in User Id| 708 | |actid*||Account id of the logged in user.| 709 | |prd*||Product name| 710 | 711 | Response Details : 712 | Response data will be in json format with below fields in case of Success: 713 | 714 | |Json Fields|Possible value|Description| 715 | | --- | --- | ---| 716 | |stat|Ok or Not_Ok|Holding request success or failure indication.| 717 | |exch_tsym||Array of objects exch_tsym objects as defined below.| 718 | |holdqty||Holding quantity| 719 | |dpqty||DP Holding quantity| 720 | |npoadqty||Non Poa display quantity| 721 | |colqty||Collateral quantity| 722 | |benqty||Beneficiary quantity| 723 | |unplgdqty||Unpledged quantity| 724 | |brkcolqty||Broker Collateral| 725 | |btstqty||BTST quantity| 726 | |btstcolqty||BTST Collateral quantity| 727 | |usedqty||Holding used today| 728 | |upldprc||Average price uploaded along with holdings| 729 | Notes: 730 | Valuation : btstqty + holdqty + brkcolqty + unplgdqty + benqty + Max(npoadqty, dpqty) - usedqty 731 | Salable: btstqty + holdqty + unplgdqty + benqty + dpqty - usedqty 732 | 733 | 734 | Exch_tsym object: 735 | |Json Fields of object in values Array|Possible value|Description| 736 | | --- | --- | ---| 737 | |exch|NSE, BSE, NFO ...|Exchange | 738 | |tsym||Trading symbol of the scrip (contract)| 739 | |token||Token of the scrip (contract)| 740 | |pp||Price precision| 741 | |ti||Tick size| 742 | |ls||Lot size| 743 | 744 | Response data will be in json format with below fields in case of failure: 745 | 746 | |Json Fields|Possible value|Description| 747 | | --- | --- | ---| 748 | |stat|Not_Ok|Position book request failure indication.| 749 | |request_time||Response received time.| 750 | |emsg||Error message| 751 | 752 | Sample Success Response : 753 | [ 754 | { 755 | "stat":"Ok", 756 | "exch_tsym":[ 757 | { 758 | "exch":"NSE", 759 | "token":"13", 760 | "tsym":"ABB-EQ" 761 | } 762 | ], 763 | "holdqty":"2000000", 764 | "colqty":"200", 765 | "btstqty":"0", 766 | "btstcolqty":"0", 767 | "usedqty":"0", 768 | "upldprc" : "1800.00" 769 | }, 770 | { 771 | "stat":"Ok", 772 | "exch_tsym":[ 773 | { 774 | "exch":"NSE", 775 | "token":"22", 776 | "tsym":"ACC-EQ" 777 | } 778 | ], 779 | "holdqty":"2000000", 780 | "colqty":"200", 781 | "btstqty":"0", 782 | "btstcolqty":"0", 783 | "usedqty":"0", 784 | "upldprc" : "1400.00" 785 | } 786 | ] 787 | 788 | Sample Failure Response : 789 | { 790 | "stat":"Not_Ok", 791 | "emsg":"Invalid Input : Missing uid or actid or prd." 792 | } 793 | 794 | #### get_positions() 795 | 796 | retrieves the overnight and day positions as a list 797 | 798 | Example: 799 | ``` 800 | ret = api.get_positions() 801 | mtm = 0 802 | pnl = 0 803 | for i in ret: 804 | mtm += float(i['urmtom']) 805 | pnl += float(i['rpnl']) 806 | day_m2m = mtm + pnl 807 | print(f'{day_m2m} is your Daily MTM') 808 | ``` 809 | 810 | Request Details : 811 | 812 | |Json Fields|Possible value|Description| 813 | | --- | --- | ---| 814 | |uid*||Logged in User Id| 815 | |actid*||Account id of the logged in user.| 816 | 817 | Response Details : 818 | 819 | Response data will be in json format with Array of Objects with below fields in case of success. 820 | 821 | |Json Fields|Possible value|Description| 822 | | --- | --- | ---| 823 | |stat|Ok or Not_Ok|Position book success or failure indication.| 824 | |exch||Exchange segment| 825 | |tsym||Trading symbol / contract.| 826 | |token||Contract token| 827 | |uid||User Id| 828 | |actid||Account Id| 829 | |prd||Product name to be shown.| 830 | |netqty||Net Position quantity| 831 | |netavgprc||Net position average price| 832 | |daybuyqty||Day Buy Quantity| 833 | |daysellqty||Day Sell Quantity| 834 | |daybuyavgprc||Day Buy average price| 835 | |daysellavgprc||Day buy average price| 836 | |daybuyamt||Day Buy Amount| 837 | |daysellamt||Day Sell Amount| 838 | |cfbuyqty||Carry Forward Buy Quantity| 839 | |cforgavgprc||Original Avg Price| 840 | |cfsellqty||Carry Forward Sell Quantity| 841 | |cfbuyavgprc||Carry Forward Buy average price| 842 | |cfsellavgprc||Carry Forward Buy average price| 843 | |cfbuyamt||Carry Forward Buy Amount| 844 | |cfsellamt||Carry Forward Sell Amount| 845 | |lp||LTP| 846 | |rpnl||RealizedPNL| 847 | |urmtom||UnrealizedMTOM.|(Can be recalculated in LTP update :| = netqty * (lp from web socket - netavgprc) * prcftr || 848 | |bep||Break even price| 849 | |openbuyqty||| 850 | |opensellqty||| 851 | |openbuyamt||| 852 | |opensellamt||| 853 | |openbuyavgprc||| 854 | |opensellavgprc||| 855 | |mult||| 856 | |pp||| 857 | |prcftr||gn*pn/(gd*pd). | 858 | |ti||Tick size| 859 | |ls||Lot size| 860 | |request_time||This will be present only in a failure response.| 861 | 862 | Response data will be in json format with below fields in case of failure: 863 | 864 | |Json Fields|Possible value|Description| 865 | | --- | --- | ---| 866 | |stat|Not_Ok|Position book request failure indication.| 867 | |request_time||Response received time.| 868 | |emsg||Error message| 869 | 870 | 871 | Sample Success Response : 872 | [ 873 | { 874 | "stat":"Ok", 875 | "uid":"POORNA", 876 | "actid":"POORNA", 877 | "exch":"NSE", 878 | "tsym":"ACC-EQ", 879 | "prarr":"C", 880 | "pp":"2", 881 | "ls":"1", 882 | "ti":"5.00", 883 | "mult":"1", 884 | "prcftr":"1.000000", 885 | "daybuyqty":"2", 886 | "daysellqty":"2", 887 | "daybuyamt":"2610.00", 888 | "daybuyavgprc":"1305.00", 889 | "daysellamt":"2610.00", 890 | "daysellavgprc":"1305.00", 891 | "cfbuyqty":"0", 892 | "cfsellqty":"0", 893 | "cfbuyamt":"0.00", 894 | "cfbuyavgprc":"0.00", 895 | "cfsellamt":"0.00", 896 | "cfsellavgprc":"0.00", 897 | "openbuyqty":"0", 898 | "opensellqty":"23", 899 | "openbuyamt":"0.00", 900 | "openbuyavgprc":"0.00", 901 | "opensellamt":"30015.00", 902 | "opensellavgprc":"1305.00", 903 | "netqty":"0", 904 | "netavgprc":"0.00", 905 | "lp":"0.00", 906 | "urmtom":"0.00", 907 | "rpnl":"0.00", 908 | "cforgavgprc":"0.00" 909 | 910 | } 911 | ] 912 | 913 | Sample Failure Response : 914 | { 915 | "stat":"Not_Ok", 916 | "request_time":"14:14:11 26-05-2020", 917 | "emsg":"Error Occurred : 5 \"no data\"" 918 | } 919 | 920 | #### get_limits 921 | retrieves the margin and limits set 922 | 923 | Request Details: 924 | 925 | | Param | Type | Optional |Description | 926 | | --- | --- | --- | ---| 927 | | product_type | ```string``` | True | retreives the delivery holdings or for a given product | 928 | | segment | ```string``` | True | CM / FO / FX | 929 | | exchange | ```string``` | True | Exchange NSE/BSE/MCX | 930 | 931 | the response is as follows, 932 | 933 | | Param | Type | Optional |Description | 934 | | --- | --- | --- | ---| 935 | |stat|Ok or Not_Ok| False |Limits request success or failure indication.| 936 | |actid| ```string``` | True |Account id| 937 | |prd| ```string``` | True |Product name| 938 | |seg| ```string``` | True |Segment CM / FO / FX | 939 | |exch| ```string``` | True |Exchange| 940 | |-------------------------Cash Primary Fields-------------------------------| 941 | |cash| ```string``` | True |Cash Margin available| 942 | |payin| ```string``` | True |Total Amount transferred using Payins today | 943 | |payout| ```string``` | True |Total amount requested for withdrawal today| 944 | |-------------------------Cash Additional Fields-------------------------------| 945 | |brkcollamt| ```string``` | True |Prevalued Collateral Amount| 946 | |unclearedcash| ```string``` | True |Uncleared Cash (Payin through cheques)| 947 | |daycash| ```string``` | True |Additional leverage amount / Amount added to handle system errors - by broker. | 948 | |-------------------------Margin Utilized----------------------------------| 949 | |marginused| ```string``` | True |Total margin / fund used today| 950 | |mtomcurper| ```string``` | True |Mtom current percentage| 951 | |-------------------------Margin Used components---------------------| 952 | |cbu| ```string``` | True |CAC Buy used| 953 | |csc| ```string``` | True |CAC Sell Credits| 954 | |rpnl| ```string``` | True |Current realized PNL| 955 | |unmtom| ```string``` | True |Current unrealized mtom| 956 | |marprt| ```string``` | True |Covered Product margins| 957 | |span| ```string``` | True |Span used| 958 | |expo| ```string``` | True |Exposure margin| 959 | |premium| ```string``` | True |Premium used| 960 | |varelm| ```string``` | True |Var Elm Margin| 961 | |grexpo| ```string``` | True |Gross Exposure| 962 | |greexpo_d| ```string``` | True |Gross Exposure derivative| 963 | |scripbskmar| ```string``` | True |Scrip basket margin| 964 | |addscripbskmrg| ```string``` | True |Additional scrip basket margin| 965 | |brokerage| ```string``` | True |Brokerage amount| 966 | |collateral| ```string``` | True |Collateral calculated based on uploaded holdings| 967 | |grcoll| ```string``` | True |Valuation of uploaded holding pre haircut| 968 | |-------------------------Additional Risk Limits---------------------------| 969 | |turnoverlmt| ```string``` | True || 970 | |pendordvallmt| ```string``` | True || 971 | |-------------------------Additional Risk Indicators---------------------------| 972 | |turnover| ```string``` | True |Turnover| 973 | |pendordval| ```string``` | True |Pending Order value| 974 | |-------------------------Margin used detailed breakup fields-------------------------| 975 | |rzpnl_e_i| ```string``` | True |Current realized PNL (Equity Intraday)| 976 | |rzpnl_e_m| ```string``` | True |Current realized PNL (Equity Margin)| 977 | |rzpnl_e_c| ```string``` | True |Current realized PNL (Equity Cash n Carry)| 978 | |rzpnl_d_i| ```string``` | True |Current realized PNL (Derivative Intraday)| 979 | |rzpnl_d_m| ```string``` | True |Current realized PNL (Derivative Margin)| 980 | |rzpnl_f_i| ```string``` | True |Current realized PNL (FX Intraday)| 981 | |rzpnl_f_m| ```string``` | True |Current realized PNL (FX Margin)| 982 | |rzpnl_c_i| ```string``` | True |Current realized PNL (Commodity Intraday)| 983 | |rzpnl_c_m| ```string``` | True |Current realized PNL (Commodity Margin)| 984 | |uzpnl_e_i| ```string``` | True |Current unrealized MTOM (Equity Intraday)| 985 | |uzpnl_e_m| ```string``` | True |Current unrealized MTOM (Equity Margin)| 986 | |uzpnl_e_c| ```string``` | True |Current unrealized MTOM (Equity Cash n Carry)| 987 | |uzpnl_d_i| ```string``` | True |Current unrealized MTOM (Derivative Intraday)| 988 | |uzpnl_d_m| ```string``` | True |Current unrealized MTOM (Derivative Margin)| 989 | |uzpnl_f_i| ```string``` | True |Current unrealized MTOM (FX Intraday)| 990 | |uzpnl_f_m| ```string``` | True |Current unrealized MTOM (FX Margin)| 991 | |uzpnl_c_i| ```string``` | True |Current unrealized MTOM (Commodity Intraday)| 992 | |uzpnl_c_m| ```string``` | True |Current unrealized MTOM (Commodity Margin)| 993 | |span_d_i| ```string``` | True |Span Margin (Derivative Intraday)| 994 | |span_d_m| ```string``` | True |Span Margin (Derivative Margin)| 995 | |span_f_i| ```string``` | True |Span Margin (FX Intraday)| 996 | |span_f_m| ```string``` | True |Span Margin (FX Margin)| 997 | |span_c_i| ```string``` | True |Span Margin (Commodity Intraday)| 998 | |span_c_m| ```string``` | True |Span Margin (Commodity Margin)| 999 | |expo_d_i| ```string``` | True |Exposure Margin (Derivative Intraday)| 1000 | |expo_d_m| ```string``` | True |Exposure Margin (Derivative Margin)| 1001 | |expo_f_i| ```string``` | True |Exposure Margin (FX Intraday)| 1002 | |expo_f_m| ```string``` | True |Exposure Margin (FX Margin)| 1003 | |expo_c_i| ```string``` | True |Exposure Margin (Commodity Intraday)| 1004 | |expo_c_m| ```string``` | True |Exposure Margin (Commodity Margin)| 1005 | |premium_d_i| ```string``` | True |Option premium (Derivative Intraday)| 1006 | |premium_d_m| ```string``` | True |Option premium (Derivative Margin)| 1007 | |premium_f_i| ```string``` | True |Option premium (FX Intraday)| 1008 | |premium_f_m| ```string``` | True |Option premium (FX Margin)| 1009 | |premium_c_i| ```string``` | True |Option premium (Commodity Intraday)| 1010 | |premium_c_m| ```string``` | True |Option premium (Commodity Margin)| 1011 | |varelm_e_i| ```string``` | True |Var Elm (Equity Intraday)| 1012 | |varelm_e_m| ```string``` | True |Var Elm (Equity Margin)| 1013 | |varelm_e_c| ```string``` | True |Var Elm (Equity Cash n Carry)| 1014 | |marprt_e_h| ```string``` | True |Covered Product margins (Equity High leverage)| 1015 | |marprt_e_b| ```string``` | True |Covered Product margins (Equity Bracket Order)| 1016 | |marprt_d_h| ```string``` | True |Covered Product margins (Derivative High leverage)| 1017 | |marprt_d_b| ```string``` | True |Covered Product margins (Derivative Bracket Order)| 1018 | |marprt_f_h| ```string``` | True |Covered Product margins (FX High leverage)| 1019 | |marprt_f_b| ```string``` | True |Covered Product margins (FX Bracket Order)| 1020 | |marprt_c_h| ```string``` | True |Covered Product margins (Commodity High leverage)| 1021 | |marprt_c_b| ```string``` | True |Covered Product margins (Commodity Bracket Order)| 1022 | |scripbskmar_e_i| ```string``` | True |Scrip basket margin (Equity Intraday)| 1023 | |scripbskmar_e_m| ```string``` | True |Scrip basket margin (Equity Margin)| 1024 | |scripbskmar_e_c| ```string``` | True |Scrip basket margin (Equity Cash n Carry)| 1025 | |addscripbskmrg_d_i| ```string``` | True |Additional scrip basket margin (Derivative Intraday)| 1026 | |addscripbskmrg_d_m| ```string``` | True |Additional scrip basket margin (Derivative Margin)| 1027 | |addscripbskmrg_f_i| ```string``` | True |Additional scrip basket margin (FX Intraday)| 1028 | |addscripbskmrg_f_m| ```string``` | True |Additional scrip basket margin (FX Margin)| 1029 | |addscripbskmrg_c_i| ```string``` | True |Additional scrip basket margin (Commodity Intraday)| 1030 | |addscripbskmrg_c_m| ```string``` | True |Additional scrip basket margin (Commodity Margin)| 1031 | |brkage_e_i| ```string``` | True |Brokerage (Equity Intraday)| 1032 | |brkage_e_m| ```string``` | True |Brokerage (Equity Margin)| 1033 | |brkage_e_c| ```string``` | True |Brokerage (Equity CAC)| 1034 | |brkage_e_h| ```string``` | True |Brokerage (Equity High Leverage)| 1035 | |brkage_e_b| ```string``` | True |Brokerage (Equity Bracket Order)| 1036 | |brkage_d_i| ```string``` | True |Brokerage (Derivative Intraday)| 1037 | |brkage_d_m| ```string``` | True |Brokerage (Derivative Margin)| 1038 | |brkage_d_h| ```string``` | True |Brokerage (Derivative High Leverage)| 1039 | |brkage_d_b| ```string``` | True |Brokerage (Derivative Bracket Order)| 1040 | |brkage_f_i| ```string``` | True |Brokerage (FX Intraday)| 1041 | |brkage_f_m| ```string``` | True |Brokerage (FX Margin)| 1042 | |brkage_f_h| ```string``` | True |Brokerage (FX High Leverage)| 1043 | |brkage_f_b| ```string``` | True |Brokerage (FX Bracket Order)| 1044 | |brkage_c_i| ```string``` | True |Brokerage (Commodity Intraday)| 1045 | |brkage_c_m| ```string``` | True |Brokerage (Commodity Margin)| 1046 | |brkage_c_h| ```string``` | True |Brokerage (Commodity High Leverage)| 1047 | |brkage_c_b| ```string``` | True |Brokerage (Commodity Bracket Order)| 1048 | |peak_mar| ```string``` | True |Peak margin used by the client| 1049 | |request_time| ```string``` | True |This will be present only in a successful response.| 1050 | |emsg| ```string``` | True |This will be present only in a failure response.| 1051 | 1052 | Sample Success Response : 1053 | { 1054 | "request_time":"18:07:31 29-05-2020", 1055 | "stat":"Ok", 1056 | "cash":"1500000000000000.00", 1057 | "payin":"0.00", 1058 | "payout":"0.00", 1059 | "brkcollamt":"0.00", 1060 | "unclearedcash":"0.00", 1061 | "daycash":"0.00", 1062 | "turnoverlmt":"50000000000000.00", 1063 | "pendordvallmt":"2000000000000000.00", 1064 | "turnover":"3915000.00", 1065 | "pendordval":"2871000.00", 1066 | "marginused":"3945540.00", 1067 | "mtomcurper":"0.00", 1068 | "urmtom":"30540.00", 1069 | "grexpo":"3915000.00", 1070 | "uzpnl_e_i":"15270.00", 1071 | "uzpnl_e_m":"61080.00", 1072 | "uzpnl_e_c":"-45810.00" 1073 | } 1074 | 1075 | Sample Failure Response : 1076 | { 1077 | "stat":"Not_Ok", 1078 | "emsg":"Server Timeout : " 1079 | } 1080 | Market Info 1081 | 1082 | 1083 | #### searchscrip(exchange, searchtext): 1084 | Search for scrip or contract and its properties 1085 | 1086 | 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 1087 | Trading Symbol: 1088 | 1089 | SymbolName + ExpDate + 'F' for all data having InstrumentName starting with FUT 1090 | 1091 | SymbolName + ExpDate + 'P' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType PE 1092 | 1093 | SymbolName + ExpDate + 'C' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType C 1094 | 1095 | For MCX, F to be ignored for FUT instruments 1096 | 1097 | Example: 1098 | ``` 1099 | exch = 'NFO' 1100 | query = 'BANKNIFTY 30DEC CE' # multiple criteria to narrow results 1101 | ret = api.searchscrip(exchange=exch, searchtext=query) 1102 | 1103 | if ret != None: 1104 | symbols = ret['values'] 1105 | for symbol in symbols: 1106 | print('{0} token is {1}'.format(symbol['tsym'], symbol['token'])) 1107 | ``` 1108 | Example 2: 1109 | ``` 1110 | api.searchscrip(exchange='NSE', searchtext='REL') 1111 | ``` 1112 | This will reply as following 1113 | ``` 1114 | { 1115 | "stat": "Ok", 1116 | "values": [ 1117 | { 1118 | "exch": "NSE", 1119 | "token": "18069", 1120 | "tsym": "REL100NAV-EQ" 1121 | }, 1122 | { 1123 | "exch": "NSE", 1124 | "token": "24225", 1125 | "tsym": "RELAXO-EQ" 1126 | }, 1127 | { 1128 | "exch": "NSE", 1129 | "token": "4327", 1130 | "tsym": "RELAXOFOOT-EQ" 1131 | }, 1132 | { 1133 | "exch": "NSE", 1134 | "token": "18068", 1135 | "tsym": "RELBANKNAV-EQ" 1136 | }, 1137 | { 1138 | "exch": "NSE", 1139 | "token": "2882", 1140 | "tsym": "RELCAPITAL-EQ" 1141 | }, 1142 | { 1143 | "exch": "NSE", 1144 | "token": "18070", 1145 | "tsym": "RELCONSNAV-EQ" 1146 | }, 1147 | { 1148 | "exch": "NSE", 1149 | "token": "18071", 1150 | "tsym": "RELDIVNAV-EQ" 1151 | }, 1152 | { 1153 | "exch": "NSE", 1154 | "token": "18072", 1155 | "tsym": "RELGOLDNAV-EQ" 1156 | }, 1157 | { 1158 | "exch": "NSE", 1159 | "token": "2885", 1160 | "tsym": "RELIANCE-EQ" 1161 | }, 1162 | { 1163 | "exch": "NSE", 1164 | "token": "15068", 1165 | "tsym": "RELIGARE-EQ" 1166 | }, 1167 | { 1168 | "exch": "NSE", 1169 | "token": "553", 1170 | "tsym": "RELINFRA-EQ" 1171 | }, 1172 | { 1173 | "exch": "NSE", 1174 | "token": "18074", 1175 | "tsym": "RELNV20NAV-EQ" 1176 | } 1177 | ] 1178 | } 1179 | ``` 1180 | Request Details : 1181 | 1182 | |Json Fields|Possible value|Description| 1183 | | --- | --- | ---| 1184 | |uid*||Logged in User Id| 1185 | |stext*||Search Text| 1186 | |exch||Exchange (Select from ‘exarr’ Array provided in User Details response)| 1187 | 1188 | Response Details : 1189 | 1190 | Response data will be in json format with below fields. 1191 | 1192 | |Json Fields|Possible value|Description| 1193 | | --- | --- | ---| 1194 | |stat|Ok or Not_Ok|Market watch success or failure indication.| 1195 | |values||Array of json objects. (object fields given in below table)| 1196 | |emsg||This will be present only in case of errors. |That is : 1) Invalid Input| 2) Session Expired| 1197 | 1198 | 1199 | |Json Fields of object in values Array|Possible value|Description| 1200 | | --- | --- | ---| 1201 | |exch|NSE, BSE, NFO ...|Exchange | 1202 | |tsym||Trading symbol of the scrip (contract)| 1203 | |token||Token of the scrip (contract)| 1204 | |pp||Price precision| 1205 | |ti||Tick size| 1206 | |ls||Lot size| 1207 | 1208 | Sample Success Response : 1209 | 1210 | { 1211 | "stat": "Ok", 1212 | "values": [ 1213 | { 1214 | "exch": "NSE", 1215 | "token": "18069", 1216 | "tsym": "REL100NAV-EQ" 1217 | }, 1218 | { 1219 | "exch": "NSE", 1220 | "token": "24225", 1221 | "tsym": "RELAXO-EQ" 1222 | }, 1223 | { 1224 | "exch": "NSE", 1225 | "token": "4327", 1226 | "tsym": "RELAXOFOOT-EQ" 1227 | }, 1228 | { 1229 | "exch": "NSE", 1230 | "token": "18068", 1231 | "tsym": "RELBANKNAV-EQ" 1232 | }, 1233 | { 1234 | "exch": "NSE", 1235 | "token": "2882", 1236 | "tsym": "RELCAPITAL-EQ" 1237 | }, 1238 | { 1239 | "exch": "NSE", 1240 | "token": "18070", 1241 | "tsym": "RELCONSNAV-EQ" 1242 | }, 1243 | { 1244 | "exch": "NSE", 1245 | "token": "18071", 1246 | "tsym": "RELDIVNAV-EQ" 1247 | }, 1248 | { 1249 | "exch": "NSE", 1250 | "token": "18072", 1251 | "tsym": "RELGOLDNAV-EQ" 1252 | }, 1253 | { 1254 | "exch": "NSE", 1255 | "token": "2885", 1256 | "tsym": "RELIANCE-EQ" 1257 | }, 1258 | { 1259 | "exch": "NSE", 1260 | "token": "15068", 1261 | "tsym": "RELIGARE-EQ" 1262 | }, 1263 | { 1264 | "exch": "NSE", 1265 | "token": "553", 1266 | "tsym": "RELINFRA-EQ" 1267 | }, 1268 | { 1269 | "exch": "NSE", 1270 | "token": "18074", 1271 | "tsym": "RELNV20NAV-EQ" 1272 | } 1273 | ] 1274 | } 1275 | 1276 | Sample Failure Response : 1277 | { 1278 | "stat":"Not_Ok", 1279 | "emsg":"No Data : " 1280 | } 1281 | 1282 | #### get_security_info(exchange, token): 1283 | gets the complete details and its properties 1284 | 1285 | Example: 1286 | ``` 1287 | exch = 'NSE' 1288 | token = '22' 1289 | ret = api.get_security_info(exchange=exch, token=token) 1290 | ``` 1291 | Request Details : 1292 | 1293 | |Json Fields|Possible value|Description| 1294 | | --- | --- | ---| 1295 | |uid*||Logged in User Id| 1296 | |exch||Exchange | 1297 | |token||Contract Token| 1298 | 1299 | Response Details : 1300 | 1301 | Response data will have below fields. 1302 | 1303 | |Json Fields|Possible value|Description| 1304 | | --- | --- | ---| 1305 | |request_time||It will be present only in a successful response.| 1306 | |stat|Ok or Not_Ok|Market watch success or failure indication.| 1307 | |exch|NSE, BSE, NFO ...|Exchange | 1308 | |tsym||Trading Symbol| 1309 | |cname||Company Name| 1310 | |symnam||Symbol Name| 1311 | |seg||Segment| 1312 | |exd||Expiry Date| 1313 | |instname||Intrument Name| 1314 | |strprc||Strike Price | 1315 | |optt||Option Type| 1316 | |isin||ISIN| 1317 | |ti ||Tick Size | 1318 | |ls||Lot Size | 1319 | |pp||Price precision| 1320 | |mult||Multiplier| 1321 | |gp_nd||gn/gd * pn/pd| 1322 | |prcunt||Price Units | 1323 | |prcqqty||Price Quote Qty| 1324 | |trdunt||Trade Units | 1325 | |delunt||Delivery Units| 1326 | |frzqty||Freeze Qty| 1327 | |gsmind||scripupdate Gsm Ind| 1328 | |elmbmrg||Elm Buy Margin| 1329 | |elmsmrg||Elm Sell Margin| 1330 | |addbmrg||Additional Long Margin| 1331 | |addsmrg||Additional Short Margin| 1332 | |splbmrg||Special Long Margin | 1333 | |splsmrg||Special Short Margin| 1334 | |delmrg||Delivery Margin | 1335 | |tenmrg||Tender Margin| 1336 | |tenstrd||Tender Start Date| 1337 | |tenendd||Tender End Eate| 1338 | |exestrd||Exercise Start Date| 1339 | |exeendd||Exercise End Date | 1340 | |elmmrg||Elm Margin | 1341 | |varmrg||Var Margin | 1342 | |expmrg||Exposure Margin| 1343 | |token||Contract Token | 1344 | |prcftr_d||((GN / GD) * (PN/PD))| 1345 | 1346 | Sample Success Response : 1347 | { 1348 | "request_time": "17:43:38 31-10-2020", 1349 | "stat": "Ok", 1350 | "exch": "NSE", 1351 | "tsym": "ACC-EQ", 1352 | "cname": "ACC LIMITED", 1353 | "symname": "ACC", 1354 | "seg": "EQT", 1355 | "instname": "EQ", 1356 | "isin": "INE012A01025", 1357 | "pp": "2", 1358 | "ls": "1", 1359 | "ti": "0.05", 1360 | "mult": "1", 1361 | "prcftr_d": "(1 / 1 ) * (1 / 1)", 1362 | "trdunt": "", 1363 | "delunt": "ACC", 1364 | "token": "22", 1365 | "varmrg": "40.00" 1366 | } 1367 | 1368 | Sample Failure Response : 1369 | { 1370 | "stat":"Not_Ok", 1371 | "request_time":"10:50:54 10-12-2020", 1372 | "emsg":"Error Occurred : 5 \"no data\"" 1373 | } 1374 | 1375 | #### get_quotes(exchange, token): 1376 | gets the complete details and its properties 1377 | 1378 | Example: 1379 | ``` 1380 | exch = 'NSE' 1381 | token = '22' 1382 | ret = api.get_quotes(exchange=exch, token=token) 1383 | ``` 1384 | 1385 | Request Details : 1386 | 1387 | |Json Fields|Possible value|Description| 1388 | | --- | --- | ---| 1389 | |uid*||Logged in User Id| 1390 | |exch||Exchange | 1391 | |token||Contract Token| 1392 | 1393 | Response Details : 1394 | 1395 | Response data will be in json format with below fields. 1396 | 1397 | |Json Fields|Possible value|Description| 1398 | | --- | --- | ---| 1399 | |stat|Ok or Not_Ok|Watch list update success or failure indication.| 1400 | |request_time||It will be present only in a successful response.| 1401 | |exch|NSE, BSE, NFO ...|Exchange | 1402 | |tsym||Trading Symbol| 1403 | |cname||Company Name| 1404 | |symname||Symbol Name| 1405 | |seg||Segment| 1406 | |instname||Instrument Name| 1407 | |isin||ISIN| 1408 | |pp||Price precision| 1409 | |ls||Lot Size | 1410 | |ti||Tick Size | 1411 | |mult||Multiplier| 1412 | |uc||Upper circuit limitlc| 1413 | |lc||Lower circuit limit| 1414 | |prcftr_d||Price factor|((GN / GD) * (PN/PD))| 1415 | |token||Token| 1416 | |lp||LTP| 1417 | |o||Open Price| 1418 | |h||Day High Price| 1419 | |l||Day Low Price| 1420 | |v||Volume| 1421 | |ltq||Last trade quantity| 1422 | |ltt||Last trade time| 1423 | |bp1||Best Buy Price 1| 1424 | |sp1||Best Sell Price 1| 1425 | |bp2||Best Buy Price 2| 1426 | |sp2||Best Sell Price 2| 1427 | |bp3||Best Buy Price 3| 1428 | |sp3||Best Sell Price 3| 1429 | |bp4||Best Buy Price 4| 1430 | |sp4||Best Sell Price 4| 1431 | |bp5||Best Buy Price 5| 1432 | |sp5||Best Sell Price 5| 1433 | |bq1||Best Buy Quantity 1| 1434 | |sq1||Best Sell Quantity 1| 1435 | |bq2||Best Buy Quantity 2| 1436 | |sq2||Best Sell Quantity 2| 1437 | |bq3||Best Buy Quantity 3| 1438 | |sq3||Best Sell Quantity 3| 1439 | |bq4||Best Buy Quantity 4| 1440 | |sq4||Best Sell Quantity 4| 1441 | |bq5||Best Buy Quantity 5| 1442 | |sq5||Best Sell Quantity 5| 1443 | |bo1||Best Buy Orders 1| 1444 | |so1||Best Sell Orders 1| 1445 | |bo2||Best Buy Orders 2| 1446 | |so2||Best Sell Orders 2| 1447 | |bo3||Best Buy Orders 3| 1448 | |so3||Best Sell Orders 3| 1449 | |bo4||Best Buy Orders 4| 1450 | |so4||Best Sell Orders 4| 1451 | |bo5||Best Buy Orders 5| 1452 | |so5||Best Sell Orders 5| 1453 | 1454 | 1455 | Sample Success Response : 1456 | { 1457 | "request_time":"12:05:21 18-05-2021", 1458 | "stat":"Ok" 1459 | ,"exch":"NSE", 1460 | "tsym":"ACC-EQ", 1461 | "cname":"ACC LIMITED", 1462 | "symname":"ACC", 1463 | "seg":"EQT", 1464 | "instname":"EQ", 1465 | "isin":"INE012A01025", 1466 | "pp":"2", 1467 | "ls":"1", 1468 | "ti":"0.05", 1469 | "mult":"1", 1470 | "uc":"2093.95", 1471 | "lc":"1713.25", 1472 | "prcftr_d":"(1 / 1 ) * (1 / 1)", 1473 | "token":"22", 1474 | "lp":"0.00", 1475 | "h":"0.00", 1476 | "l":"0.00", 1477 | "v":"0", 1478 | "ltq":"0", 1479 | "ltt":"05:30:00", 1480 | "bp1":"2000.00", 1481 | "sp1":"0.00", 1482 | "bp2":"0.00", 1483 | "sp2":"0.00", 1484 | "bp3":"0.00", 1485 | "sp3":"0.00", 1486 | "bp4":"0.00", 1487 | "sp4":"0.00", 1488 | "bp5":"0.00", 1489 | "sp5":"0.00", 1490 | "bq1":"2", 1491 | "sq1":"0", 1492 | "bq2":"0", 1493 | "sq2":"0", 1494 | "bq3":"0", 1495 | "sq3":"0", 1496 | "bq4":"0", 1497 | "sq4":"0", 1498 | "bq5":"0", 1499 | "sq5":"0", 1500 | "bo1":"2", 1501 | "so1":"0", 1502 | "bo2":"0", 1503 | "so2":"0", 1504 | "bo3":"0", 1505 | "so3":"0", 1506 | "bo4":"0", 1507 | "so4":"0", 1508 | "bo5":"0", 1509 | "So5":"0" 1510 | } 1511 | 1512 | Sample Failure Response : 1513 | { 1514 | "stat":"Not_Ok", 1515 | "request_time":"10:50:54 10-12-2020", 1516 | "emsg":"Error Occurred : 5 \"no data\"" 1517 | } 1518 | 1519 | #### get_time_price_series(exchange, token, starttime, endtime, interval): 1520 | gets the chart date for the symbol 1521 | 1522 | Example: 1523 | ``` 1524 | lastBusDay = datetime.datetime.today() 1525 | lastBusDay = lastBusDay.replace(hour=0, minute=0, second=0, microsecond=0) 1526 | ret = api.get_time_price_series(exchange='NSE', token='22', starttime=lastBusDay.timestamp(), interval=5) 1527 | ``` 1528 | Request Details : 1529 | 1530 | |Json Fields|Possible value|Description| 1531 | | --- | --- | ---| 1532 | |uid*||Logged in User Id| 1533 | |exch*||Exchange| 1534 | |token*||| 1535 | |st||Start time (seconds since 1 jan 1970)| 1536 | |et||End Time (seconds since 1 jan 1970)| 1537 | |intrv|“1”, ”3”, “5”, “10”, “15”, “30”, “60”, “120”, “240”|Candle size in minutes (optional field, if not given assume to be “1”)| 1538 | 1539 | Response Details : 1540 | 1541 | Response data will be in json format in case for failure. 1542 | 1543 | |Json Fields|Possible value|Description| 1544 | | --- | --- | ---| 1545 | |stat|Not_Ok|TPData failure indication.| 1546 | |emsg||This will be present only in case of errors. | 1547 | 1548 | Response data will be in json format in case for success. 1549 | 1550 | |Json Fields|Possible value|Description| 1551 | | --- | --- | ---| 1552 | |stat|Ok|TPData success indication.| 1553 | |time||DD/MM/CCYY hh:mm:ss| 1554 | |into||Interval open| 1555 | |inth||Interval high| 1556 | |intl||Interval low| 1557 | |intc||Interval close| 1558 | |intvwap||Interval vwap| 1559 | |intv||Interval volume| 1560 | |v||volume| 1561 | |intoi||Interval io change| 1562 | |oi||oi| 1563 | 1564 | 1565 | Sample Success Response : 1566 | [ 1567 | { 1568 | "stat":"Ok", 1569 | "time":"02-06-2020 15:46:23", 1570 | "into":"0.00", 1571 | "inth":"0.00", 1572 | "intl":"0.00", 1573 | "intc":"0.00", 1574 | "intvwap":"0.00", 1575 | "intv":"0", 1576 | "intoi":"0", 1577 | "v":"980515", 1578 | "oi":"128702" 1579 | }, 1580 | { 1581 | "stat":"Ok", 1582 | "time":"02-06-2020 15:45:23", 1583 | "into":"0.00", 1584 | "inth":"0.00", 1585 | "intl":"0.00", 1586 | "intc":"0.00", 1587 | "intvwap":"0.00", 1588 | "intv":"0", 1589 | "intoi":"0", 1590 | "v":"980515", 1591 | "oi":"128702" 1592 | }, 1593 | { 1594 | "stat":"Ok", 1595 | "time":"02-06-2020 15:44:23", 1596 | "into":"0.00", 1597 | "inth":"0.00", 1598 | "intl":"0.00", 1599 | "intc":"0.00", 1600 | "intvwap":"0.00", 1601 | "intv":"0", 1602 | "intoi":"0", 1603 | "v":"980515", 1604 | "oi":"128702" 1605 | }, 1606 | { 1607 | "stat":"Ok", 1608 | "time":"02-06-2020 15:43:23", 1609 | "into":"1287.00", 1610 | "inth":"1287.00", 1611 | "intl":"0.00", 1612 | "intc":"1287.00", 1613 | "intvwap":"128702.00", 1614 | "intv":"4", 1615 | "intoi":"128702", 1616 | "v":"980515", 1617 | "oi":"128702" 1618 | }, 1619 | { 1620 | "stat":"Ok", 1621 | "time":"02-06-2020 15:42:23", 1622 | "into":"0.00", 1623 | "inth":"0.00", 1624 | "intl":"0.00", 1625 | "intc":"0.00", 1626 | "intvwap":"0.00", 1627 | "intv":"0", 1628 | "intoi":"0", 1629 | "v":"980511", 1630 | "oi":"128702" 1631 | } 1632 | ] 1633 | 1634 | Sample Failure Response : 1635 | { 1636 | "stat":"Not_Ok", 1637 | "emsg":"Session Expired : Invalid Session Key" 1638 | } 1639 | 1640 | 1641 | #### get_option_chain(exchange, tradingsymbol, strikeprice, count): 1642 | 1643 | gets the contracts of related strikes 1644 | 1645 | | Param | Type | Optional |Description | 1646 | | --- | --- | --- | ---| 1647 | | exchange | ```string``` | False | Exchange (UI need to check if exchange in NFO / CDS / MCX / or any other exchange which has options, if not don't allow)| 1648 | | tradingsymbol | ```string``` | False | Trading 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)| 1649 | | strikeprice | ```float``` | False | Mid price for option chain selection| 1650 | | count | ```int``` | True | Number 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)| 1651 | 1652 | the response is as follows, 1653 | 1654 | | Param | Type | Optional |Description | 1655 | | --- | --- | --- | ---| 1656 | | stat | ```string``` | True | ok or Not_ok | 1657 | | values | ```string``` | True | properties of the scrip | 1658 | | emsg | ```string``` | False | Error Message | 1659 | 1660 | | Param | Type | Optional |Description | 1661 | | --- | --- | --- | ---| 1662 | | exch | ```string``` | False | Exchange | 1663 | | tsym | ```string``` | False | Trading Symbol of Contract | 1664 | | token | ```string``` | False | Contract token | 1665 | | optt | ```string``` | False | Option type | 1666 | | strprc | ```string``` | False | Strike Price | 1667 | | pp | ```string``` | False | Price Precision | 1668 | | ti | ```string``` | False | Tick Size | 1669 | | ls | ```string``` | False | Lot Size | 1670 | 1671 | #### start_websocket() 1672 | starts the websocket, WebSocket feed has 2 types of ticks( t=touchline d=depth)and 2 stages (k=acknowledgement, f=further change in tick). 1673 | 1674 | | Param | Type | Optional |Description | 1675 | | --- | --- | --- | ---| 1676 | | subscribe_callback | ```function``` | False | callback for market updates | 1677 | | order_update_callback | ```function```| False | callback for order updates | 1678 | | socket_open_callback | ```function``` | False | callback when socket is open (reconnection also) | 1679 | | socket_close_callback | ```function```| False | callback when socket is closed | 1680 | 1681 | #### subscribe_orders() 1682 | get order and trade update callbacks 1683 | 1684 | Subscription Acknowledgement: 1685 | 1686 | | Json Fields| Possible value| Description| 1687 | | --- | --- | --- | 1688 | | t | ok | ‘ok’ represents order update subscription acknowledgement | 1689 | 1690 | Order Update subscription Updates : 1691 | 1692 | | Json Fields | Possible value | Description | 1693 | | --- | --- | --- | 1694 | | t | om | ‘om’ represents touchline feed | 1695 | | norenordno | | Noren Order Number | 1696 | | uid | | User Id | 1697 | | actid | | Account ID | 1698 | | exch | | Exchange | 1699 | | tsym | | Trading symbol | 1700 | | qty | | Order quantity | 1701 | | prc | | Order Price | 1702 | | prd | | Product | 1703 | | status | | Order status (New, Replaced, Complete, Rejected etc) | 1704 | | reporttype | | Order event for which this message is sent out. (Fill, Rejected, Canceled) | 1705 | | trantype | | Order transaction type, buy or sell | 1706 | | prctyp | | Order price type (LMT, MKT, SL-LMT, SL-MKT) | 1707 | | ret | | Order retention type (DAY, EOS, IOC,...) | 1708 | | fillshares | | Total Filled shares for this order | 1709 | | avgprc | | Average fill price | 1710 | | fltm | | Fill Time(present only when reporttype is Fill) | 1711 | | flid | | Fill ID (present only when reporttype is Fill) | 1712 | | flqty | | Fill Qty(present only when reporttype is Fill) | 1713 | | flprc | | Fill Price(present only when reporttype is Fill) | 1714 | | rejreason | | Order rejection reason, if rejected | 1715 | | exchordid | | Exchange Order ID | 1716 | | cancelqty | | Canceled quantity, in case of canceled order | 1717 | | remarks | | User added tag, while placing order | 1718 | | dscqty | | Disclosed quantity | 1719 | | trgprc | | Trigger price for SL orders | 1720 | | snonum | | This will be present for child orders in case of cover and bracket orders, if present needs to be sent during exit | 1721 | | snoordt | | This will be present for child orders in case of cover and bracket orders, it will indicate whether the order is profit or stoploss | 1722 | | blprc | | This will be present for cover and bracket parent order. This is the differential stop loss trigger price to be entered. | 1723 | | bpprc | | This will be present for bracket parent order. This is the differential profit price to be entered. | 1724 | | trailprc | | This will be present for cover and bracket parent order. This is required if trailing ticks is to be enabled. | 1725 | | exch_tm | | This will have the exchange update time | 1726 | 1727 | 1728 | #### subscribe([instruments]) 1729 | send a list of instruments to watch 1730 | 1731 | t='tk' is sent once on subscription for each instrument. this will have all the fields with the most recent value 1732 | thereon t='tf' is sent for fields that have changed. 1733 | ``` 1734 | For example 1735 | 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'} 1736 | 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'} 1737 | quote event: 03-12-2021 11:54:46{'t': 'tf', 'e': 'NSE', 'tk': '11630', 'lp': '118.60'} 1738 | ``` 1739 | 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 1740 | in the next tick ( 3rd message) only last price is changed to 118.6 1741 | 1742 | This method can be used to subscribe indices as well such as Nifty-50 [NSE|26000], BankNifty[NSE|26009] 1743 | 1744 | | Param | Type | Optional |Description | 1745 | | --- | --- | --- | -----| 1746 | | instruments | ```list``` | False | list of instruments [NSE\|22,CDS\|1] | 1747 | 1748 | Subscription Acknowledgement: 1749 | 1750 | Number of Acknowledgements for a single subscription will be the same as the number of scrips mentioned in the key (k) field. 1751 | 1752 | | Json Fields | Possible value | Description| 1753 | | --- | --- | --- | 1754 | | t | tk |‘tk’ represents touchline acknowledgement | 1755 | | e |NSE, BSE, NFO ..|Exchange name | 1756 | | tk |22|Scrip Token | 1757 | | pp |2 for NSE, BSE & 4 for CDS USDINR|Price precision | 1758 | | ts | | Trading Symbol | 1759 | | ti | | Tick size | 1760 | | ls | | Lot size | 1761 | | lp | |LTP | 1762 | | pc | |Percentage change | 1763 | | v | | volume | 1764 | | o | | Open price | 1765 | | h | | High price | 1766 | | l | | Low price | 1767 | | c | | Close price | 1768 | | ap | | Average trade price | 1769 | | oi | | Open interest | 1770 | | poi | | Previous day closing Open Interest | 1771 | | toi | | Total open interest for underlying | 1772 | | bq1 | | Best Buy Quantity 1 | 1773 | | bp1 | | Best Buy Price 1 | 1774 | | sq1 | | Best Sell Quantity 1 | 1775 | | sp1 | | Best Sell Price 1| 1776 | 1777 | TouchLine subscription Updates : 1778 | Accept for t, e, and tk other fields may / may not be present. 1779 | 1780 | | Json Fields | Possible value | Description| 1781 | | --- | --- | --- | 1782 | | t | tf |‘tf’ represents touchline acknowledgement | 1783 | | e |NSE, BSE, NFO ..|Exchange name | 1784 | | tk | 22 |Scrip Token | 1785 | | lp | |LTP | 1786 | | pc | |Percentage change | 1787 | | v | | volume | 1788 | | o | | Open price | 1789 | | h | | High price | 1790 | | l | | Low price | 1791 | | c | | Close price | 1792 | | ap | | Average trade price | 1793 | | oi | | Open interest | 1794 | | poi | | Previous day closing Open Interest | 1795 | | toi | | Total open interest for underlying | 1796 | | bq1 | | Best Buy Quantity 1 | 1797 | | bp1 | | Best Buy Price 1 | 1798 | | sq1 | | Best Sell Quantity 1 | 1799 | | sp1 | | Best Sell Price 1| 1800 | 1801 | #### unsubscribe() 1802 | send a list of instruments to stop watch 1803 | 1804 | **** 1805 | ## Example - Getting Started 1806 | Provide your token and user id as follows. 1807 | 1808 | ```python 1809 | from api_helper import NorenApiPy 1810 | import logging 1811 | 1812 | #enable dbug to see request and responses 1813 | logging.basicConfig(level=logging.DEBUG) 1814 | 1815 | #start of our program 1816 | api = NorenApiPy() 1817 | 1818 | #set token and user id 1819 | #paste the token generated using the login flow described 1820 | # in LOGIN FLOW of https://pi.flattrade.in/docs 1821 | usersession='token here' 1822 | userid = 'user id here' 1823 | 1824 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 1825 | 1826 | print(ret) 1827 | ``` 1828 | 1829 | ## Example Symbol/Contract : Example_market.py 1830 | This Example shows API usage for finding scrips and its properties 1831 | 1832 | ### Search Scrips 1833 | 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 1834 | Trading Symbol: 1835 | 1836 | SymbolName + ExpDate + 'F' for all data having InstrumentName starting with FUT 1837 | 1838 | SymbolName + ExpDate + 'P' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType PE 1839 | 1840 | SymbolName + ExpDate + 'C' + StrikePrice for all data having InstrumentName starting with OPT and with OptionType C 1841 | 1842 | For MCX, F to be ignored for FUT instruments 1843 | 1844 | ``` 1845 | api.searchscrip(exchange='NSE', searchtext='REL') 1846 | ``` 1847 | This will reply as following 1848 | ``` 1849 | { 1850 | "stat": "Ok", 1851 | "values": [ 1852 | { 1853 | "exch": "NSE", 1854 | "token": "18069", 1855 | "tsym": "REL100NAV-EQ" 1856 | }, 1857 | { 1858 | "exch": "NSE", 1859 | "token": "24225", 1860 | "tsym": "RELAXO-EQ" 1861 | }, 1862 | { 1863 | "exch": "NSE", 1864 | "token": "4327", 1865 | "tsym": "RELAXOFOOT-EQ" 1866 | }, 1867 | { 1868 | "exch": "NSE", 1869 | "token": "18068", 1870 | "tsym": "RELBANKNAV-EQ" 1871 | }, 1872 | { 1873 | "exch": "NSE", 1874 | "token": "2882", 1875 | "tsym": "RELCAPITAL-EQ" 1876 | }, 1877 | { 1878 | "exch": "NSE", 1879 | "token": "18070", 1880 | "tsym": "RELCONSNAV-EQ" 1881 | }, 1882 | { 1883 | "exch": "NSE", 1884 | "token": "18071", 1885 | "tsym": "RELDIVNAV-EQ" 1886 | }, 1887 | { 1888 | "exch": "NSE", 1889 | "token": "18072", 1890 | "tsym": "RELGOLDNAV-EQ" 1891 | }, 1892 | { 1893 | "exch": "NSE", 1894 | "token": "2885", 1895 | "tsym": "RELIANCE-EQ" 1896 | }, 1897 | { 1898 | "exch": "NSE", 1899 | "token": "15068", 1900 | "tsym": "RELIGARE-EQ" 1901 | }, 1902 | { 1903 | "exch": "NSE", 1904 | "token": "553", 1905 | "tsym": "RELINFRA-EQ" 1906 | }, 1907 | { 1908 | "exch": "NSE", 1909 | "token": "18074", 1910 | "tsym": "RELNV20NAV-EQ" 1911 | } 1912 | ] 1913 | } 1914 | ``` 1915 | ### Security Info 1916 | This call is done to get the properties of the scrip such as freeze qty and margins 1917 | ``` 1918 | api.get_security_info(exchange='NSE', token='22') 1919 | ``` 1920 | The response for the same would be 1921 | ``` 1922 | { 1923 | "request_time": "17:43:38 31-10-2020", 1924 | "stat": "Ok", 1925 | "exch": "NSE", 1926 | "tsym": "ACC-EQ", 1927 | "cname": "ACC LIMITED", 1928 | "symname": "ACC", 1929 | "seg": "EQT", 1930 | "instname": "EQ", 1931 | "isin": "INE012A01025", 1932 | "pp": "2", 1933 | "ls": "1", 1934 | "ti": "0.05", 1935 | "mult": "1", 1936 | "prcftr_d": "(1 / 1 ) * (1 / 1)", 1937 | "trdunt": "ACC.BO", 1938 | "delunt": "ACC", 1939 | "token": "22", 1940 | "varmrg": "40.00" 1941 | } 1942 | 1943 | ``` 1944 | ### Subscribe to a live feed 1945 | Subscribe to a single token as follows 1946 | 1947 | ``` 1948 | api.subscribe('NSE|13') 1949 | ``` 1950 | 1951 | Subscribe to a list of tokens as follows 1952 | ``` 1953 | api.subscribe(['NSE|22', 'BSE|522032']) 1954 | ``` 1955 | 1956 | First we need to connect to the WebSocket and then subscribe as follows 1957 | ``` 1958 | feed_opened = False 1959 | 1960 | def event_handler_feed_update(tick_data): 1961 | print(f"feed update {tick_data}") 1962 | 1963 | def open_callback(): 1964 | global feed_opened 1965 | feed_opened = True 1966 | 1967 | 1968 | api.start_websocket( order_update_callback=event_handler_order_update, 1969 | subscribe_callback=event_handler_feed_update, 1970 | socket_open_callback=open_callback) 1971 | 1972 | while(feed_opened==False): 1973 | pass 1974 | 1975 | # subscribe to a single token 1976 | api.subscribe('NSE|13') 1977 | 1978 | #subscribe to multiple tokens 1979 | api.subscribe(['NSE|22', 'BSE|522032']) 1980 | ``` 1981 | ## Example - Orders and Trades : example_orders.py 1982 | ### Place Order 1983 | Place a Limit order as follows 1984 | ``` 1985 | api.place_order(buy_or_sell='B', product_type='C', 1986 | exchange='NSE', tradingsymbol='INFY-EQ', 1987 | quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None, 1988 | retention='DAY', remarks='my_order_001') 1989 | ``` 1990 | Place a Market Order as follows 1991 | ``` 1992 | api.place_order(buy_or_sell='B', product_type='C', 1993 | exchange='NSE', tradingsymbol='INFY-EQ', 1994 | quantity=1, discloseqty=0,price_type='MKT', price=0, trigger_price=None, 1995 | retention='DAY', remarks='my_order_001') 1996 | ``` 1997 | Place a StopLoss Order as follows 1998 | ``` 1999 | api.place_order(buy_or_sell='B', product_type='C', 2000 | exchange='NSE', tradingsymbol='INFY-EQ', 2001 | quantity=1, discloseqty=0,price_type='SL-LMT', price=1500, trigger_price=1450, 2002 | retention='DAY', remarks='my_order_001') 2003 | ``` 2004 | Place a Cover Order as follows 2005 | ``` 2006 | api.place_order(buy_or_sell='B', product_type='H', 2007 | exchange='NSE', tradingsymbol='INFY-EQ', 2008 | quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None, 2009 | retention='DAY', remarks='my_order_001', bookloss_price = 1490) 2010 | ``` 2011 | Place a Bracket Order as follows 2012 | ``` 2013 | api.place_order(buy_or_sell='B', product_type='B', 2014 | exchange='NSE', tradingsymbol='INFY-EQ', 2015 | quantity=1, discloseqty=0,price_type='LMT', price=1500, trigger_price=None, 2016 | retention='DAY', remarks='my_order_001', bookloss_price = 1490, bookprofit_price = 1510) 2017 | ``` 2018 | ### Modify Order 2019 | Modify a New Order by providing the OrderNumber 2020 | ``` 2021 | api.modify_order(exchange='NSE', tradingsymbol='INFY-EQ', orderno=orderno, 2022 | newquantity=2, newprice_type='LMT', newprice=1505) 2023 | ``` 2024 | ### Cancel Order 2025 | Cancel a New Order by providing the Order Number 2026 | ``` 2027 | api.cancel_order(orderno=orderno) 2028 | ``` 2029 | ### Subscribe to Order Updates 2030 | 2031 | Connecting to the Websocket will automatically subscribe and provide the order updates in the call back as follows 2032 | Note: Feed and Order updates are received from the same websocket and needs to be connected once only. 2033 | 2034 | ``` 2035 | feed_opened = False 2036 | 2037 | def event_handler_order_update(order): 2038 | print(f"order feed {order}") 2039 | 2040 | def open_callback(): 2041 | global feed_opened 2042 | feed_opened = True 2043 | 2044 | 2045 | api.start_websocket( order_update_callback=event_handler_order_update, 2046 | subscribe_callback=event_handler_feed_update, 2047 | socket_open_callback=open_callback) 2048 | 2049 | while(feed_opened==False): 2050 | pass 2051 | 2052 | 2053 | ``` 2054 | 2055 | **** 2056 | 2057 | 2058 | 2059 | 2060 | -------------------------------------------------------------------------------- /api_helper.py: -------------------------------------------------------------------------------- 1 | from NorenRestApiPy.NorenApi import NorenApi 2 | from threading import Timer 3 | import pandas as pd 4 | import time 5 | import concurrent.futures 6 | 7 | api = None 8 | class Order: 9 | def __init__(self, buy_or_sell:str = None, product_type:str = None, 10 | exchange: str = None, tradingsymbol:str =None, 11 | price_type: str = None, quantity: int = None, 12 | price: float = None,trigger_price:float = None, discloseqty: int = 0, 13 | retention:str = 'DAY', remarks: str = "tag", 14 | order_id:str = None): 15 | self.buy_or_sell=buy_or_sell 16 | self.product_type=product_type 17 | self.exchange=exchange 18 | self.tradingsymbol=tradingsymbol 19 | self.quantity=quantity 20 | self.discloseqty=discloseqty 21 | self.price_type=price_type 22 | self.price=price 23 | self.trigger_price=trigger_price 24 | self.retention=retention 25 | self.remarks=remarks 26 | self.order_id=None 27 | 28 | 29 | #print(ret) 30 | 31 | 32 | 33 | 34 | def get_time(time_string): 35 | data = time.strptime(time_string,'%d-%m-%Y %H:%M:%S') 36 | 37 | return time.mktime(data) 38 | 39 | 40 | class NorenApiPy(NorenApi): 41 | def __init__(self): 42 | # NorenApi.__init__(self, host='https://piconnect.flattrade.in/PiConnectTP/', websocket='wss://piconnect.flattrade.in/PiConnectWSTp/', eodhost='https://web.flattrade.in/chartApi/getdata/') 43 | NorenApi.__init__(self, host='https://piconnect.flattrade.in/PiConnectTP/', websocket='wss://piconnect.flattrade.in/PiConnectWSTp/') 44 | 45 | global api 46 | api = self 47 | def place_basket(self, orders): 48 | 49 | resp_err = 0 50 | resp_ok = 0 51 | result = [] 52 | with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: 53 | 54 | future_to_url = {executor.submit(self.place_order, order): order for order in orders} 55 | for future in concurrent.futures.as_completed(future_to_url): 56 | url = future_to_url[future] 57 | try: 58 | result.append(future.result()) 59 | except Exception as exc: 60 | print(exc) 61 | resp_err = resp_err + 1 62 | else: 63 | resp_ok = resp_ok + 1 64 | 65 | return result 66 | 67 | def placeOrder(self,order: Order): 68 | ret = NorenApi.place_order(self, buy_or_sell=order.buy_or_sell, product_type=order.product_type, 69 | exchange=order.exchange, tradingsymbol=order.tradingsymbol, 70 | quantity=order.quantity, discloseqty=order.discloseqty, price_type=order.price_type, 71 | price=order.price, trigger_price=order.trigger_price, 72 | retention=order.retention, remarks=order.remarks) 73 | #print(ret) 74 | 75 | return ret -------------------------------------------------------------------------------- /dist/NorenRestApi-0.0.29-py3-none-any.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flattrade/pythonAPI/ad69ba7f17a72828a84e67c210422248f07e7d12/dist/NorenRestApi-0.0.29-py3-none-any.whl -------------------------------------------------------------------------------- /example_market.py: -------------------------------------------------------------------------------- 1 | from api_helper import NorenApiPy, get_time 2 | import logging 3 | import time 4 | import pandas as pd 5 | 6 | #sample 7 | logging.basicConfig(level=logging.DEBUG) 8 | 9 | #flag to tell us if the websocket is open 10 | socket_opened = False 11 | 12 | #application callbacks 13 | def event_handler_order_update(message): 14 | print("order event: " + str(message)) 15 | 16 | 17 | def event_handler_quote_update(message): 18 | #e Exchange 19 | #tk Token 20 | #lp LTP 21 | #pc Percentage change 22 | #v volume 23 | #o Open price 24 | #h High price 25 | #l Low price 26 | #c Close price 27 | #ap Average trade price 28 | 29 | print("quote event: {0}".format(time.strftime('%d-%m-%Y %H:%M:%S')) + str(message)) 30 | 31 | 32 | def open_callback(): 33 | global socket_opened 34 | socket_opened = True 35 | print('app is connected') 36 | 37 | api.subscribe('NSE|11630') 38 | #api.subscribe(['NSE|22', 'BSE|522032']) 39 | 40 | #end of callbacks 41 | 42 | def get_time(time_string): 43 | data = time.strptime(time_string,'%d-%m-%Y %H:%M:%S') 44 | 45 | return time.mktime(data) 46 | 47 | #start of our program 48 | api = NorenApiPy() 49 | 50 | 51 | #set token and user id 52 | #paste the token generated using the login flow described 53 | # in LOGIN FLOW of https://pi.flattrade.in/docs 54 | usersession='token here' 55 | userid = 'user id here' 56 | 57 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 58 | 59 | if ret != None: 60 | while True: 61 | print('f => find symbol') 62 | print('m => get quotes') 63 | print('p => contract info n properties') 64 | print('v => get 1 min market data') 65 | print('t => get today 1 min market data') 66 | print('d => get daily data') 67 | print('o => get option chain') 68 | print('s => start_websocket') 69 | print('q => quit') 70 | 71 | prompt1=input('what shall we do? ').lower() 72 | 73 | if prompt1 == 'v': 74 | start_time = "13-07-2021 09:10:00" 75 | #end_time = time.time() 76 | 77 | start_secs = get_time(start_time) 78 | 79 | end_time = get_time("13-07-2021 09:20:00") 80 | ret = api.get_time_price_series(exchange='NSE', token='22', starttime=start_secs, endtime=end_time) 81 | 82 | df = pd.DataFrame.from_dict(ret) 83 | print(df) 84 | print(f'{start_secs} to {end_time}') 85 | 86 | elif prompt1 == 't': 87 | ret = api.get_time_price_series(exchange='NSE', token='22') 88 | 89 | df = pd.DataFrame.from_dict(ret) 90 | print(df) 91 | 92 | 93 | elif prompt1 == 'f': 94 | exch = 'NFO' 95 | query = 'BANKNIFTY 30DEC CE' 96 | ret = api.searchscrip(exchange=exch, searchtext=query) 97 | print(ret) 98 | 99 | if ret != None: 100 | symbols = ret['values'] 101 | for symbol in symbols: 102 | print('{0} token is {1}'.format(symbol['tsym'], symbol['token'])) 103 | 104 | elif prompt1 == 'd': 105 | exch = 'NSE' 106 | tsym = 'RELIANCE-EQ' 107 | ret = api.get_daily_price_series(exchange=exch, tradingsymbol=tsym, startdate=0) 108 | print(ret) 109 | 110 | elif prompt1 == 'p': 111 | exch = 'NSE' 112 | token = '22' 113 | ret = api.get_security_info(exchange=exch, token=token) 114 | print(ret) 115 | 116 | elif prompt1 == 'm': 117 | exch = 'NSE' 118 | token = '22' 119 | ret = api.get_quotes(exchange=exch, token=token) 120 | print(ret) 121 | elif prompt1 == 'o': 122 | exch = 'NFO' 123 | tsym = 'COFORGE30DEC21F' 124 | chain = api.get_option_chain(exchange=exch, tradingsymbol=tsym, strikeprice=3500, count=2) 125 | 126 | chainscrips = [] 127 | for scrip in chain['values']: 128 | scripdata = api.get_quotes(exchange=scrip['exch'], token=scrip['token']) 129 | chainscrips.append(scripdata) 130 | 131 | print(chainscrips) 132 | 133 | elif prompt1 == 's': 134 | if socket_opened == True: 135 | print('websocket already opened') 136 | continue 137 | ret = api.start_websocket(order_update_callback=event_handler_order_update, subscribe_callback=event_handler_quote_update, socket_open_callback=open_callback) 138 | print(ret) 139 | 140 | else: 141 | ret = api.logout() 142 | print(ret) 143 | print('Fin') #an answer that wouldn't be yes or no 144 | break 145 | 146 | -------------------------------------------------------------------------------- /example_orders.py: -------------------------------------------------------------------------------- 1 | from api_helper import NorenApiPy, get_time 2 | import logging 3 | import pandas as pd 4 | 5 | logging.basicConfig(level=logging.DEBUG) 6 | 7 | #flag to tell us if the websocket is open 8 | socket_opened = False 9 | 10 | #application callbacks 11 | def event_handler_order_update(message): 12 | print("order event: " + str(message)) 13 | 14 | 15 | def event_handler_quote_update(message): 16 | #e Exchange 17 | #tk Token 18 | #lp LTP 19 | #pc Percentage change 20 | #v volume 21 | #o Open price 22 | #h High price 23 | #l Low price 24 | #c Close price 25 | #ap Average trade price 26 | 27 | print("quote event: " + str(message)) 28 | 29 | 30 | def open_callback(): 31 | global socket_opened 32 | socket_opened = True 33 | print('app is connected') 34 | #api.subscribe_orders() 35 | api.subscribe('NSE|22') 36 | #api.subscribe(['NSE|22', 'BSE|522032']) 37 | 38 | #end of callbacks 39 | 40 | 41 | #start of our program 42 | api = NorenApiPy() 43 | 44 | #set token and user id 45 | #paste the token generated using the login flow described 46 | # in LOGIN FLOW of https://pi.flattrade.in/docs 47 | usersession='token here' 48 | userid = 'user id here' 49 | 50 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 51 | 52 | if ret != None: 53 | while True: 54 | print('p => place order') 55 | print('m => modify order') 56 | print('c => cancel order') 57 | print('y => order history') 58 | print('o => get order book') 59 | print('h => get holdings') 60 | print('l => get limits') 61 | print('k => get positions') 62 | print('d => get daily mtm') 63 | print('s => start_websocket') 64 | print('q => quit') 65 | 66 | prompt1=input('what shall we do? ').lower() 67 | 68 | if prompt1 == 'p': 69 | ret = api.place_order(buy_or_sell='B', product_type='C', 70 | exchange='NSE', tradingsymbol='INFY-EQ', 71 | quantity=1, discloseqty=0,price_type='LMT', price=1500.00, trigger_price=None, 72 | retention='DAY', remarks='my_order_001') 73 | print(ret) 74 | 75 | elif prompt1 == 'm': 76 | orderno=input('Enter orderno:').lower() 77 | ret = api.modify_order(exchange='NSE', tradingsymbol='INFY-EQ', orderno=orderno, 78 | newquantity=2, newprice_type='LMT', newprice=1505.00) 79 | print(ret) 80 | 81 | elif prompt1 == 'c': 82 | orderno=input('Enter orderno:').lower() 83 | ret = api.cancel_order(orderno=orderno) 84 | print(ret) 85 | 86 | elif prompt1 == 'y': 87 | orderno=input('Enter orderno:').lower() 88 | ret = api.single_order_history(orderno=orderno) 89 | print(ret) 90 | 91 | elif prompt1 == 'o': 92 | ret = api.get_order_book() 93 | print(ret) 94 | 95 | elif prompt1 == 'h': 96 | ret = api.get_holdings() 97 | print(ret) 98 | 99 | elif prompt1 == 'l': 100 | ret = api.get_limits() 101 | print(ret) 102 | 103 | elif prompt1 == 'k': 104 | ret = api.get_positions() 105 | print(ret) 106 | elif prompt1 == 'd': 107 | while True: 108 | ret = api.get_positions() 109 | mtm = 0 110 | pnl = 0 111 | for i in ret: 112 | mtm += float(i['urmtom']) 113 | pnl += float(i['rpnl']) 114 | day_m2m = mtm + pnl 115 | print(day_m2m) 116 | elif prompt1 == 's': 117 | if socket_opened == True: 118 | print('websocket already opened') 119 | continue 120 | ret = api.start_websocket(order_update_callback=event_handler_order_update, subscribe_callback=event_handler_quote_update, socket_open_callback=open_callback) 121 | print(ret) 122 | else: 123 | print('Fin') #an answer that wouldn't be yes or no 124 | break 125 | 126 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | websocket_client 3 | ./dist/NorenRestApi-0.0.29-py3-none-any.whl 4 | pandas 5 | pyyaml 6 | -------------------------------------------------------------------------------- /test_api.py: -------------------------------------------------------------------------------- 1 | from api_helper import NorenApiPy 2 | import logging 3 | 4 | #enable dbug to see request and responses 5 | logging.basicConfig(level=logging.DEBUG) 6 | 7 | #start of our program 8 | api = NorenApiPy() 9 | 10 | #set token and user id 11 | #paste the token generated using the login flow described 12 | # in LOGIN FLOW of https://pi.flattrade.in/docs 13 | usersession='token here' 14 | userid = 'user id here' 15 | 16 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 17 | 18 | ret = api.get_limits() 19 | 20 | print(ret) 21 | 22 | -------------------------------------------------------------------------------- /tests/option_chain.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flattrade/pythonAPI/ad69ba7f17a72828a84e67c210422248f07e7d12/tests/option_chain.xlsx -------------------------------------------------------------------------------- /tests/test_basket_order.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 3 | from api_helper import NorenApiPy, Order 4 | import logging 5 | import yaml 6 | import timeit 7 | 8 | #enable dbug to see request and responses 9 | logging.basicConfig(level=logging.DEBUG) 10 | 11 | #start of our program 12 | api = NorenApiPy() 13 | 14 | #set token and user id 15 | #paste the token generated using the login flow described 16 | # in LOGIN FLOW of https://pi.flattrade.in/docs 17 | usersession='token here' 18 | userid = 'user id here' 19 | 20 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 21 | 22 | orders = [] 23 | 24 | for index in range(1,5): 25 | order = Order() 26 | order.buy_or_sell = 'B' 27 | order.product_type='C' 28 | order.exchange='NSE' 29 | order.tradingsymbol='INFY-EQ' 30 | order.quantity=index 31 | order.discloseqty=0 32 | order.price_type='LMT' 33 | order.price=1500.00 34 | order.trigger_price=None 35 | order.retention='DAY' 36 | order.remarks='my_order_001' 37 | 38 | orders.append(order) 39 | 40 | starttime = timeit.default_timer() 41 | ret = api.place_basket(orders) 42 | print("The time difference is :", timeit.default_timer() - starttime) 43 | 44 | 45 | print(ret) 46 | -------------------------------------------------------------------------------- /tests/test_optionchain_excel.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 3 | from api_helper import NorenApiPy 4 | import signal 5 | import datetime 6 | import logging 7 | import time 8 | import yaml 9 | import pandas as pd 10 | import xlsxwriter 11 | import xlwings as xw 12 | 13 | #sample 14 | logging.basicConfig(level=logging.DEBUG) 15 | 16 | #flag to tell us if the websocket is open 17 | socket_opened = False 18 | 19 | #application callbacks 20 | def event_handler_order_update(message): 21 | print("order event: " + str(message)) 22 | 23 | 24 | SYMBOLDICT = {} 25 | def event_handler_quote_update(inmessage): 26 | global SYMBOLDICT 27 | #e Exchange 28 | #tk Token 29 | #lp LTP 30 | #pc Percentage change 31 | #v volume 32 | #o Open price 33 | #h High price 34 | #l Low price 35 | #c Close price 36 | #ap Average trade price 37 | 38 | fields = ['ts', 'lp', 'pc', 'c', 'o', 'h', 'l', 'v', 'ltq', 'ltp'] 39 | 40 | message = { field: inmessage[field] for field in set(fields) & set(inmessage.keys())} 41 | 42 | feedtime = int(inmessage['ft']) 43 | message['ft'] = str(datetime.datetime.fromtimestamp( feedtime )) 44 | 45 | print("quote event: {0}".format(time.strftime('%d-%m-%Y %H:%M:%S')) + str(inmessage)) 46 | 47 | print(message) 48 | 49 | key = inmessage['e'] + '|' + inmessage['tk'] 50 | 51 | if key in SYMBOLDICT: 52 | symbol_info = SYMBOLDICT[key] 53 | symbol_info.update(message) 54 | SYMBOLDICT[key] = symbol_info 55 | else: 56 | SYMBOLDICT[key] = message 57 | 58 | pd.DataFrame.from_dict(SYMBOLDICT).transpose() 59 | #print(SYMBOLDICT[key]) 60 | 61 | def open_callback(): 62 | global socket_opened 63 | socket_opened = True 64 | print('app is connected') 65 | 66 | api.subscribe(["NSE|22","NSE|13","BSE|522032"], feed_type='t') 67 | #api.subscribe(['NSE|22', 'BSE|522032']) 68 | 69 | #end of callbacks 70 | 71 | def get_time(time_string): 72 | data = time.strptime(time_string,'%d-%m-%Y %H:%M:%S') 73 | 74 | return time.mktime(data) 75 | 76 | class ProgramKilled(Exception): 77 | pass 78 | 79 | def signal_handler(signum, frame): 80 | raise ProgramKilled 81 | if __name__=="__main__": 82 | 83 | # Register our signal handler with `SIGINT`(CTRL + C) 84 | signal.signal(signal.SIGINT, signal_handler) 85 | # Register the exit handler with `SIGTSTP` (Ctrl + Z) 86 | signal.signal(signal.SIGTERM , signal_handler) 87 | 88 | #start of our program 89 | api = NorenApiPy() 90 | 91 | #yaml for parameters 92 | with open('..\\cred.yml') as f: 93 | cred = yaml.load(f, Loader=yaml.FullLoader) 94 | print(cred) 95 | 96 | 97 | excel_file = 'option_chain.xlsx' 98 | if os.path.exists(excel_file): 99 | workbook = xlsxwriter.Workbook(excel_file) 100 | workbook.add_worksheet('Live') 101 | workbook.close() 102 | 103 | wb1 = xw.Book(excel_file) 104 | sht = wb1.sheets('Live') 105 | 106 | ret = api.login(userid = cred['user'], password = cred['pwd'], twoFA=cred['factor2'], vendor_code=cred['vc'], api_secret=cred['apikey'], imei=cred['imei']) 107 | 108 | if ret != None: 109 | ret = api.start_websocket(order_update_callback=event_handler_order_update, subscribe_callback=event_handler_quote_update, socket_open_callback=open_callback) 110 | 111 | 112 | 113 | while True: 114 | try: 115 | if socket_opened == True: 116 | 117 | time.sleep(5) 118 | df = pd.DataFrame().from_dict(SYMBOLDICT).transpose() 119 | #print(df) 120 | try: 121 | sht.range('A1').value = df 122 | 123 | except Exception as e: 124 | print(e) 125 | continue 126 | else: 127 | continue 128 | 129 | except ProgramKilled: 130 | print("Program killed: running cleanup code") 131 | break -------------------------------------------------------------------------------- /tests/test_place_order.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 3 | from api_helper import NorenApiPy 4 | import logging 5 | 6 | #enable dbug to see request and responses 7 | logging.basicConfig(level=logging.DEBUG) 8 | 9 | #start of our program 10 | api = NorenApiPy() 11 | 12 | #set token and user id 13 | #paste the token generated using the login flow described 14 | # in LOGIN FLOW of https://pi.flattrade.in/docs 15 | usersession='token here' 16 | userid = 'user id here' 17 | 18 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 19 | 20 | ret = api.place_order(buy_or_sell='B', product_type='C', 21 | exchange='NSE', tradingsymbol='CANBK-EQ', 22 | quantity=1, discloseqty=0,price_type='SL-LMT', price=200.00, trigger_price=199.50, 23 | retention='DAY', remarks='my_order_001') 24 | 25 | print(ret) 26 | 27 | ## check sl modification 28 | orderno = ret['norenordno'] 29 | 30 | ret = api.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno, 31 | newquantity=2, newprice_type='SL-LMT', newprice=201.00, newtrigger_price=200.00) 32 | 33 | 34 | print(ret) 35 | 36 | ret = api.modify_order(exchange='NSE', tradingsymbol='CANBK-EQ', orderno=orderno, 37 | newquantity=2, newprice_type='MKT', newprice=0.00) 38 | 39 | print(ret) 40 | 41 | ret = api.single_order_history(orderno=orderno) 42 | 43 | for ord in ret: 44 | 45 | print(f"{ord['qty']} prc: {ord['prc']} trgprc: {ord['trgprc']} {ord['rpt']}") 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /tests/test_product_convertion.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 3 | from api_helper import NorenApiPy 4 | import logging 5 | 6 | #enable dbug to see request and responses 7 | logging.basicConfig(level=logging.DEBUG) 8 | 9 | #start of our program 10 | api = NorenApiPy() 11 | 12 | #set token and user id 13 | #paste the token generated using the login flow described 14 | # in LOGIN FLOW of https://pi.flattrade.in/docs 15 | usersession='token here' 16 | userid = 'user id here' 17 | 18 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 19 | 20 | ret = api.get_positions() 21 | 22 | p = ret[0] 23 | ret = api.position_product_conversion(p['exch'], p['tsym'], p['netqty'], 'I', p['prd'], 'B', 'DAY') 24 | 25 | print(ret) -------------------------------------------------------------------------------- /tests/test_tpseries.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 3 | from api_helper import NorenApiPy 4 | import logging 5 | import datetime 6 | import timeit 7 | 8 | #supress debug messages for prod/tests 9 | #logging.basicConfig(level=logging.DEBUG) 10 | logging.basicConfig(level=logging.INFO) 11 | 12 | 13 | #start of our program 14 | api = NorenApiPy() 15 | 16 | #set token and user id 17 | #paste the token generated using the login flow described 18 | # in LOGIN FLOW of https://pi.flattrade.in/docs 19 | usersession='token here' 20 | userid = 'user id here' 21 | 22 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 23 | 24 | if ret != None: 25 | lastBusDay = datetime.datetime.today() 26 | lastBusDay = lastBusDay.replace(hour=0, minute=0, second=0, microsecond=0) 27 | 28 | if datetime.date.weekday(lastBusDay) == 5: #if it's Saturday 29 | lastBusDay = lastBusDay - datetime.timedelta(days = 1) #then make it Friday 30 | elif datetime.date.weekday(lastBusDay) == 6: #if it's Sunday 31 | lastBusDay = lastBusDay - datetime.timedelta(days = 2); #then make it Friday 32 | 33 | print(lastBusDay.timestamp()) 34 | #lastBusDay = 1639098000 35 | 36 | starttime = timeit.default_timer() 37 | print("The start time is :",starttime) 38 | #get one day's data 39 | 40 | #ret = api.get_time_price_series(exchange='NSE', token='22', starttime=lastBusDay.timestamp()) 41 | ret = api.get_time_price_series(exchange='NSE', token='2885') 42 | print("The time difference is :", timeit.default_timer() - starttime) 43 | 44 | if ret != None: 45 | print(len(ret)) 46 | print(ret[0]) 47 | print(ret[-1]) -------------------------------------------------------------------------------- /tests/test_watchlist.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 3 | from api_helper import NorenApiPy 4 | import logging 5 | 6 | #supress debug messages for prod/tests 7 | logging.basicConfig(level=logging.DEBUG) 8 | 9 | #start of our program 10 | api = NorenApiPy() 11 | 12 | #set token and user id 13 | #paste the token generated using the login flow described 14 | # in LOGIN FLOW of https://pi.flattrade.in/docs 15 | usersession='token here' 16 | userid = 'user id here' 17 | 18 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 19 | 20 | if ret != None: 21 | wlnames = api.get_watch_list_names() 22 | 23 | for wl in wlnames['values']: 24 | print(80*'=') 25 | scrips = api.get_watch_list(wlname=wl) 26 | print(scrips) 27 | print(80*'=') 28 | 29 | wltest = wlnames['values'][0] 30 | ret = api.add_watch_list_scrip(wlname=wltest, instrument='NSE|22') 31 | wlscrips = api.get_watch_list(wlname=wltest) 32 | 33 | for scrip in wlscrips['values']: 34 | print(f"{scrip['exch']} - {scrip['token']} {scrip['tsym']}") 35 | 36 | print(80*'=') 37 | ret = api.delete_watch_list_scrip(wlname=wltest, instrument='NSE|22') 38 | wlscrips = api.get_watch_list(wlname=wltest) 39 | 40 | for scrip in wlscrips['values']: 41 | print(f"{scrip['exch']} - {scrip['token']} {scrip['tsym']}") 42 | -------------------------------------------------------------------------------- /tests/test_websocket_feed.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 3 | from api_helper import NorenApiPy 4 | import logging 5 | import time 6 | import pandas as pd 7 | 8 | #sample 9 | logging.basicConfig(level=logging.DEBUG) 10 | 11 | #flag to tell us if the websocket is open 12 | socket_opened = False 13 | 14 | #application callbacks 15 | def event_handler_order_update(message): 16 | print("order event: " + str(message)) 17 | 18 | 19 | SYMBOLDICT = {} 20 | def event_handler_quote_update(message): 21 | global SYMBOLDICT 22 | #e Exchange 23 | #tk Token 24 | #lp LTP 25 | #pc Percentage change 26 | #v volume 27 | #o Open price 28 | #h High price 29 | #l Low price 30 | #c Close price 31 | #ap Average trade price 32 | 33 | print("quote event: {0}".format(time.strftime('%d-%m-%Y %H:%M:%S')) + str(message)) 34 | 35 | key = message['e'] + '|' + message['tk'] 36 | 37 | if key in SYMBOLDICT: 38 | symbol_info = SYMBOLDICT[key] 39 | symbol_info.update(message) 40 | SYMBOLDICT[key] = symbol_info 41 | else: 42 | SYMBOLDICT[key] = message 43 | 44 | print(SYMBOLDICT[key]) 45 | 46 | def open_callback(): 47 | global socket_opened 48 | socket_opened = True 49 | print('app is connected') 50 | 51 | api.subscribe('NSE|11630', feed_type='d') 52 | #api.subscribe(['NSE|22', 'BSE|522032']) 53 | 54 | #end of callbacks 55 | 56 | def get_time(time_string): 57 | data = time.strptime(time_string,'%d-%m-%Y %H:%M:%S') 58 | 59 | return time.mktime(data) 60 | 61 | #start of our program 62 | api = NorenApiPy() 63 | 64 | #set token and user id 65 | #paste the token generated using the login flow described 66 | # in LOGIN FLOW of https://pi.flattrade.in/docs 67 | usersession='token here' 68 | userid = 'user id here' 69 | 70 | ret = api.set_session(userid= userid, password = '', usertoken= usersession) 71 | 72 | if ret != None: 73 | ret = api.start_websocket(order_update_callback=event_handler_order_update, subscribe_callback=event_handler_quote_update, socket_open_callback=open_callback) 74 | 75 | while True: 76 | if socket_opened == True: 77 | print('q => quit') 78 | prompt1=input('what shall we do? ').lower() 79 | 80 | print('Fin') #an answer that wouldn't be yes or no 81 | break 82 | 83 | else: 84 | continue 85 | 86 | -------------------------------------------------------------------------------- /token_generator/gettoken.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, jsonify,render_template_string 2 | import hashlib 3 | import requests 4 | 5 | # Configuration variables 6 | #============================ 7 | # Endpoint for the API 8 | EndPoint = "/" 9 | # Port number for the Flask application 10 | GPort = 8080 11 | # API key for authentication 12 | api_key = "4cfe6XXXXXXXXXXXXXXXXX0c3c" # YOUR_API_KEY 13 | # API secret for generating hash 14 | api_secret = "2025.f09ffXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX43777f2e3" #YOUR_SECRET_KEY 15 | #============================== 16 | # Display login URL 17 | print(f"{'*-'*50}\n Click the link below to authenticate:\n{'*-'*50}\n\nhttps://auth.flattrade.in/?app_key={api_key}\n\n{'*-'*50}") 18 | 19 | app = Flask(__name__) 20 | 21 | # Generate API hash 22 | def generate_hash(api_key, request_token, api_secret): 23 | return hashlib.sha256(f"{api_key}{request_token}{api_secret}".encode()).hexdigest() 24 | 25 | # API request function 26 | def get_api_token(payload): 27 | try: 28 | response = requests.post("https://authapi.flattrade.in/trade/apitoken", json=payload) 29 | return response.json() if response.status_code == 200 else {"error": f"HTTP {response.status_code}", "details": response.text} 30 | except requests.exceptions.RequestException as e: 31 | return {"error": "RequestException", "details": str(e)} 32 | 33 | # HTML template with escaped `{}` for CSS 34 | html_template = """ 35 |