forked from suresh-n/richdotin
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Richdotin_Scalper_App.py
1514 lines (1310 loc) · 44.2 KB
/
Richdotin_Scalper_App.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
from time import sleep
from tkinter import *
import tkinter as tk
from tkinter import ttk
import threading, json, math, sqlite3, logging, os, csv, time
from datetime import datetime, timedelta
from datetime import datetime as dt
from datetime import timedelta as td
from time import strftime
from api_helper import ShoonyaApiPy
import pandas as pd
from tkinter import simpledialog, filedialog, messagebox
import pyotp
import configparser
from pathlib import Path
config = configparser.ConfigParser()
config.read("config.ini")
authotp = pyotp.TOTP(
config.get("CRED", "authenticator")
).now() # copy the authenticator code here in quote.
start = datetime.now()
print(start)
logfile = "./logs/" + dt.now().strftime("%d-%m-%Y_%H%M%S") + "_Scalper_App.log"
print(logfile)
logging.basicConfig(
format="%(asctime)s %(levelname)-8s %(message)s",
level=logging.INFO,
filename=logfile,
filemode="w",
datefmt="%Y-%m-%d %H:%M:%S",
)
def log(msg, *args):
logging.info(msg, *args)
# print(msg, *args)
def errorlog(msg1, *args):
logging.error(msg1, *args)
# print(msg1,*args)
# enable dbug to see request and responses
# logging.basicConfig(level=logging.DEBUG)
api = ShoonyaApiPy()
call_strike_ltp = 0.0
put_strike_ltp = 0.0
token_ce = 0
token_pe = 0
bn_nifty_lp = 0.0
nifty_lp = 0.0
##Style
lbl_fonts = ("Helvatical bold", 10)
btn_fonts = ("Helvatical bold", 10)
btn_fg = "White"
btn_bg = "Black"
lbl_fg = "white"
lbl_bg = "#ffffe6"
m2m_fonts = ("Helvatical bold", 10)
time_font = ("Helvatical bold", 10, "bold")
time_bg = "Green"
time_fg = "White"
top_lbl_fg = "Black"
top_lbl_bg = "Grey"
top_lbl_font = ("Helvatical bold", 10)
welcome_font = ("Helvatical bold", 10)
welcome_bg = "White"
welcome_fg = "Green"
refresh_font = ("Helvatical bold", 10)
refresh_bg = "White"
refresh_fg = "Green"
def write_test():
get_user = get_username.get()
get_password = get_pwd.get()
get_Auth_2_1 = get_Auth.get()
get_vc_1 = get_vc.get()
get_apikey_1 = get_apikey.get()
config.set("CRED", "user", get_user)
config.set("CRED", "pwd", get_password)
config.set("CRED", "authenticator", get_Auth_2_1)
config.set("CRED", "vc", get_vc_1)
config.set("CRED", "app_key", get_apikey_1)
with open("config.ini", "w") as configfile:
config.write(configfile)
log(f"The test.ini file filled with the Credential details")
top.destroy()
def Logout():
global ret, api, display_call_ltp, display_put_ltp
try:
api.unsubscribe(["NSE|26009", "NSE|26000"])
api.unsubscribe([f"NFO|{token_ce}", f"NFO|{token_pe}"])
print("closing websocket")
api.close_websocket()
print("Logging out from API")
api.logout()
username = ret["uname"]
username = "Bye Bye" + " " + str(username[:-10]) + "!"
welcome_lbl["text"] = username
display_call_ltp["text"] = 0.0
display_put_ltp["text"] = 0.0
Expiry_day_combo_box1.current(0)
index_combo1box.current(0)
Strike_combo_box1.current(0)
qty_combo_box1.current(0)
nifty_price_lbl["text"] = 0.0
bnf_price_lbl["text"] = 0.0
log(f"Sucessfully Logged out from the account {username}")
except Exception as e:
errorlog(f"an exception occurred :: {e} API ERROR")
def Login(): # Login function get the api login + username and cash margin
global ret
global get_username, get_pwd, get_Auth, get_vc, get_apikey
global top
if not config.get("CRED", "user"):
log("CRED Variable is empty so getting variable")
top = Toplevel(root)
top.geometry("310x270")
top.title("Richdotin Scalping App")
top.config(background="Grey")
lbl_username = Label(
top, text="User:", fg=top_lbl_fg, font=top_lbl_font, bg=top_lbl_bg
)
lbl_username.place(x=30, y=20)
lbl_password = Label(
top, text="Password:", fg=top_lbl_fg, font=top_lbl_font, bg=top_lbl_bg
)
lbl_password.place(x=30, y=60)
lbl_Auth = Label(
top, text="Authenticator:", fg=top_lbl_fg, font=top_lbl_font, bg=top_lbl_bg
)
lbl_Auth.place(x=30, y=100)
lbl_vc = Label(top, text="VC:", fg=top_lbl_fg, font=top_lbl_font, bg=top_lbl_bg)
lbl_vc.place(x=30, y=140)
lbl_api_key = Label(
top, text="api_key:", fg=top_lbl_fg, font=top_lbl_font, bg=top_lbl_bg
)
lbl_api_key.place(x=30, y=180)
get_username = Entry(top, width=15, borderwidth=0)
get_username.place(x=130, y=20)
get_pwd = Entry(top, width=15, show="*", borderwidth=0)
get_pwd.place(x=130, y=60)
get_Auth = Entry(top, width=20, borderwidth=0)
get_Auth.place(x=130, y=100)
get_vc = Entry(top, width=15, borderwidth=0)
get_vc.place(x=130, y=140)
get_apikey = Entry(top, width=20, show="*", borderwidth=0)
get_apikey.place(x=130, y=180)
submit_btn1 = Button(
top,
text="Submit",
font=btn_fonts,
fg=btn_fg,
bg=btn_bg,
bd=0,
activeforeground="Green",
command=write_test,
)
submit_btn1.place(x=130, y=220)
else:
try:
# ret = api.login(userid = config.user, password = config.pwd, twoFA=config.factor2, vendor_code=config.vc, api_secret=config.app_key, imei=config.imei)
ret = api.login(
userid=config.get("CRED", "user"),
password=config.get("CRED", "pwd"),
twoFA=authotp,
vendor_code=config.get("CRED", "vc"),
api_secret=config.get("CRED", "app_key"),
imei=config.get("CRED", "imei"),
)
usersession = ret["susertoken"]
username = ret["uname"]
log(f"Sucessfully Login to the account {username}")
username = (
"Welcome" + " " + str(username[:-10]) + "!"
) # Just for hiding full name
welcome_lbl["text"] = username
setupwebsocket()
sleep(0.5)
api.subscribe(["NSE|26009", "NSE|26000"])
except Exception as e:
errorlog(f"an exception occurred :: {e} API ERROR")
feed_opened = False
live_data = {}
SYMBOLDICT = {}
def event_handler_quote_update(inmessage):
global live_data, token_ce, token_pe, bn_nifty_lp, nifty_lp
if inmessage["tk"] == str(26000):
nifty_price_lbl["text"] = inmessage["lp"]
print(inmessage["tk"], inmessage["lp"], inmessage["ts"])
if inmessage["tk"] == str(26009):
bnf_price_lbl["text"] = inmessage["lp"]
print(inmessage["tk"], inmessage["lp"], inmessage["ts"])
if inmessage["tk"] == str(token_ce):
display_call_ltp["text"] = inmessage["lp"]
print(inmessage["tk"], inmessage["lp"], inmessage["ts"])
if inmessage["tk"] == str(token_pe):
display_put_ltp["text"] = inmessage["lp"]
print(inmessage["tk"], inmessage["lp"], inmessage["ts"])
global SYMBOLDICT
# e Exchange
# tk Token
# lp LTP
# pc Percentage change
# v volume
# o Open price
# h High price
# l Low price
# c Close price
# ap Average trade price
fields = [
"ts",
"lp",
"pc",
"c",
"o",
"h",
"l",
"v",
"ltq",
"ltp",
"bp1",
"sp1",
"ap",
"oi",
"ap",
"poi",
"toi",
]
message = {field: inmessage[field] for field in set(fields) & set(inmessage.keys())}
# print(message)
key = inmessage["e"] + "|" + inmessage["tk"]
if key in SYMBOLDICT:
symbol_info = SYMBOLDICT[key]
symbol_info.update(message)
SYMBOLDICT[key] = symbol_info
live_data[key] = symbol_info
else:
SYMBOLDICT[key] = message
live_data[key] = message
def event_handler_order_update(tick_data):
# print(f"Order update {tick_data}")
print("order update")
def open_callback():
global feed_opened
feed_opened = True
def setupwebsocket():
global feed_opened
api.start_websocket(
order_update_callback=event_handler_order_update,
subscribe_callback=event_handler_quote_update,
socket_open_callback=open_callback,
)
print("websocket connected")
sleep(1)
while feed_opened == False:
print(feed_opened)
pass
return True
def Refresh(): # Function get the BN last price so the code can calculate the Strikes
global api
pos_data = api.get_positions()
if pos_data == None:
log(f"No Positions Data available for today")
else:
mtm = 0
pnl = 0
for i in pos_data:
mtm += float(i["urmtom"])
pnl += float(i["rpnl"])
day_m2m = mtm + pnl
day_m2m_total = "{:.2f}".format(day_m2m)
m2m["text"] = day_m2m_total
if day_m2m > 0:
m2m.config(fg="Green")
else:
m2m.config(fg="Red")
limit = api.get_limits()
try:
marginused = float((limit["marginused"]))
except KeyError:
marginused = 0
margin_available = round(((float((limit["cash"]))) - marginused), 2)
margin_available_1lotbn = margin_available / 25
margin_available_1lotnf = margin_available / 50
print(
"With the available fund you can get one lot of BN with price:",
margin_available_1lotbn,
)
print(
"With the available fund you can get one lot of NF with price:",
margin_available_1lotnf,
)
available_margin_price["text"] = margin_available
log(f"BN last price updated {bn_nifty_lp}")
log(f"The fund balance updated {margin_available}")
try:
show_SL_order()
log(f"checked if there is any SL order")
except Exception as e:
errorlog(f"an exception occurred :: {e}")
root.update()
stopPos = False
stopStrat = False
def startThread(thread): # Start the Thread (Thread Manager)
match thread:
case 0:
t1 = threading.Thread(target=Login)
t1.start()
case 1:
t1 = threading.Thread(target=trade_book)
t1.start()
case 2:
t1 = threading.Thread(target=placeCallOrder())
t1.start()
case 3:
t1 = threading.Thread(target=Refresh)
t1.start()
case 4:
t1 = threading.Thread(target=placePutOrder())
t1.start()
case 5:
t1 = threading.Thread(target=squareoff)
t1.start()
case 6:
t1 = threading.Thread(target=pos, daemon="true")
t1.start()
case 7:
t1 = threading.Thread(target=Logout)
t1.start()
def stopThread(thread): # Stop the Thread (Thread Manager)
global stopPos, stopStrat
match thread:
case 0:
stopPos = True
case 1:
stopStrat = True
def check_order_stat(): # Check the order details to place the SL order
global order_status
try:
ret = api.get_order_book()
# print(ret)
ret = pd.DataFrame(ret)
row = 0
for row in ret.to_dict("records"):
if order_no == row["norenordno"]:
order_status = row["status"]
print("orderstatus:", order_status)
log(
f"[OrderStatus]Checking order status for order number {order_no} and the order status is {order_status}"
)
# print(row["status"],row["tsym"])
# #order status to displayed in GUI
ord_stat_entry.delete(0, "end")
ord_stat_entry.insert(0, order_status)
except Exception as e:
errorlog(f"an exception occurred :: {e}")
Symbol_Name = []
order_no = []
def placeCallOrder(): # Place the Call option order
global order_no
global price_ltp
try:
# global target_limit
price_ltp = api.get_quotes(exchange="NFO", token=token_ce)
price_ltp = price_ltp["bp1"]
# # Place call order
order_no = api.place_order(
buy_or_sell="B",
product_type="I",
exchange="NFO",
tradingsymbol=tsym_ce,
quantity=qty,
discloseqty=0,
price_type="LMT",
price=price_ltp,
trigger_price=None,
retention="DAY",
remarks="my_order_001",
)
order_no = order_no["norenordno"]
log(
f"[OrderPlaced] Placed call { tsym_ce } order at {price_ltp} x Quantity {qty} and order number is {order_no}"
)
check_order_stat()
if order_status == "OPEN":
cancel_ord = api.cancel_order(orderno=order_no)
check_order_stat()
else:
pass
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def placePutOrder(): # Place the Put option order
global order_no
global price_ltp
try:
price_ltp = api.get_quotes(exchange="NFO", token=token_pe)
price_ltp = price_ltp["bp1"]
order_no = api.place_order(
buy_or_sell="B",
product_type="I",
exchange="NFO",
tradingsymbol=tsym_pe,
quantity=qty,
discloseqty=0,
price_type="LMT",
price=price_ltp,
trigger_price=None,
retention="DAY",
remarks="my_order_001",
)
order_no = order_no["norenordno"]
log(
f"[OrderPlaced] Placed Put { tsym_pe } order at {price_ltp} x Quantity {qty} and order number is {order_no}"
)
check_order_stat()
if order_status == "OPEN":
cancel_ord = api.cancel_order(orderno=order_no)
check_order_stat()
else:
pass
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def destroy_sl_show():
sl_symbol_lbl1.destroy()
sl_price_lbl1.destroy()
sl_qty_lbl1.destroy()
sl_status_lbl1.destroy()
def cancel_sl_order():
try:
cancel_sl_order = api.cancel_order(orderno=sl_order_number)
log(f"cancelled SL order {sl_order_number}, before squre off the position")
destroy_sl_show()
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def squareoff(): # squareoff all the open order manually
try:
cancel_sl_order()
log(f"square off the open postions")
squareoff_Pos = api.get_positions()
squareoff_Pos = pd.DataFrame(squareoff_Pos)
row = 0
for row in squareoff_Pos.to_dict("records"):
if int(row["netqty"]) > 0:
print(row["tsym"])
api.place_order(
buy_or_sell="S",
product_type="I",
exchange=exch,
tradingsymbol=row["tsym"],
quantity=int(row["netqty"]),
discloseqty=0,
price_type="MKT",
price=0,
trigger_price=None,
retention="DAY",
remarks="my_order_001",
)
except Exception as e:
errorlog(f"an exception occurred :: {e}")
stopPos = False
def do_popmenu(event):
try:
right_menu.tk_popup(event.x_root, event.y_root)
finally:
right_menu.grab_release
def manual_exit():
try:
cancel_sl_order()
destroy_sl_show()
except Exception as e:
errorlog(f"an exception occurred :: {e}")
try:
api.place_order(
buy_or_sell="S",
product_type="I",
exchange=exch,
tradingsymbol=symbol,
quantity=netqty,
discloseqty=0,
price_type="MKT",
price=0,
trigger_price=None,
retention="DAY",
remarks="my_order_001",
)
log(f"The open position exited,{symbol} {netqty} at market price")
# destroy_pos_lbl()
pos()
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def do_popmenu1(event):
try:
right_menu1.tk_popup(event.x_root, event.y_root)
finally:
right_menu1.grab_release
def popup_sl():
global sl_manual, sl_trigger
try:
manual_sl = simpledialog.askinteger(title="Add SL", prompt="SL")
avg_round = round(float(Avg))
sl_manual = float(avg_round) - float(manual_sl)
sl_trigger = float(sl_manual) + float(1.0)
log(f"manual SL is:{sl_manual}")
place_manual_SL()
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def show_SL_order():
global right_menu1, sl_symbol_lbl1, sl_price_lbl1, sl_qty_lbl1, sl_status_lbl1, sl_order_number
try:
trail_sl = api.get_order_book()
trail_sl = pd.DataFrame(trail_sl)
row = 0
for row in trail_sl.to_dict("records"):
if row["status"] == "TRIGGER_PENDING":
sl_order_number = row["norenordno"]
sl_symbol_lbl1 = Label(
root,
text=row["tsym"],
width=25,
bg="cornsilk3",
fg="black",
font=("Arial Black", 10),
)
sl_symbol_lbl1.place(x=10, y=310)
sl_price_lbl1 = Label(
root,
text=row["prc"],
width=10,
bg="cornsilk3",
fg="black",
font=("Arial Black", 10),
)
sl_price_lbl1.place(x=220, y=310)
sl_qty_lbl1 = Label(
root,
text=row["qty"],
width=10,
bg="cornsilk3",
fg="black",
font=("Arial Black", 10),
)
sl_qty_lbl1.place(x=310, y=310)
sl_status_lbl1 = Label(
root,
text=row["status"],
width=15,
bg="cornsilk3",
fg="black",
font=("Arial Black", 10),
)
sl_status_lbl1.place(x=400, y=310)
right_menu1 = Menu(root, tearoff=0)
right_menu1.config(
background="black", fg="white", activeforeground="Green"
)
right_menu1.add_command(
label="Trail SL", command=lambda: trail_sl_pop()
)
right_menu1.add_command(
label="Calcel Order", command=lambda: cancel_sl_order()
)
sl_symbol_lbl1.bind("<Button-3>", do_popmenu1)
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def place_manual_SL():
global sl_order_number
try:
sl_order_number = api.place_order(
buy_or_sell="S",
product_type="I",
exchange=exch,
tradingsymbol=symbol,
quantity=netqty,
discloseqty=0,
price_type="SL-LMT",
price=sl_manual,
trigger_price=sl_trigger,
retention="DAY",
remarks="my_order_001",
)
sl_order_number = sl_order_number["norenordno"]
log(f"Placed manual SL order: the order number is {sl_order_number}")
show_SL_order()
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def trail_sl_pop():
global trail_sl_manual, trail_sl_trigger
get_live_ltp = api.get_quotes(exchange=exch, token=symbol)
get_live_ltp = get_live_ltp["lp"]
try:
trail_manual_sl = simpledialog.askinteger(title="Add Trail SL", prompt="SL")
avg_round = round(float(get_live_ltp))
trail_sl_manual = float(avg_round) - float(trail_manual_sl)
trail_sl_trigger = float(trail_sl_manual) + float(2.0)
log(f"trail manual SL is:{trail_sl_manual}")
modify_sl_order()
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def modify_sl_order():
try:
trail_sl = api.get_order_book()
trail_sl = pd.DataFrame(trail_sl)
row = 0
for row in trail_sl.to_dict("records"):
if row["status"] == "TRIGGER_PENDING":
trail_exch = row["exch"]
trail_symbol = row["tsym"]
trail_order = row["norenordno"]
trail_qty = row["qty"]
trail_sl = api.modify_order(
exchange=trail_exch,
tradingsymbol=trail_symbol,
orderno=trail_order,
newquantity=trail_qty,
newprice_type="SL-LMT",
newprice=trail_sl_manual,
newtrigger_price=trail_sl_trigger,
)
log(
f"SL Order modified with trail price {trail_symbol} x {trail_qty}x{trail_order}x{trail_sl_manual}x{trail_sl_trigger}"
)
show_SL_order()
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def destroy_pos_lbl():
pos_symbol.destroy()
pos_Avg.destroy()
pos_ltp.destroy()
pos_netqty.destroy()
profitLabel.destroy()
def pos():
global profitLabel, Avg, netqty, symbol, exch
global pos_symbol, pos_Avg, pos_ltp, pos_netqty, profitLabel
global right_menu
try:
netqty = 0
while True:
# Refresh()
orders = api.get_positions()
orders = pd.DataFrame(orders)
row = 0
for row in orders.to_dict("records"):
if int(row["netqty"]) > 0:
symbol = row["tsym"]
Avg = row["netavgprc"]
liveprice = row["lp"]
pnlpos = float(row["urmtom"])
netqty = float(row["netqty"])
exch = row["exch"]
if netqty > 0:
pos_symbol = Label(
root,
text=symbol,
width=25,
bg="cornsilk3",
fg="black",
font=("Arial Black", 10),
)
pos_symbol.place(x=10, y=250)
pos_Avg = Label(
root,
text=Avg,
width=10,
bg="cornsilk3",
fg="black",
font=("Arial Black", 10),
)
pos_Avg.place(x=220, y=250)
pos_ltp = Label(
root,
text=liveprice,
width=10,
bg="cornsilk3",
fg="black",
font=("Arial Black", 10),
)
pos_ltp.place(x=310, y=250)
pos_netqty = Label(
root,
text=netqty,
width=10,
bg="cornsilk3",
fg="black",
font=("Arial Black", 10),
)
pos_netqty.place(x=400, y=250)
profitLabel = Label(
root, text=pnlpos, width=10, fg="black", font=("Arial Black", 10)
)
profitLabel.place(x=490, y=250)
right_menu = Menu(root, tearoff=0)
right_menu.config(
background="black", fg="white", activeforeground="Green"
)
right_menu.add_command(label="Stop Loss", command=lambda: popup_sl())
right_menu.add_command(label="Exit", command=lambda: manual_exit())
pos_symbol.bind("<Button-3>", do_popmenu)
if pnlpos > 0:
profitLabel.config(bg="Green")
else:
profitLabel.config(bg="Red")
elif netqty == 0:
log(f"No Open Position since the loop brokened")
break
# global stopPos
# if(stopPos==True):
# stopPos=False
# break
# break
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def my_expiry_update(*args): # Get the expiry date from Combobox
global Expiry_day
try:
Expiry_day = Expiry_day_combo_box1.get()
log(f"Expiry day selected {Expiry_day}")
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def my_index(*args):
global index_symbol
global qty
try:
index_symbol = index_combo1box.get()
log(f"index selected is: {index_symbol}")
except Exception as e:
errorlog(f"an exception occurred :: {e}")
try:
if index_symbol == "NIFTY":
qty_value = qty_combo_box1.get()
qty_to_lot = {"1": 50, "2": 100, "3": 150, "4": 200, "5": 250}
elif index_symbol == "BANKNIFTY":
qty_value = qty_combo_box1.get()
qty_to_lot = {"1": 25, "2": 50, "3": 75, "4": 100, "5": 125}
if qty_value == "1":
qty = qty_to_lot.get("1")
elif qty_value == "2":
qty = qty_to_lot.get("2")
elif qty_value == "3":
qty = qty_to_lot.get("3")
elif qty_value == "4":
qty = qty_to_lot.get("4")
elif qty_value == "5":
qty = qty_to_lot.get("5")
log(f"Qty selected is: {qty}")
except Exception as e:
errorlog(f"an exception occurred :: {e}")
def my_strike(
*args,
): # Get the token details according to the Comobox selection & update the call & pur strike
global tsym_ce
global tsym_pe
global token_ce
global token_pe
global call_strike_ltp
global put_strike_ltp
Strike_selection = Strike_combo_box1.get()
bn_TokenKey = "NSE|26009"
nf_TokenKey = "NSE|26000"
bn_nifty_lp = float(live_data[bn_TokenKey].get("lp"))
nifty_lp = float(live_data[nf_TokenKey].get("lp"))
# update_idx_price()
try:
if index_symbol == "NIFTY":
nf_round_number = math.fmod(nifty_lp, 50)
nf_atm = nifty_lp - nf_round_number
nf_itm = nf_atm - 50
nf_itm1 = nf_atm - 100
nf_itm2 = nf_atm - 150
nf_itm3 = nf_atm - 200
nf_itm4 = nf_atm - 250
nf_otm = nf_atm + 50
nf_otm1 = nf_atm + 100
nf_otm2 = nf_atm + 150
nf_otm3 = nf_atm + 200
nf_otm4 = nf_atm + 250
in_the_money4 = "itm4"
in_the_money3 = "itm3"
in_the_money2 = "itm2"
in_the_money1 = "itm1"
in_the_money = "itm"
at_the_money = "atm"
out_of_the_money = "otm"
out_of_the_money1 = "otm1"
out_of_the_money2 = "otm2"
out_of_the_money3 = "otm3"
out_of_the_money4 = "otm4"
bn_list = {
"itm4": nf_itm4,
"itm3": nf_itm3,
"itm2": nf_itm2,
"itm1": nf_itm1,
"itm": nf_itm,
"atm": nf_atm,
"otm": nf_otm,
"otm1": nf_otm1,
"otm2": nf_otm2,
"otm3": nf_otm3,
"otm4": nf_otm4,
}
in_the_money4 = "itm4"
in_the_money3 = "itm3"
in_the_money2 = "itm2"
in_the_money1 = "itm1"
in_the_money = "itm"
at_the_money = "atm"
out_of_the_money = "otm"
out_of_the_money1 = "otm1"
out_of_the_money2 = "otm2"
out_of_the_money3 = "otm3"
out_of_the_money4 = "otm4"
elif index_symbol == "BANKNIFTY":
bn_round_number = math.fmod(bn_nifty_lp, 100) # round the strike
bn_atm = bn_nifty_lp - bn_round_number
bn_itm = bn_atm - 100
bn_itm1 = bn_atm - 200
bn_itm2 = bn_atm - 300
bn_itm3 = bn_atm - 400
bn_itm4 = bn_atm - 500
bn_otm = bn_atm + 100
bn_otm1 = bn_atm + 200
bn_otm2 = bn_atm + 300
bn_otm3 = bn_atm + 400
bn_otm4 = bn_atm + 500
in_the_money4 = "itm4"
in_the_money3 = "itm3"
in_the_money2 = "itm2"
in_the_money1 = "itm1"
in_the_money = "itm"
at_the_money = "atm"
out_of_the_money = "otm"
out_of_the_money1 = "otm1"
out_of_the_money2 = "otm2"
out_of_the_money3 = "otm3"
out_of_the_money4 = "otm4"
bn_list = {
"itm4": bn_itm4,
"itm3": bn_itm3,
"itm2": bn_itm2,
"itm1": bn_itm1,
"itm": bn_itm,
"atm": bn_atm,
"otm": bn_otm,
"otm1": bn_otm1,
"otm2": bn_otm2,
"otm3": bn_otm3,
"otm4": bn_otm4,
}
in_the_money4 = "itm4"
in_the_money3 = "itm3"
in_the_money2 = "itm2"
in_the_money1 = "itm1"
in_the_money = "itm"
at_the_money = "atm"
out_of_the_money = "otm"
out_of_the_money1 = "otm1"
out_of_the_money2 = "otm2"
out_of_the_money3 = "otm3"
out_of_the_money4 = "otm4"
combo_value = Strike_selection
if combo_value == "ATM":
strike_price_Ce = bn_list.get(at_the_money)