-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmain.py
1987 lines (1596 loc) · 58.3 KB
/
main.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 kite_api import Kite
from tkinter import *
from threading import Thread, Lock
from ifl_api import MarketApi
from tkinter import messagebox
import pandas as pd
from datetime import datetime
from handlefile import delete_data, fetch_data, insert_data, fetch_data, change_data
from Auto import AutocompleteCombobox
import platform
import time
import xlrd
from Adapter import AdapterApi
from exchange import exchange_name, convert_date
import logging.config
import traceback
logging.config.fileConfig(r'.\Logs\log.ini',disable_existing_loggers=False)
logging.getLogger(__name__)
BUY = "BUY"
SELL = "SELL"
EXIT_ALL = 0
#Milisecconds
CALL_FEQ = 10000
NEW_CALL_FEQ = 3000
#Seconds
TARGETDIFF = 3
SLDIFF = 3
try:
dataframe = pd.read_excel(".\\OrderData\\order_data.xlsx")
pending_df = pd.read_excel('.\\OrderData\\notcompleted.xlsx')
completed_df = pd.read_excel('.\\OrderData\\completed.xlsx')
except:
logging.error("Exception: %s", traceback.format_exc())
try :
last_num = dataframe['SN'].iloc[-1]
except IndexError as e:
last_num = 1
logging.error(e, exc_info=True)
try :
last_cnum = dataframe['SN'].iloc[-1]
except IndexError as e:
last_cnum = 1
logging.error(e, exc_info=True)
columns = dataframe.columns
trade_threads = 0
y_value = 100
mp = MarketApi()
lock = Lock()
#variables to control threads
price_thread1 = 0
price_thread2 = 0
price_thread3 = 0
price_thread4 = 0
lsize_thread1 = 0
lsize_thread2 = 0
lsize_thread3 = 0
lsize_thread4 = 0
isop_thread = 0
PlaceOrderClass = AdapterApi(None) #Adapter Class
class ScrollFrame(Frame):
def __init__(self, parent):
super().__init__(parent) # create a frame (self)
self.canvas = Canvas(self, borderwidth=0, background="#ffffff") #place canvas on self
self.viewPort = Frame(self.canvas, background="#ffffff") #place a frame on the canvas, this frame will hold the child widgets
self.vsb = Scrollbar(self, orient="vertical", command=self.canvas.yview) #place a scrollbar on self
self.canvas.configure(yscrollcommand=self.vsb.set) #attach scrollbar action to scroll of canvas
self.vsb.pack(side="right", fill="y") #pack scrollbar to right of self
self.canvas.pack(side="left", fill="both", expand=True) #pack canvas to left of self and expand to fil
self.canvas_window = self.canvas.create_window((4,4), window=self.viewPort, anchor="nw", #add view port frame to canvas
tags="self.viewPort")
self.viewPort.bind("<Configure>", self.onFrameConfigure) #bind an event whenever the size of the viewPort frame changes.
self.canvas.bind("<Configure>", self.onCanvasConfigure) #bind an event whenever the size of the canvas frame changes.
self.viewPort.bind('<Enter>', self.onEnter) # bind wheel events when the cursor enters the control
self.viewPort.bind('<Leave>', self.onLeave) # unbind wheel events when the cursorl leaves the control
self.onFrameConfigure(None) #perform an initial stretch on render, otherwise the scroll region has a tiny border until the first resize
def onFrameConfigure(self, event):
'''Reset the scroll region to encompass the inner frame'''
self.canvas.configure(scrollregion=self.canvas.bbox("all")) #whenever the size of the frame changes, alter the scroll region respectively.
def onCanvasConfigure(self, event):
'''Reset the canvas window to encompass inner frame when required'''
canvas_width = event.width
self.canvas.itemconfig(self.canvas_window, width = canvas_width) #whenever the size of the canvas changes alter the window region respectively.
def onMouseWheel(self, event): # cross platform scroll wheel event
if platform.system() == 'Windows':
# self.canvas.yview_scroll(int(-1* (event.delta/120)), "units")
pass
elif platform.system() == 'Darwin':
self.canvas.yview_scroll(int(-1 * event.delta), "units")
else:
if event.num == 4:
self.canvas.yview_scroll( -1, "units" )
elif event.num == 5:
self.canvas.yview_scroll( 1, "units" )
def onEnter(self, event): # bind wheel events when the cursor enters the control
if platform.system() == 'Linux':
self.canvas.bind_all("<Button-4>", self.onMouseWheel)
self.canvas.bind_all("<Button-5>", self.onMouseWheel)
else:
self.canvas.bind_all("<MouseWheel>", self.onMouseWheel)
def onLeave(self, event): # unbind wheel events when the cursorl leaves the control
if platform.system() == 'Linux':
self.canvas.unbind_all("<Button-4>")
self.canvas.unbind_all("<Button-5>")
else:
self.canvas.unbind_all("<MouseWheel>")
def exit_all_trade():
"""
Exit all Trade at a given moment.
All trades will be squared off.
"""
global EXIT_ALL
mssg = messagebox.askyesno("EXIT","Do you want to exit all orders ?")
if mssg:
EXIT_ALL = 1
def clear_order_variables():
"""
Clear OrderScreen variables and set new values.
"""
product_type.set("MIS")
bs1.set(None)
bs2.set(None)
bs3.set(None)
bs4.set(None)
instru1.set("")
instru2.set("")
instru3.set("")
instru4.set("")
otype1.set(None)
otype2.set(None)
otype3.set(None)
otype4.set(None)
expiry1.set("")
expiry2.set("")
expiry3.set("")
expiry4.set("")
price1.set(0)
price2.set(0)
price3.set(0)
price4.set(0)
l1.set(0)
l2.set(0)
l3.set(0)
l4.set(0)
lotdata1.set("")
lotdata2.set("")
lotdata3.set("")
lotdata4.set("")
premium1.set(0)
premium2.set(0)
premium3.set(0)
premium4.set(0)
def clear():
"""
Clear PlaceOrder screen variables and assign new values.
"""
global price_thread1, price_thread2, price_thread3, price_thread4,\
lsize_thread1, lsize_thread2, lsize_thread3, lsize_thread4
ls.set(-1)
cp.set(-1)
st1.set(0)
st2.set(0)
st3.set(0)
st4.set(0)
# instrument.set("")
instu.set("")
lots.set(1)
expiry.set("")
Bid_label['text'] = "None"
Ask_label['text'] = "None"
inable_all()
price_thread1 = 0
price_thread2 = 0
price_thread3 = 0
price_thread4 = 0
lsize_thread1 = 0
lsize_thread2 = 0
lsize_thread3 = 0
lsize_thread4 = 0
def preorderscreen():
clear()
preorderframe.tkraise()
def orderscreen():
orderframe.tkraise()
def ordermenuscreen():
"""
Start Threads in OrderScreen.
"""
global price_thread1, price_thread2, price_thread3, price_thread4, lsize_thread1, lsize_thread2, lsize_thread3, lsize_thread4
lsize_thread1, lsize_thread2, lsize_thread3, lsize_thread4 = 1, 1, 1, 1
price_thread1, price_thread2, price_thread3, price_thread4 = 1, 1, 1, 1
clear_order_variables()
owidget_active()
update_price_label()
update_lotlabel()
orderframe.tkraise()
def getexpiry():
"""
get list of expiry date from IFL api.
Returns
-------
list
sorted list of expiry dates in `%d-%m-%Y %b` format.
"""
symbol = "NIFTY"
s = "OPTSTK"
if "NIFTY" in symbol:
s = "OPTIDX"
dates = mp.get_expiry(symbol=symbol,esegment=2,series=s)
date = []
for i in dates:
d = datetime.strptime(i,"%Y-%m-%d").date()
date.append(str(d.strftime("%d-%m-%Y %b")))
date.sort()
date = sorted(date,key=lambda x: x.split("-")[1])
date = sorted(date,key=lambda x: x.split("-")[2].split(" ")[0])
return date
def inable_all():
"""
Inable all Strike price widgets in PlaceOrder Screen.
"""
strike = [s1,s2,s3,s4]
for i in strike:
i['state'] = 'normal'
def disable_n(n):
"""
Parameters
----------
n : int
int specifing how many stike price widgets on PlaceOrder
Screen will be disabled.
"""
strike = [s4,s3,s2,s1]
for i in range(1,n+1):
strike[i-1]['state'] = 'disable'
def dummy_radio_fun():
t = Thread(target=radio_fun)
t.start()
def radio_fun():
"""
Function called by radiobuttons to disable/inable
Strike price Widgets on PlaceOrder screen based on a strategy.
"""
value = cp.get()
if value!=-1:
inable_all()
if cp.get() in [1,2,3]:
disable_n(2)
elif cp.get() ==4:
disable_n(1)
def setorder():
"""
Function to validate input and open OrderScreen
for placing orders.
"""
if cp.get()==-1 or ls==-1:
messagebox.showerror("ERROR","Select a Valid Strategy")
return 0
try:
if lots.get() <=0 :
messagebox.showerror("ERROR","Invalid Lot Size")
except Exception as e:
messagebox.showerror("ERROR",e+" for Lot No.")
logging.error(e,exc_info=True)
return 0
else:
clear_order_variables() # Clears orderscreen variables.
update_order(cp.get()) # Update orderscreen variables.
orderscreen()
def start_setorder():
t = Thread(target=setorder)
t.start()
def update_order(n):
"""
Function to manage Order Blocks on orderscreen and their
threads for updating marketprice and lotsize.
Parameters
----------
n : int
int specifying number of order instruments to manage.
This number depends on the strategy choosen on placeorder screen.
"""
global price_thread1, price_thread2, price_thread3, price_thread4, lsize_thread1, lsize_thread2, lsize_thread3, lsize_thread4,\
isop_thread
instru_value = instu.get()
expiry_date = expiry.get()
api_expiry_date = convert_date(expiry_date)
lots_num = lots.get()
isop_thread = 1
s = "OPTSTK"
if instru_value.find("NIFTY")!=-1:
s = "OPTIDX"
if n in [1,2,3]:
owidget_active()
owidget_disable(2)
s1instru.set(instru_value)
s2instru.set(instru_value)
l1.set(lots_num)
l2.set(lots_num)
if ls.get()==1:
bs1.set(BUY)
bs2.set(SELL)
else:
bs1.set(SELL)
bs2.set(BUY)
if n==2:
otype1.set("PE")
otype2.set("PE")
else:
otype1.set("CE")
otype2.set("CE")
num1, _ = get_instru_id(instru_value,"CE",api_expiry_date,st1.get(),s)
num2 = num1
lotdata1.set(str(num1))
lotdata2.set(str(num2))
price1.set(st1.get())
price2.set(st2.get())
price_thread1 = 1
price_thread2 = 1
lsize_thread1 = 1
lsize_thread2 = 1
expiry1.set(expiry_date)
expiry2.set(expiry_date)
elif n==4:
owidget_active()
owidget_disable(1)
s1instru.set(instru_value)
s2instru.set(instru_value)
s3instru.set(instru_value)
l1.set(lots_num)
l2.set(lots_num)
l3.set(lots_num)
if ls.get()==1:
bs1.set(BUY)
bs2.set(SELL)
bs3.set(BUY)
else:
bs1.set(SELL)
bs2.set(BUY)
bs3.set(SELL)
otype1.set("CE")
otype2.set("CE")
otype3.set("CE")
num1, _ = get_instru_id(instru_value,"CE",api_expiry_date,st1.get(),s)
num2 = num1
num3 = num1
lotdata1.set(str(num1))
lotdata2.set(str(num2))
lotdata3.set(str(num3))
price1.set(st1.get())
price2.set(st2.get())
price3.set(st3.get())
#Start Threads
price_thread1 = 1
price_thread2 = 1
price_thread3 = 1
lsize_thread1 = 1
lsize_thread2 = 1
lsize_thread3 = 1
expiry1.set(expiry_date)
expiry2.set(expiry_date)
expiry3.set(expiry_date)
else:
owidget_active()
s1instru.set(instru_value)
s2instru.set(instru_value)
s3instru.set(instru_value)
s4instru.set(instru_value)
l1.set(lots_num)
l2.set(lots_num)
l3.set(lots_num)
l4.set(lots_num)
num1, _ = get_instru_id(instru_value,"PE",api_expiry_date,st1.get(),s)
num2, _ = get_instru_id(instru_value,"CE",api_expiry_date,st2.get(),s)
if ls.get()==1:
bs1.set(BUY)
bs2.set(SELL)
bs3.set(BUY)
bs4.set(SELL)
else:
bs1.set(SELL)
bs2.set(BUY)
bs3.set(SELL)
bs4.set(BUY)
otype1.set("CE")
otype2.set("CE")
otype3.set("PE")
otype4.set("PE")
lotdata1.set(str(num1))
lotdata2.set(str(num1))
lotdata3.set(str(num2))
lotdata4.set(str(num2))
price1.set(st1.get())
price2.set(st2.get())
price3.set(st3.get())
price4.set(st4.get())
#Start Threads
price_thread1 = 1
price_thread2 = 1
price_thread3 = 1
price_thread4 = 1
lsize_thread1 = 1
lsize_thread2 = 1
lsize_thread3 = 1
lsize_thread4 = 1
expiry1.set(expiry_date)
expiry2.set(expiry_date)
expiry3.set(expiry_date)
expiry4.set(expiry_date)
update_thread = Thread(target=update_price_label,args=())
update_thread.start()
update_lotlabel()
def owidget_disable(n):
"""
Disable Widgets on OrderScreen.
"""
for i in range(n):
list_sc[i]['state'] = 'disable'
list_sp[i]['state'] = 'disable'
list_b[i]['state'] = 'disable'
list_s[i]['state'] = 'disable'
list_exp[i]['state'] = 'disable'
list_instru[i]['state'] = 'disable'
list_lotlabel[i]['state'] = 'disable'
list_sprice[i]['state'] = 'disable'
list_mkprice[i]['state'] = 'disable'
list_lot[i]['state'] = 'disable'
def owidget_active():
"""
Activate Widgets on OrderScreen.
"""
for i in range(4):
list_sc[i]['state'] = 'normal'
list_sp[i]['state'] = 'normal'
list_b[i]['state'] = 'normal'
list_s[i]['state'] = 'normal'
list_exp[i]['state'] = 'normal'
list_instru[i]['state'] = 'normal'
list_lotlabel[i]['state'] = 'normal'
list_sprice[i]['state'] = 'normal'
list_mkprice[i]['state'] = 'normal'
list_lot[i]['state'] = 'normal'
def set_top():
"""
Create TradeManagement Screen.
"""
global top, scroll_frame, display_frame
top = Toplevel()
scroll_frame = ScrollFrame(top)
scroll_frame.pack(fill='both',expand=1)
scroll_frame.tkraise()
display_frame = Frame(scroll_frame.viewPort,bg='white')
display_frame.pack(side='top',anchor=NW,fill='both',expand=1)
display_frame.tkraise()
trade_frame = Frame(display_frame,bg='white')
trade_frame.pack(fill='x',expand=1,ipady=100)
trade_frame.tkraise()
top.geometry('700x600')
top.resizable(0,0)
top.title("AlgoApp | Trade Management")
top.withdraw()
top.protocol('WM_DELETE_WINDOW',top.withdraw) # Replace default close function
Label(display_frame,text='Initial SOP',font=('Calibri',13),bg='white').place(x=30,y=20)
Label(trade_frame,text='Current SOP',font=('Calibri',13),bg='white').place(x=170,y=20)
Label(trade_frame,text='Target',font=('Calibri',13),bg='white').place(x=310,y=20)
Label(trade_frame,text='SL',font=('Calibri',13),bg='white').place(x=410,y=20)
Label(trade_frame,text='P&L',font=('Calibri',13),bg='white').place(x=510,y=20)
def tradescreen():
"""
Open TradeManagement Screen.
"""
top.deiconify()
def create_api_top():
"""
Create API selction window for placing
orders. Default api for placing orders
is `Kite Free`.
"""
global api_variable, api_top
api_top = Toplevel(bg='white')
api_top.geometry('200x200')
api_top.resizable(0,0)
api_variable = IntVar()
api_variable.set(3)
Label(api_top,text=" Select You API for placing orders. ",font=("Arial",9,"bold"),bg='white').pack(pady=12)
ifl = Radiobutton(api_top,text="IFL",variable=api_variable,value=1,bg='white',command=set_Adapter)
ifl.pack(pady=10)
kite_api = Radiobutton(api_top,text='Kite',variable=api_variable,value=2,bg='white',command=set_Adapter)
kite_api.pack(pady=10)
kite_free = Radiobutton(api_top,text='Kite Free',variable=api_variable,value=3,bg='white',command=set_Adapter)
kite_free.pack(pady=10)
api_top.withdraw()
api_top.protocol('WM_DELETE_WINDOW',api_top.withdraw)
def order_api():
"""
Open API Selection window.
"""
api_top.deiconify()
def set_Adapter():
"""
Change Adapter based on the API selection
for placing orders on API selection screen.
"""
global PlaceOrderClass
if api_variable.get()==1:
PlaceOrderClass = AdapterApi(MarketApi())
# elif api_variable.get()==2:
# PlaceOrderClass = AdapterApi(Kite())
elif api_variable.get()==3:
PlaceOrderClass = AdapterApi(None)
def dummy_place_order():
t = Thread(target=place_realorder)
t.start()
def update_price_label():
"""
Function to start Threads for updating market price
of instruments in OrderScreen.
"""
price_thread_list = [price_thread1, price_thread2,price_thread3, price_thread4]
if price_thread_list.count(1)==2:
t1 = Thread(target=price_update_thread1,args=())
t1.start()
t2 = Thread(target=price_update_thread2,args=())
t2.start()
elif price_thread_list.count(1)==3:
t1 = Thread(target=price_update_thread1,args=())
t1.start()
t2 = Thread(target=price_update_thread2,args=())
t2.start()
t3 = Thread(target=price_update_thread3,args=())
t3.start()
elif price_thread_list.count(1)==4:
t1 = Thread(target=price_update_thread1,args=())
t1.start()
t2 = Thread(target=price_update_thread2,args=())
t2.start()
t3 = Thread(target=price_update_thread3,args=())
t3.start()
t4 = Thread(target=price_update_thread4,args=())
t4.start()
t5 = Thread(target=update_isop,args=())
t5.start()
def price_update_thread1():
"""
Function to Update market Price of 1st
instrument in OrderScreen.
"""
if instru1.get() and otype1.get():
o = 'CE'
if otype1.get()=="PE":
o = "PE"
instru = instru1.get()
series='OPTSTK'
if 'NIFTY' in instru:
series='OPTIDX'
try :
_, id_ = get_instru_id(instru,o,convert_date(expiry1.get()),price1.get(),series)
m = MarketApi()
m_bid, m_ask = m.get_quote(id_,2,1502)
if bs1.get()==BUY:
premium1.set(float(m_ask[0]))
else:
premium1.set(float(m_bid[0]))
except Exception as e:
print("price update 1 ",e)
logging.error(e,exc_info=True)
if price_thread1:
time.sleep(5)
price_update_thread1()
else:
return
def price_update_thread2():
"""
Function to Update market Price of 2nd
instrument in OrderScreen.
"""
if instru2.get() and otype2.get():
o = 'CE'
if otype2.get()=="PE":
o = "PE"
instru = instru2.get()
series='OPTSTK'
if 'NIFTY' in instru:
series='OPTIDX'
try :
_, id_ = get_instru_id(instru,o,convert_date(expiry2.get()),price2.get(),series)
m = MarketApi()
m_bid, m_ask = m.get_quote(id_,2,1502)
if bs2.get()==BUY:
premium2.set(str(m_ask[0]))
else:
premium2.set(str(m_bid[0]))
except Exception as e:
print("price update 2 ",e)
logging.error(e,exc_info=True)
if price_thread2:
time.sleep(5)
price_update_thread2()
else:
return
def price_update_thread3():
"""
Function to Update market Price of 3rd
instrument in OrderScreen.
"""
if instru3.get() and otype3.get():
o = 'CE'
if otype3.get()=="PE":
o = "PE"
instru = instru3.get()
series='OPTSTK'
if 'NIFTY' in instru:
series='OPTIDX'
try :
_, id_ = get_instru_id(instru,o,convert_date(expiry3.get()),price3.get(),series)
m = MarketApi()
m_bid, m_ask = m.get_quote(id_,2,1502)
if bs3.get()==BUY:
premium3.set(str(m_ask[0]))
else:
premium3.set(str(m_bid[0]))
except Exception as e:
print("price update 3 ",e)
logging.error(e,exc_info=True)
if price_thread3:
time.sleep(5)
price_update_thread3()
else:
return
def price_update_thread4():
"""
Function to Update market Price of 4th
instrument in OrderScreen.
"""
if instru4.get():
o = 'CE'
if otype4.get()=="PE":
o = "PE"
instru = instru4.get()
series='OPTSTK'
if 'NIFTY' in instru:
series='OPTIDX'
try :
_, id_ = get_instru_id(instru,o,convert_date(expiry4.get()),price4.get(),series)
m = MarketApi()
m_bid, m_ask = m.get_quote(id_,2,1502)
if bs4.get()==BUY:
premium4.set(str(m_ask[0]))
else:
premium4.set(str(m_bid[0]))
except Exception as e:
print("price update 4 ",e)
logging.error(e,exc_info=True)
if price_thread4:
time.sleep(5)
price_update_thread4()
else:
return
def update_isop():
try:
bs = [bs1.get(), bs2.get(), bs3.get(), bs4.get()]
lots = [l1.get(), l2.get(), l3.get(), l4.get()]
price_list = [premium1.get(), premium2.get(), premium3.get(), premium4.get()]
isop = 0
for i in range(4):
if bs[i]=="BUY":
isop+=(lots[i]*price_list[i])
elif bs[i]=="SELL":
isop-=(lots[i]*price_list[i])
isop_value['text'] = f'{isop:.2f}'
except Exception as e:
logging.error(e,exc_info=True)
if isop_thread:
time.sleep(4.9)
update_isop()
else:
return
def update_lotlabel():
"""
Function to start Threads for updating lot size
of instruments in OrderScreen.
"""
lot_label_list = [lsize_thread1, lsize_thread2, lsize_thread3,lsize_thread4]
if lot_label_list.count(1)==2:
t1 = Thread(target=set_lot_label1,args=())
t1.start()
t2 = Thread(target=set_lot_label2,args=())
t2.start()
elif lot_label_list.count(1)==3:
t1 = Thread(target=set_lot_label1,args=())
t1.start()
t2 = Thread(target=set_lot_label2,args=())
t2.start()
t3 = Thread(target=set_lot_label3,args=())
t3.start()
elif lot_label_list.count(1)==4:
t1 = Thread(target=set_lot_label1,args=())
t1.start()
t2 = Thread(target=set_lot_label2,args=())
t2.start()
t3 = Thread(target=set_lot_label3,args=())
t3.start()
t4 = Thread(target=set_lot_label4,args=())
t4.start()
def set_lot_label1():
"""
Function to Update lot size of 1st
instrument in OrderScreen.
"""
if instru1.get() and exp1['value']:
o = 'CE'
if otype1.get()=="PE":
o = "CE"
instru = instru1.get()
series='OPTSTK'
if 'NIFTY' in instru:
series='OPTIDX'
try :
lotsize, id_ = get_instru_id(instru,o,convert_date(expiry1.get()),price1.get(),series)
lotdata1.set(str(lotsize))
except Exception as e:
print("Lot size 1 ",e)
logging.error(e,exc_info=True)
if lsize_thread1:
time.sleep(5)
set_lot_label1()
else:
return
def set_lot_label2():
"""
Function to Update lot size of 2nd
instrument in OrderScreen.
"""
if instru2.get() and exp2['value']:
o = 'CE'
if otype2.get()=="PE":
o = "PE"
instru = instru2.get()
series='OPTSTK'
if 'NIFTY' in instru:
series='OPTIDX'
try :
lotsize, id_ = get_instru_id(instru,o,convert_date(expiry2.get()),price2.get(),series)
lotdata2.set(str(lotsize))
except Exception as e:
print("lot size 2 ",e)
logging.error(e,exc_info=True)
if lsize_thread2:
time.sleep(5)
set_lot_label2()
else:
return
def set_lot_label3():
"""
Function to Update lot size of 3rd
instrument in OrderScreen.
"""
if instru3.get() and exp3['value']:
o = 'CE'
if otype3.get()=="PE":
o = "PE"
instru = instru3.get()
series='OPTSTK'
if 'NIFTY' in instru:
series='OPTIDX'
try :
lotsize, id_ = get_instru_id(instru,o,convert_date(expiry3.get()),price3.get(),series)
lotdata3.set(str(lotsize))
except Exception as e:
print("lot size 3 ",e)
logging.error(e,exc_info=True)
if lsize_thread3:
time.sleep(5)
set_lot_label3()
else:
return
def set_lot_label4():
"""
Function to Update lot size of 4th
instrument in OrderScreen.
"""
if instru4.get() and exp4['value']:
o = 'CE'
if otype4.get()=="PE":
o = "PE"
instru = instru4.get()
series='OPTSTK'
if 'NIFTY' in instru:
series='OPTIDX'
try :
lotsize, id_ = get_instru_id(instru,o,convert_date(expiry4.get()),price4.get(),series)
lotdata4.set(str(lotsize))
except Exception as e:
print("lot size 4 ",e)
logging.error(e,exc_info=True)
if lsize_thread4:
time.sleep(5)
set_lot_label4()
else:
return
def place_realorder():
"""
Function to Place orders based on the values specified on
orderscreen. Order is managed by creating `ManageOrder` object
which updates profit, current sop and other values. It also inserts
the order in `OrderData//orders_data.xlsx` after it is placed.
"""
global last_num,trade_threads,y_value, price_thread1, price_thread2,\
price_thread3, price_thread4, lsize_thread1, lsize_thread2, lsize_thread3, lsize_thread4, EXIT_ALL,\
isop_thread