-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathNoren.py
1642 lines (1274 loc) · 48.4 KB
/
Noren.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import requests
import threading
import websocket
import logging
from enum import Enum
import datetime
import hashlib
import time
import urllib
from time import sleep
from datetime import datetime as dt
logger = logging.getLogger(__name__)
class position:
prd: str
exch: str
instname: str
symname: str
exd: int
optt: str
strprc: float
buyqty: int
sellqty: int
netqty: int
def encode(self):
return self.__dict__
class ProductType(Enum):
Delivery = "C"
Intraday = "I"
Normal = "M"
CF = "M"
class FeedType(Enum):
TOUCHLINE = 1
SNAPQUOTE = 2
class PriceType(Enum):
Market = "MKT"
Limit = "LMT"
StopLossLimit = "SL-LMT"
StopLossMarket = "SL-MKT"
class BuyorSell(Enum):
Buy = "B"
Sell = "S"
class AlertType(Enum):
LTP_ABOVE = "LTP_A_O"
LTP_BELOW = "LTP_B_O"
LTP_OCO = "LMT_BOS_O"
def reportmsg(msg):
# print(msg)
logger.debug(msg)
def reporterror(msg):
# print(msg)
logger.error(msg)
def reportinfo(msg):
# print(msg)
logger.info(msg)
class NorenApi(object):
TRANSACTION_TYPE_SELL = "S"
TRANSACTION_TYPE_BUY = "B"
PRODUCT_TYPE_INTRADAY = "I"
PRODUCT_TYPE_DELIVERY = "C"
PRODUCT_TYPE_NORMAL = "M"
PRICE_TYPE_MARKET = "MKT"
PRICE_TYPE_LIMIT = "LMT"
PRICE_TYPE_STOPLOSS_LIMIT = "SL-LMT"
PRICE_TYPE_STOPLOSS_MARKET = "SL-MKT"
ALERT_TYPE_ABOVE = "LTP_A_O"
ALERT_TYPE_BELOW = "LTP_B_O"
ALERT_TYPE_OCO = "LMT_BOS_O"
FEED_TYPE_TOUCHLINE = 1
FEED_TYPE_SNAPSHOT = 2
__service_config = {
"host": "http://wsapihost/",
"routes": {
"authorize": "/QuickAuth",
"logout": "/Logout",
"forgot_password": "/ForgotPassword",
"change_password": "/Changepwd",
"watchlist_names": "/MWList",
"watchlist": "/MarketWatch",
"watchlist_add": "/AddMultiScripsToMW",
"watchlist_delete": "/DeleteMultiMWScrips",
"placeorder": "/PlaceOrder",
"modifyorder": "/ModifyOrder",
"cancelorder": "/CancelOrder",
"exitorder": "/ExitSNOOrder",
"product_conversion": "/ProductConversion",
"orderbook": "/OrderBook",
"tradebook": "/TradeBook",
"singleorderhistory": "/SingleOrdHist",
"searchscrip": "/SearchScrip",
"TPSeries": "/TPSeries",
"optionchain": "/GetOptionChain",
"holdings": "/Holdings",
"limits": "/Limits",
"positions": "/PositionBook",
"scripinfo": "/GetSecurityInfo",
"getquotes": "/GetQuotes",
"span_calculator": "/SpanCalc",
"option_greek": "/GetOptionGreek",
"get_daily_price_series": "/EODChartData",
"placegtt": "/PlaceGTTOrder",
"gtt": "/GetPendingGTTOrder",
"enabledgtt": "/GetEnabledGTTs",
"cancelgtt": "/CancelGTTOrder",
"ocogtt": "/PlaceOCOOrder",
"modifyoco": "/ModifyOCOOrder",
},
"websocket_endpoint": "wss://wsendpoint/",
# 'eoddata_endpoint' : 'http://eodhost/'
}
def __init__(self, host, websocket):
self.__service_config["host"] = host
self.__service_config["websocket_endpoint"] = websocket
# self.__service_config['eoddata_endpoint'] = eodhost
self.__websocket = None
self.__websocket_connected = False
self.__ws_mutex = threading.Lock()
self.__on_error = None
self.__on_disconnect = None
self.__on_open = None
self.__subscribe_callback = None
self.__order_update_callback = None
self.__subscribers = {}
self.__market_status_messages = []
self.__exchange_messages = []
def __ws_run_forever(self):
while self.__stop_event.is_set() == False:
try:
self.__websocket.run_forever(ping_interval=3, ping_payload='{"t":"h"}')
except Exception as e:
logger.warning(f"websocket run forever ended in exception, {e}")
sleep(0.1) # Sleep for 100ms between reconnection.
def __ws_send(self, *args, **kwargs):
while self.__websocket_connected == False:
# sleep for 50ms if websocket is not connected, wait for reconnection
sleep(0.05)
with self.__ws_mutex:
ret = self.__websocket.send(*args, **kwargs)
return ret
def __on_close_callback(self, wsapp, close_status_code, close_msg):
reportmsg(close_status_code)
reportmsg(wsapp)
self.__websocket_connected = False
if self.__on_disconnect:
self.__on_disconnect()
def __on_open_callback(self, ws=None):
self.__websocket_connected = True
# prepare the data
values = {"t": "c"}
values["uid"] = self.__username
values["actid"] = self.__username
values["susertoken"] = self.__susertoken
values["source"] = "API"
payload = json.dumps(values)
reportmsg(payload)
self.__ws_send(payload)
# self.__resubscribe()
def __on_error_callback(self, ws=None, error=None):
if (
type(ws) is not websocket.WebSocketApp
): # This workaround is to solve the websocket_client's compatiblity issue of older versions. ie.0.40.0 which is used in upstox. Now this will work in both 0.40.0 & newer version of websocket_client
error = ws
if self.__on_error:
self.__on_error(error)
def __on_data_callback(
self, ws=None, message=None, data_type=None, continue_flag=None
):
# print(ws)
# print(message)
# print(data_type)
# print(continue_flag)
res = json.loads(message)
if self.__subscribe_callback is not None:
if res["t"] == "tk" or res["t"] == "tf":
self.__subscribe_callback(res)
return
if res["t"] == "dk" or res["t"] == "df":
self.__subscribe_callback(res)
return
if self.__on_error is not None:
if res["t"] == "ck" and res["s"] != "OK":
self.__on_error(res)
return
if self.__order_update_callback is not None:
if res["t"] == "om":
self.__order_update_callback(res)
return
if self.__on_open:
if res["t"] == "ck" and res["s"] == "OK":
self.__on_open()
return
def start_websocket(
self,
subscribe_callback=None,
order_update_callback=None,
socket_open_callback=None,
socket_close_callback=None,
socket_error_callback=None,
):
"""Start a websocket connection for getting live data"""
self.__on_open = socket_open_callback
self.__on_disconnect = socket_close_callback
self.__on_error = socket_error_callback
self.__subscribe_callback = subscribe_callback
self.__order_update_callback = order_update_callback
self.__stop_event = threading.Event()
url = self.__service_config["websocket_endpoint"].format(
access_token=self.__susertoken
)
#print(url)
reportmsg("connecting to {}".format(url))
self.__websocket = websocket.WebSocketApp(
url,
on_data=self.__on_data_callback,
on_error=self.__on_error_callback,
on_close=self.__on_close_callback,
on_open=self.__on_open_callback,
)
# th = threading.Thread(target=self.__send_heartbeat)
# th.daemon = True
# th.start()
# if run_in_background is True:
self.__ws_thread = threading.Thread(target=self.__ws_run_forever)
self.__ws_thread.daemon = True
self.__ws_thread.start()
def close_websocket(self):
if self.__websocket_connected == False:
return
self.__stop_event.set()
self.__websocket_connected = False
self.__websocket.close()
self.__ws_thread.join()
def login(self, userid, password, twoFA, vendor_code, api_secret, imei):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['authorize']}"
reportmsg(url)
# Convert to SHA 256 for password and app key
pwd = hashlib.sha256(password.encode("utf-8")).hexdigest()
u_app_key = "{0}|{1}".format(userid, api_secret)
app_key = hashlib.sha256(u_app_key.encode("utf-8")).hexdigest()
# prepare the data
values = {"source": "API", "apkversion": "1.0.0"}
values["uid"] = userid
values["pwd"] = pwd
values["factor2"] = twoFA
values["vc"] = vendor_code
values["appkey"] = app_key
values["imei"] = imei
payload = "jData=" + json.dumps(values)
reportmsg("Req:" + payload)
res = requests.post(url, data=payload)
reportmsg("Reply:" + res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
self.__username = userid
self.__accountid = userid
self.__password = password
self.__susertoken = resDict["susertoken"]
# reportmsg(self.__susertoken)
return resDict
def set_session(self, userid, password, usertoken):
self.__username = userid
self.__accountid = userid
self.__password = password
self.__susertoken = usertoken
reportmsg(f"{userid} session set to : {self.__susertoken}")
return True
def forgot_password(self, userid, pan, dob):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['forgot_password']}"
reportmsg(url)
# prepare the data
values = {"source": "API"}
values["uid"] = userid
values["pan"] = pan
values["dob"] = dob
payload = "jData=" + json.dumps(values)
reportmsg("Req:" + payload)
res = requests.post(url, data=payload)
reportmsg("Reply:" + res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def logout(self):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['logout']}"
reportmsg(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
self.__username = None
self.__accountid = None
self.__password = None
self.__susertoken = None
return resDict
def subscribe(self, instrument, feed_type=FeedType.SNAPQUOTE):
values = {}
if feed_type == FeedType.TOUCHLINE:
values["t"] = "t"
elif feed_type == FeedType.SNAPQUOTE:
values["t"] = "d"
else:
values["t"] = str(feed_type)
if type(instrument) == list:
values["k"] = "#".join(instrument)
else:
values["k"] = instrument
data = json.dumps(values)
# print(data)
self.__ws_send(data)
def unsubscribe(self, instrument, feed_type=FeedType.TOUCHLINE):
values = {}
if feed_type == FeedType.TOUCHLINE:
values["t"] = "u"
elif feed_type == FeedType.SNAPQUOTE:
values["t"] = "ud"
if type(instrument) == list:
values["k"] = "#".join(instrument)
else:
values["k"] = instrument
data = json.dumps(values)
# print(data)
self.__ws_send(data)
def subscribe_orders(self):
values = {"t": "o"}
values["actid"] = self.__accountid
data = json.dumps(values)
reportmsg(data)
self.__ws_send(data)
def get_watch_list_names(self):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['watchlist_names']}"
reportmsg(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def get_watch_list(self, wlname):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['watchlist']}"
reportmsg(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["wlname"] = wlname
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def add_watch_list_scrip(self, wlname, instrument):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['watchlist_add']}"
reportmsg(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["wlname"] = wlname
if type(instrument) == list:
values["scrips"] = "#".join(instrument)
else:
values["scrips"] = instrument
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def delete_watch_list_scrip(self, wlname, instrument):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['watchlist_delete']}"
reportmsg(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["wlname"] = wlname
if type(instrument) == list:
values["scrips"] = "#".join(instrument)
else:
values["scrips"] = instrument
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def place_order(
self,
buy_or_sell,
product_type,
exchange,
tradingsymbol,
quantity,
discloseqty,
price_type,
price=0.0,
trigger_price=None,
retention="DAY",
amo="NO",
remarks=None,
bookloss_price=0.0,
bookprofit_price=0.0,
trail_price=0.0,
):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['placeorder']}"
reportmsg(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["actid"] = self.__accountid
values["trantype"] = buy_or_sell
values["prd"] = product_type
values["exch"] = exchange
values["tsym"] = urllib.parse.quote_plus(tradingsymbol)
values["qty"] = str(quantity)
values["dscqty"] = str(discloseqty)
values["prctyp"] = price_type
values["prc"] = str(price)
values["trgprc"] = str(trigger_price)
values["ret"] = retention
values["remarks"] = remarks
values["amo"] = amo
# if cover order or high leverage order
if product_type == "H":
values["blprc"] = str(bookloss_price)
# trailing price
if trail_price != 0.0:
values["trailprc"] = str(trail_price)
# bracket order
if product_type == "B":
values["blprc"] = str(bookloss_price)
values["bpprc"] = str(bookprofit_price)
# trailing price
if trail_price != 0.0:
values["trailprc"] = str(trail_price)
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def modify_order(
self,
orderno,
exchange,
tradingsymbol,
newquantity,
newprice_type,
newprice=0.0,
newtrigger_price=None,
bookloss_price=0.0,
bookprofit_price=0.0,
trail_price=0.0,
):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['modifyorder']}"
print(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["actid"] = self.__accountid
values["norenordno"] = str(orderno)
values["exch"] = exchange
values["tsym"] = urllib.parse.quote_plus(tradingsymbol)
values["qty"] = str(newquantity)
values["prctyp"] = newprice_type
values["prc"] = str(newprice)
if (newprice_type == "SL-LMT") or (newprice_type == "SL-MKT"):
if newtrigger_price != None:
values["trgprc"] = str(newtrigger_price)
else:
reporterror("trigger price is missing")
return None
# if cover order or high leverage order
if bookloss_price != 0.0:
values["blprc"] = str(bookloss_price)
# trailing price
if trail_price != 0.0:
values["trailprc"] = str(trail_price)
# book profit of bracket order
if bookprofit_price != 0.0:
values["bpprc"] = str(bookprofit_price)
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def cancel_order(self, orderno):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['cancelorder']}"
print(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["norenordno"] = str(orderno)
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
print(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def exit_order(self, orderno, product_type):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['exitorder']}"
print(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["norenordno"] = orderno
values["prd"] = product_type
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def position_product_conversion(
self,
exchange,
tradingsymbol,
quantity,
new_product_type,
previous_product_type,
buy_or_sell,
day_or_cf,
):
"""
Coverts a day or carryforward position from one product to another.
"""
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['product_conversion']}"
print(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["actid"] = self.__accountid
values["exch"] = exchange
values["tsym"] = urllib.parse.quote_plus(tradingsymbol)
values["qty"] = str(quantity)
values["prd"] = new_product_type
values["prevprd"] = previous_product_type
values["trantype"] = buy_or_sell
values["postype"] = day_or_cf
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def single_order_history(self, orderno):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['singleorderhistory']}"
#print(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["norenordno"] = orderno
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
# error is a json with stat and msg wchih we printed earlier.
if type(resDict) != list:
return None
return resDict
def get_order_book(self):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['orderbook']}"
reportmsg(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
# error is a json with stat and msg wchih we printed earlier.
if type(resDict) != list:
return None
return resDict
def get_trade_book(self):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['tradebook']}"
reportmsg(url)
# prepare the data
values = {"ordersource": "API"}
values["uid"] = self.__username
values["actid"] = self.__accountid
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
# error is a json with stat and msg wchih we printed earlier.
if type(resDict) != list:
return None
return resDict
def searchscrip(self, exchange, searchtext):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['searchscrip']}"
reportmsg(url)
if searchtext == None:
reporterror("search text cannot be null")
return None
values = {}
values["uid"] = self.__username
values["exch"] = exchange
values["stext"] = urllib.parse.quote_plus(searchtext)
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def get_option_chain(self, exchange, tradingsymbol, strikeprice, count=2):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['optionchain']}"
reportmsg(url)
values = {}
values["uid"] = self.__username
values["exch"] = exchange
values["tsym"] = urllib.parse.quote_plus(tradingsymbol)
values["strprc"] = str(strikeprice)
values["cnt"] = str(count)
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def get_security_info(self, exchange, token):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['scripinfo']}"
reportmsg(url)
values = {}
values["uid"] = self.__username
values["exch"] = exchange
values["token"] = token
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def get_quotes(self, exchange, token):
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['getquotes']}"
reportmsg(url)
values = {}
values["uid"] = self.__username
values["exch"] = exchange
values["token"] = token
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
if resDict["stat"] != "Ok":
return None
return resDict
def get_time_price_series(
self, exchange, token, starttime=None, endtime=None, interval=None
):
"""
gets the chart data
interval possible values 1, 3, 5 , 10, 15, 30, 60, 120, 240
"""
config = NorenApi.__service_config
# prepare the uri
url = f"{config['host']}{config['routes']['TPSeries']}"
reportmsg(url)
# prepare the data
if starttime == None:
timestring = time.strftime("%d-%m-%Y") + " 00:00:00"
timeobj = time.strptime(timestring, "%d-%m-%Y %H:%M:%S")
starttime = time.mktime(timeobj)
#
values = {"ordersource": "API"}
values["uid"] = self.__username
values["exch"] = exchange
values["token"] = token
values["st"] = str(starttime)
if endtime != None:
values["et"] = str(endtime)
if interval != None:
values["intrv"] = str(interval)
payload = "jData=" + json.dumps(values) + f"&jKey={self.__susertoken}"
reportmsg(payload)
res = requests.post(url, data=payload)
reportmsg(res.text)
resDict = json.loads(res.text)
# error is a json with stat and msg wchih we printed earlier.
if type(resDict) != list:
return None
return resDict
def get_daily_price_series(
self, exchange, tradingsymbol, startdate=None, enddate=None
):
config = NorenApi.__service_config