forked from RajeshSivadasan/alice-blue-futures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathab.py
1802 lines (1452 loc) · 88 KB
/
ab.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
# pylint: disable=unused-wildcard-import
# v1.1 Added new column "signal", changed df_cols and reset again,
# v1.2 Disabled Opening range breakout code, blank initiation of signal column value (as .at was giving float conversion error)
# v1.3 Added parameterization of qty
# v1.3 Premarket trade procedure and logic added
# v1.4 getMTM and check_MTM_Limit() merged into one
# v1.5 Exception handling in savedata(), close_all_orders(), counters for df_nifty and crude implemented,
# df_crude_med created and data captured
# v1.6 df_nifty_med created and data captured, updated savedata()
# v1.7 Implemented df_crude_med and df_nifty_med in both buy and sell logic
# v1.8 premarket_tarde(): enabled BO2 condition
# v1.9 Fixed Tele() issue, added premarket_flag
# v2.0 Processing time limit changed to 2 seconds; changed medium level df interval logic, cur_min used
# v2.1 Enabled Telegram notification in premarket_tarde()
# v2.2 Interval set to 3 min in ab.ini and counter trade taken
# v2.3 Premarket trade condition check. Gap of 50 pts and above, premarket will not trigger
# Saving datafilename with Savedata(). Reading previous 10 period data for nifty at the start
# v2.4 Changed BO2 lt_price to be offset by half of ATR both buy/sell crude/nifty
# v2.5 Updated if condition for adding nifty dataframe rows. Added time check as blank rows were going into df.
# v2.6 nifty_sl set to ST(SuperTrend price)+3 in buy_nifty() and sell_nifty()
# v2.7 ST buy/Sell logic implemented using nifty_med ST as well
# v2.8 Fixed ST_Medium buy/sell not getting triggered. wrong dataframe name used. copy/paste miss.
# implemented ST crude_med buy/Sell option, Fix incorrect SL issue in case of medium timeframe override for nifty only.
# It was taking low timeframe ST for calculating value of SL which was comming negative and huge.
# v2.9 Pending - crude override trade price and sl logic
# v3.0 Fixed crude medium ST Sell calling buy_nifty
# v3.1 Added bot_token and ChatID for parameterising telegram bot and chat options
# v3.2 Enable BO3 for Nifty
# v3.3 buy/sell cancellation handled in close_all_orders(), enable_MCX, enable_NFO implemented
# v3.4 savedata() - Included parameter to update datafilename in the .ini file
# v3.5 Merged iLog() and Tele() functions
# v3.6 get_trade_price() in nifty buy/sell
# v3.7 SL added in the df_nifty for offline MTM calculations
# v3.8 added cur_HHMM > 914 in nifty df and order execution code other optimisations in buy/sell nifty/crude
# v3.9 check_pending_orders() implemented in buy/sell nifty/crude before order execution
# v4.0 trade_limit_reached() implemented in buy/sell nifty/crude
# v4.1 deactivated ST_MEDIUM counter trade execution
# v4.2 ab_lib.update_contract_symbol() implemented, get_trade_price() in crude buy/sell
# SL added in the df_nifty for offline MTM calculations
# v4.3 enableNFO while reading previous day datafile, logging post check_pending_orders() invocation in buy/sell
# v4.4 Set initial sleep time to match the crude market opening time of 9:00 AM to avoid previous junk values
# check_pending_orders() and cancellation implementation changes in nifty/crude buy/sell
# trade_limit_reached() moved before check_pending_orders(). Need to check if this is the correct approach
# v4.5 Fixed TypeError on init_sleep_seconds. Added CRUDE previous data load functionality. Updated savedata() for crude
# v4.6 Fixed NameError: name 'ilog' is not defined in trade_limit_reached()
# v4.7 check_pending_orders not required as if there are no position we would need to close all open/pending orders and
# initiate fresh buy/sell orders. Hence, close_all_orders() call in nifty/crude buy/sell.
# get_trade_price - Changed the SL to df_med.ST due to SL hits (4-Aug-2020)
# v4.8 Consecutive order execution due to ST_Medium fixed.
# v4.9 reverted the v4.7 changes of get_trade_price(), parameterised dl_buffer
# v5.0 Fixed the v4.8 issue as it was not solved by the min flag
# Crude/Nifty position updated in check_MTM_Limit() and used in buy/sell nifty/crude()
# close_pend_ord_post_interval parameter implementation WIP (Cancelled)
# v5.1 close_pend_ord_post_interval changed to pending_ord_limit_mins
# Implemented cancellation of open orders after n mins in close_all_orders(). This funciton needs to be called every ineterval with ord_open_time>0 from parameter
# v5.2 WebSocket disconnection and subscription/tick loss issue. Upgraded the package
# enabled MIS orders apart from previous only BO orders. configurable in ab.ini. Nifty default to BO and Crude default to MIS
# v5.3 BUG: Fixed reload of updated nifty contract symbol from ab.ini file
# v5.4 get_trade_price(); Ignore ATR addition to lt price if TR is very high (>25); can be parameterised.
# v5.5 1.Changed reading previous 10 period data to 40 as ATR and ST calculation were not carrying over. ST up changed to down
# 2.For MIS nifty/crude buy/sell, squareoff handled by doubling the ord qty
# 3.Created squareOff_MIS() to handle CRUDE/Nifty MIS Eod position closure and exit position when mtm limit is reached
# v5.6 check_MTM_Limit() updated to keep a SL order at previous open/close instead of market squreoff to get the benefit of one way rally.
# can check for implementation of trailing SL (update the last order)
# v5.7 MIS order placing changed to Market orders as partial orders were remaining pending and later cancelled.
# get_trade_price(): bo_level 0 option added to have market order option in Nifty BO
# v5.8 get_trade_price(): bo_level -1 for market and 0 for last close
# v5.9 reset trade flags(mcx,nfo) to 1 at EOD crude i.e post 11:30 pm ist
# v6.0 fixed BUG: error in reading enable_NFO_data
# v6.1 added and implemented additional parameters for nifty/crude bo execution level -1,0,1,2,3...
# v6.2 fixed (while reading ab.ini) int conversion bug because of the above change
# v6.3 parameterised sl in get_trade_price()
# v6.4 warnings set at buy/sell logging calls. mtm limits,lmt ord strategy level moved to realtime procedure.
# commented get_position() method(can be removed later) as position is derived in the check_mtm_limit() method.
# v6.5.1 check_trade_time_zone() implemented; Check_mtm_limit(): mtm value printed while calling ilog
# v6.6.2 close_all_orders() updated to inlude MIS Square offs. Implemented in ST_MED counter signals.
# print calculated SL in get_trade_price()
# Fixed typo error in calling iLog (was calling ilog) L vs l )
# v6.6.3 Removed dead code, get position proc
# v6.7 get_trade_price(): removed multiplication with 0.5 and updated the effected code. Multiplication factor to be set in bo_level
# v6.8 check_MTM_limit(): Changes made to fix non saving of tradeflag into the ab.ini file.
# v6.9 get_trade_price(): changed the SL calcuation to consider only ST_Med. sl_buffer may need to be reduced or made 0 or negative values.
# Consider seperate sl_buffer for nifty and crude
# v6.9.1 Changed logging of ticks and close in the main while loop
# v6.9.2 Implemented try block in subscribe_ins(), INI_FILE variable
# v6.9.3 mcx_trade_start_time implemented in .ini and in code.
# v6.9.4 condition added to Exit the program post NSE closure
# bg process
# 2020-09-01 09:59:18.152555|1|chat_id=670221062 text=Cmd ls
# exception= list index out of range
# 2020-09-01 10:00:18.565516|1|chat_id= text=Cmd ls
# exception= list index out of range
# Open issues/tasks:
# Consider seperate sl_buffer for nifty and crude in get_trade_price()
# Check if order parameters like order type and others can be paramterised
# Look at close pending orders, my not be efficient, exception handling and all
# WebSocket disconnection and subscription/tick loss issue. Upgraded the package
# Option of MIS orders for CRUDE to be added, maybe for nifty as well. Can test with nifty
# check_MTM_Limit() limitation : if other nifty or crude scrips are traded this will messup the position
# trade_limit_reached() moved before check_pending_orders(). Need to check if this is the correct approach
# get_trade_price bo_level to be parameterised from .ini 0 , 1 (half of atr), 2 (~atr)
# If ATR > 10 or something activate BO3
# In ST up/down if ST_MEDIUM is down/Up - If high momentum (check rate of change) chances are it will break medium SL
# Look at 3 min to 6 min crossover points , compare ST values of low and medium for possible override
# Retun/Exit function after Postion check in buy/sell function fails
# Look at df_nifty.STX.values; Can we use tail to get last n values in the list
# Can have few tasks to be taken care/check each min like MTM/Tradefalg check/set. This is apart from interval
# Delay of 146 secs, 57 secs, 15 secs etc seen. Check and Need to handle
# Look at 5/10 mins trend, dont take positions against the trend
# Keep limit price at 10% from ST and Sl beyond 10% from ST
# Relook at supertrend multiplier=2.5 option instead of current 3
# NSE Premarket method values may not be current as crude open time is considered . Need to fetch this realtime around 915
# May need try/catch in reading previous day datafile due to copy of ini file or failed runs
# Can look at frequency of data export through parameter, say 60,120,240 etc..
# Guidelines:
# TSL to be double of SL (Otherwise mostly SLs are hit as they tend to )
# SL will be hit in high volatility. SL may be set to ATR*3 or medium df Supertrend Value
# Always buy market, in case SL reverse and get out cost to cost. Market has to come up.
# SLs are usually hit in non volatile market, so see if you can use less qty and no SLs, especially crude.
# Dont go against the trend in any case.
# Avoid manual trades
# Manual running of program
# python3 ab.py &
import ab_lib
from ab_lib import *
import sys
import time
# Reduce position to cut loss if price is going against the trade, can close BO1
# Manual Activities
# Frequency - Monthly , Change Symbol of nifty/crude in ab.ini
# Enable logging to file
sys.stdout = sys.stderr = open(r"./log/ab_" + datetime.datetime.now().strftime("%Y%m%d") +".log" , "a")
######################################
# Initialise variables
######################################
INI_FILE = "ab.ini" # Set .ini file name used for storing confi info.
# Load parameters from the config file
cfg = configparser.ConfigParser()
cfg.read(INI_FILE)
# Set user profile; Access token and other user specific info from ab.ini will be pulled from this section
ab_lib.strChatID = cfg.get("tokens", "chat_id")
ab_lib.strBotToken = cfg.get("tokens", "bot_token") #Bot include bot prefix in the token
strMsg = "Initialising " + __file__
iLog(strMsg,sendTeleMsg=True)
# crontabed this at 9.00 am instead of 8.59
# Set initial sleep time to match the crude market opening time of 9:00 AM to avoid previous junk values
init_sleep_seconds = int(cfg.get("info", "init_sleep_seconds"))
strMsg = "Setting up initial sleep time of " + str(init_sleep_seconds) + " seconds."
iLog(strMsg,sendTeleMsg=True)
time.sleep(init_sleep_seconds)
susername = cfg.get("tokens", "uid")
spassword = cfg.get("tokens", "pwd")
# Realtime variables also loaded in get_realtime_config()
enableBO2_nifty = int(cfg.get("realtime", "enableBO2_nifty")) # True = 1 (or non zero) False=0
enableBO3_nifty = int(cfg.get("realtime", "enableBO3_nifty")) # True = 1 (or non zero) False=0
enableBO2_crude = int(cfg.get("realtime", "enableBO2_crude")) # True = 1 (or non zero) False=0
enableBO3_crude = int(cfg.get("realtime", "enableBO3_crude")) # True = 1 (or non zero) False=0
tradeNFO = int(cfg.get("realtime", "tradeNFO")) # True = 1 (or non zero) False=0
tradeMCX = int(cfg.get("realtime", "tradeMCX")) # True = 1 (or non zero) False=0
nifty_sl = float(cfg.get("realtime", "nifty_sl")) #20.0
crude_sl = float(cfg.get("realtime", "crude_sl")) #15.0
mtm_sl = int(cfg.get("realtime", "mtm_sl")) #amount below which program exit all positions
mtm_target = int(cfg.get("realtime", "mtm_target")) #amount above which program exit all positions and not take new positions
nifty_bo1_qty = int(cfg.get("realtime", "nifty_bo1_qty"))
nifty_bo2_qty = int(cfg.get("realtime", "nifty_bo2_qty"))
nifty_bo3_qty = int(cfg.get("realtime", "nifty_bo3_qty"))
crude_bo1_qty = int(cfg.get("realtime", "crude_bo1_qty"))
crude_bo2_qty = int(cfg.get("realtime", "crude_bo2_qty"))
crude_bo3_qty = int(cfg.get("realtime", "crude_bo3_qty"))
sl_buffer = int(cfg.get("realtime", "sl_buffer"))
nifty_ord_type = cfg.get("realtime", "nifty_ord_type") # BO / MIS
crude_ord_type = cfg.get("realtime", "crude_ord_type") # MIS / BO
# atr * level * 0.5 (lvl = 0->close, -1->Mkt Price, 1,2,3..based on times of atr gap required)
nifty_ord_exec_level1 = float(cfg.get("realtime", "nifty_ord_exec_level1"))
nifty_ord_exec_level2 = float(cfg.get("realtime", "nifty_ord_exec_level2"))
nifty_ord_exec_level3 = float(cfg.get("realtime", "nifty_ord_exec_level3"))
crude_ord_exec_level1 = float(cfg.get("realtime", "crude_ord_exec_level1"))
crude_ord_exec_level2 = float(cfg.get("realtime", "crude_ord_exec_level2"))
crude_ord_exec_level3 = float(cfg.get("realtime", "crude_ord_exec_level3"))
nifty_lot_size = int(cfg.get("info", "nifty_lot_size"))
criude_lot_size = int(cfg.get("info", "crude_lot_size"))
nifty_symbol = cfg.get("info", "nifty_symbol")
crude_symbol = cfg.get("info", "crude_symbol")
nifty_tgt1 = float(cfg.get("info", "nifty_tgt1")) #15.0
nifty_tgt2 = float(cfg.get("info", "nifty_tgt2")) #60.0 medium target
nifty_tgt3 = float(cfg.get("info", "nifty_tgt3")) #150.0 high target
crude_tgt1 = float(cfg.get("info", "crude_tgt1")) #10.0
crude_tgt2 = float(cfg.get("info", "crude_tgt2")) #60.0
crude_tgt3 = float(cfg.get("info", "crude_tgt2")) #60.0
olhc_duration = int(cfg.get("info", "olhc_duration")) #3
nifty_sqoff_time = int(cfg.get("info", "nifty_sqoff_time")) #1512 time after which orders not to be processed and open orders to be cancelled
crude_sqoff_time = int(cfg.get("info", "crude_sqoff_time")) #2310 time after which orders not to be processed and open orders to be cancelled
nifty_tsl = int(cfg.get("info", "nifty_tsl")) #Trailing Stop Loss for Nifty
crude_tsl = int(cfg.get("info", "crude_tsl")) #Trailing Stop Loss for Nifty
rsi_buy_param = int(cfg.get("info", "rsi_buy_param")) #may need exchane/indicator specific; ML on this?
rsi_sell_param = int(cfg.get("info", "rsi_sell_param"))
premarket_advance = int(cfg.get("info", "premarket_advance"))
premarket_decline = int(cfg.get("info", "premarket_decline"))
premarket_flag = int(cfg.get("info", "premarket_flag")) # whether premarket trade enabled or not 1=yes
nifty_last_close = float(cfg.get("info", "nifty_last_close"))
# file_crude = cfg.get("info", "file_crude")
enable_MCX = int(cfg.get("info", "enable_MCX")) # 1=Original flag for CRUDE trading. Daily(realtime) flag to be reset eod based on this.
enable_NFO = int(cfg.get("info", "enable_NFO")) # 1=Original flag for Nifty trading. Daily(realtime) flag to be reset eod based on this.
enable_MCX_data = int(cfg.get("info", "enable_MCX_data")) # 1=CRUDE data subscribed, processed and saved/exported
enable_NFO_data = int(cfg.get("info", "enable_NFO_data")) # 1=NIFTY data subscribed, processed and saved/exported
file_nifty = cfg.get("info", "file_nifty")
file_nifty_med = cfg.get("info", "file_nifty_med")
file_crude = cfg.get("info", "file_crude")
file_crude_med = cfg.get("info", "file_crude_med")
no_of_trades_limit = int(cfg.get("info", "no_of_trades_limit")) # 2 BOs trades per order; 6 trades for 3 orders
pending_ord_limit_mins = int(cfg.get("info", "pending_ord_limit_mins")) # Close any open orders not executed beyond the set limit
mcx_trade_start_time = int(cfg.get("info", "mcx_trade_start_time"))
mcx_trade_end_time = int(cfg.get("info", "mcx_trade_end_time"))
nifty_trade_start_time = int(cfg.get("info", "nifty_trade_start_time"))
nifty_trade_end_time = int(cfg.get("info", "nifty_trade_end_time"))
nifty_no_trade_zones = eval(cfg.get("info", "nifty_no_trade_zones"))
lst_crude_ltp = []
lst_nifty_ltp = []
socket_opened = False
# Counters for dataframe indexes
df_nifty_cnt = 0
df_nifty_med_cnt = 0
df_crude_cnt = 0
df_crude_med_cnt = 0
df_cols = ["cur_HHMM","open","high","low","close","signal","sl"] # v1.1 added signal column
df_nifty = pd.DataFrame(data=[],columns=df_cols)
df_crude = pd.DataFrame(data=[],columns=df_cols) # Low - to store 2/3 mins level data
df_crude_med = pd.DataFrame(data=[],columns=df_cols) # Medium - to store 4/6 mins level data crude
df_nifty_med = pd.DataFrame(data=[],columns=df_cols) # Medium - to store 4/6 mins level data nifty
# --------------- Call Initialization functions ------------------------
# Load previous day data files, last 10 rows
# Maybe we can put this into a load procedure
try:
# CRUDE previous data load
if int(datetime.datetime.now().strftime("%H%M")) < 905:
# 1. --- Read from previous day. In case of rerun or failures do not load previous day
# Can clear the prameter file_nifty in the ab.ini if previous day data is not required
if enable_MCX_data and file_crude.strip()!="":
iLog("Reading previous 40 period data from " + file_crude)
#May need try/catch due to copy of ini file or failed runs
df_crude = pd.read_csv(file_crude).tail(40)
df_crude.reset_index(drop=True, inplace=True) # To reset index from 0 to 9 as tail gets the last 10 indexes
df_crude_cnt = len(df_crude.index)
# iLog("df_crude_cnt=" + str(df_crude_cnt))
if enable_MCX_data and file_crude_med.strip()!="":
iLog("Reading previous 40 period data from " + file_crude_med)
#May need try/catch due to copy of ini file or failed runs
df_crude_med = pd.read_csv(file_crude_med).tail(40)
df_crude_med.reset_index(drop=True, inplace=True) # To reset index from 0 to 9 as tail gets the last 10 indexes
df_crude_med_cnt = len(df_crude_med.index)
# iLog("df_crude_med_cnt=" + str(df_crude_med_cnt))
# NIFTY previous data load and update of nifty/crude current contract symbol in ab.ini
# if True:
if int(datetime.datetime.now().strftime("%H%M")) < 915:
# 1. --- Read from previous day. In case of rerun or failures do not load previous day
# Can clear the prameter file_nifty in the ab.ini if previous day data is not required
if enable_NFO_data and file_nifty.strip()!="":
iLog("Reading previous 40 period data from " + file_nifty)
#May need try/catch due to copy of ini file or failed runs
df_nifty = pd.read_csv(file_nifty).tail(40)
df_nifty.reset_index(drop=True, inplace=True) # To reset index from 0 to 9 as tail gets the last 10 indexes
df_nifty_cnt = len(df_nifty.index)
# iLog("df_nifty_cnt=" + str(df_nifty_cnt))
if enable_NFO_data and file_nifty_med.strip()!="":
iLog("Reading previous 40 period data from " + file_nifty_med)
df_nifty_med = pd.read_csv(file_nifty_med).tail(40)
df_nifty_med.reset_index(drop=True, inplace=True)
df_nifty_med_cnt = len(df_nifty_med.index)
# iLog("df_nifty_med_cnt=" + str(df_nifty_med_cnt))
# 2. --- Update nifty or crude symbol in ab.ini
iLog("Running contract expiry checks.")
ab_lib.update_contract_symbol()
cfg.read(INI_FILE) #28-aug-2020 program failed due to picking up of old nifty contract symbol
nifty_symbol = cfg.get("info", "nifty_symbol")
crude_symbol = cfg.get("info", "crude_symbol")
except Exception as ex:
iLog("Loading previous day data, Exception occured = " + str(ex),3)
# Removed
# df_cols = ["cur_HHMM","open","high","low","close"] # v1.1 Reset to list of columns required for ohlc value assignment
lst_crude_table = [] # index,open,high,low,close
lst_nifty = []
cur_min = 0
flg_min = 0
flg_med_nifty = 0 # Flag for avoiding consecutive orders when medium signal is generated
flg_med_crude = 0
MTM = 0.0 # Float
pos_crude = 0 # current crude position
pos_nifty = 0 # current nifty position
super_trend_n = [] # Supertrend list Nifty
super_trend = [] # Supertrend list Crude
interval = olhc_duration # Time interval of candles in minutes; 2
processNiftyEOD = False # Process pending Nifty order cancellation and saving of df data; Flag to run procedure only once
processCrudeEOD = False # Process pending Crude order cancellation; Flag to run procedure only once
export_data = 0 # Realtime export of crude and nifty dataframe; triggered through .ini; reset to 0 after export
############################################################################
# Functions
############################################################################
def get_realtime_config():
'''This procedure can be called during execution to get realtime values from the .ini file'''
global tradeNFO, tradeMCX, enableBO2_crude, enableBO2_nifty, enableBO3_nifty, cfg, nifty_sl\
,crude_sl, export_data, sl_buffer, nifty_ord_type, crude_ord_type, mtm_sl, mtm_target\
,nifty_ord_exec_level1,crude_ord_exec_level1
cfg.read(INI_FILE)
tradeNFO = int(cfg.get("realtime", "tradeNFO")) # True = 1 (or non zero) False=0
tradeMCX = int(cfg.get("realtime", "tradeMCX")) # True = 1 (or non zero) False=0
enableBO2_nifty = int(cfg.get("realtime", "enableBO2_nifty")) # True = 1 (or non zero) False=0
enableBO3_nifty = int(cfg.get("realtime", "enableBO3_nifty")) # True = 1 (or non zero) False=0
enableBO2_crude = int(cfg.get("realtime", "enableBO2_crude")) # True = 1 (or non zero) False=0
nifty_sl = float(cfg.get("realtime", "nifty_sl")) #20.0
crude_sl = float(cfg.get("realtime", "crude_sl")) #15.0
export_data = float(cfg.get("realtime", "export_data"))
mtm_sl = float(cfg.get("realtime", "mtm_sl"))
mtm_target = float(cfg.get("realtime", "mtm_target"))
#print(enableBO2,enableBO3,tradeNFO,tradeMCX,flush=True)
sl_buffer = int(cfg.get("realtime", "sl_buffer"))
nifty_ord_type = cfg.get("realtime", "nifty_ord_type") # BO / MIS
crude_ord_type = cfg.get("realtime", "crude_ord_type") # MIS / BO
nifty_ord_exec_level1 = float(cfg.get("realtime", "nifty_ord_exec_level1"))
crude_ord_exec_level1 = float(cfg.get("realtime", "crude_ord_exec_level1"))
def savedata(flgUpdateConfigFile=True):
'''flgUpdateConfigFile = True Updates datafilename in the .ini file for nextday reload.
In case of intermediary exports you may not want to update the datafile in the .ini file'''
iLog("In savedata(). Exporting dataframes to .csv files.",6) # Log as activity
try:
ts_ext = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + ".csv"
if enable_NFO_data:
file_nifty = "./data/NIFTY_" + ts_ext
file_nifty_med = "./data/NIFTY_MED_" + ts_ext
df_nifty.to_csv(file_nifty,index=False)
df_nifty_med.to_csv(file_nifty_med,index=False)
if enable_MCX_data:
file_crude = "./data/CRUDE_" + ts_ext
file_crude_med = "./data/CRUDE_MED_" + ts_ext
df_crude.to_csv(file_crude,index=False)
df_crude_med.to_csv(file_crude_med,index=False)
# Save nifty and crude filenames for use in next day to load last 10 rows
if flgUpdateConfigFile :
if enable_NFO_data:
cfg.set("info","file_nifty",file_nifty)
cfg.set("info","file_nifty_med",file_nifty_med)
if enable_MCX_data:
cfg.set("info","file_crude",file_crude)
cfg.set("info","file_crude_med",file_crude_med)
with open('ab.ini', 'w') as configfile:
cfg.write(configfile)
configfile.close()
except Exception as ex:
iLog("In savedata(). Exception occured = " + str(ex),3)
def squareOff_MIS(buy_sell,ins_scrip,qty, order_type = OrderType.Market, limit_price=0.0):
'''Square off MIS positions at EoD or when mtm limit is reached. Also used for placing Market orders.
buy_sell = TransactionType.Buy/TransactionType.Sell
order_type = OrderType.StopLossLimit Default is Market order
limit_price = limit price in case SL order needs to be placed
'''
global alice
if limit_price > 1 :
trigger_price = limit_price
else:
trigger_price = None
try:
ord_obj=alice.place_order(transaction_type = buy_sell,
instrument = ins_scrip,
quantity = qty,
order_type = order_type,
product_type = ProductType.Intraday,
price = limit_price,
trigger_price = trigger_price,
stop_loss = None,
square_off = None,
trailing_sl = None,
is_amo = False)
strMsg = "In squareOff_MIS(): buy_sell={},ins_scrip={},qty={},order_type={},limit_price={}".format(buy_sell,ins_scrip,qty,order_type,limit_price)
iLog(strMsg,6,sendTeleMsg=True)
except Exception as ex:
iLog("Exception occured in squareOff_MIS():"+str(ex),3)
return ord_obj
def buy_signal(ins_scrip,qty,limit_price,stop_loss_abs,target_abs,trailing_sl_abs,product_type=ProductType.BracketOrder):
global alice
#ord=
#{'status': 'success', 'message': 'Order placed successfully', 'data': {'oms_order_id': '200416000176487'}}
#{'status': 'error', 'message': 'Error Occurred :Trigger price cannot be greater than Limit Price', 'data': {}}
#ord1['status']=='success'
#print(ord['data']['oms_order_id'])
try:
ord_obj=alice.place_order(transaction_type = TransactionType.Buy,
instrument = ins_scrip,
quantity = qty,
order_type = OrderType.Limit,
product_type = product_type,
price = limit_price,
trigger_price = limit_price,
stop_loss = stop_loss_abs,
square_off = target_abs,
trailing_sl = trailing_sl_abs,
is_amo = False)
except Exception as ex:
# print("Exception occured in buy_signal():",ex,flush=True)
#ord_obj={'status': 'error'} not required as api gives this in case of actual error
#print("buy_signal():ins_scrip,qty,limit_price,stop_loss_abs,target_abs,trailing_sl_abs:",ins_scrip,qty,limit_price,stop_loss_abs,target_abs,trailing_sl_abs,flush=True)
iLog("Exception occured in buy_signal():"+str(ex),3)
return ord_obj
def sell_signal(ins_scrip,qty,limit_price,stop_loss_abs,target_abs,trailing_sl_abs,product_type=ProductType.BracketOrder):
global alice
try:
ord_obj=alice.place_order(transaction_type = TransactionType.Sell,
instrument = ins_scrip,
quantity = qty,
order_type = OrderType.Limit,
product_type = product_type,
price = limit_price,
trigger_price = limit_price,
stop_loss = stop_loss_abs,
square_off = target_abs,
trailing_sl = trailing_sl_abs,
is_amo = False)
except Exception as ex:
# print("Exception occured in sell_signal():",ex,flush=True)
iLog("Exception occured in sell_signal():"+str(ex),3)
#print("sell_signal():ins_scrip,qty,limit_price,stop_loss_abs,target_abs,trailing_sl_abs:",ins_scrip,qty,limit_price,stop_loss_abs,target_abs,trailing_sl_abs,flush=True)
return ord_obj
def buy_crude(strMsg):
global df_crude
df_crude.iat[-1,5]="B" # v1.1 set signal column value
lt_price, crude_sl = get_trade_price("CRUDE","BUY",crude_ord_exec_level1) # Get trade price and SL for BO1
df_crude.iat[-1,6] = crude_sl
strMsg = strMsg + " Limit Price=" + str(lt_price) + " SL=" + str(crude_sl)
if not tradeMCX:
strMsg = strMsg + " In buy_crude(): tradeMCX=0. Order will not be executed."
iLog(strMsg,2,sendTeleMsg=True)
return
if not check_trade_time_zone("CRUDE"):
strMsg = strMsg + " In buy_crude(): No trade time zone. Order will not be executed."
iLog(strMsg,2,sendTeleMsg=True)
return
# position_crude = get_position('CRUDE')
# print("pos_crude=",pos_crude)
if pos_crude > 0 : # Position updated in MTM check
strMsg = "buy_crude() BO1 Position already exists. " + strMsg #do not buy if position already exists;
else:
if trade_limit_reached("CRUDE"):
strMsg = strMsg + "In buy_crude().Trade limit reached."
iLog(strMsg,2,sendTeleMsg=True)
return
# if check_pending_orders("CRUDE","BUY"):
# iLog("Pending CRUDE BUY Order exists. Cancelling BUY Orders.")
# close_all_orders("NIFTY","BUY")
# else:
# iLog("Cancelling and CRUDE SELL Orders if exists.")
# close_all_orders("CRUDE","SELL")
close_all_orders("CRUDE")
if crude_ord_type == "MIS" :
# If not first order, make it double qty
if pos_crude == 0 :
crude_ord_qty = crude_bo1_qty
else:
crude_ord_qty = crude_bo1_qty * 2
#---- Intraday order (MIS)
# order = buy_signal(ins_crude, crude_ord_qty, lt_price, crude_sl, crude_tgt1, crude_tsl,ProductType.Intraday)
# Place a market type buy order using squareOff_MIS()
order = squareOff_MIS(TransactionType.Buy, ins_crude,crude_ord_qty)
if order['status'] == 'success':
strMsg = strMsg + " MIS order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' buy_crude() MIS Order Failed.' + order['message']
elif crude_ord_type == "BO" :
#---- First Bracket order for initial target
order = buy_signal(ins_crude, crude_bo1_qty, lt_price, crude_sl, crude_tgt1, crude_tsl)
if order['status']=='success':
# buy_order1_crude = order['data']['oms_order_id']
strMsg = strMsg + " 1st BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' buy_crude() 1st BO Failed.'+ order['message']
#---- Second Bracket order for open target
if enableBO2_crude:
lt_price, crude_sl = get_trade_price("CRUDE","BUY",crude_ord_exec_level2) # Get trade price and SL for BO2
order = buy_signal(ins_crude, crude_bo2_qty, lt_price, crude_sl, crude_tgt2, crude_tsl)
strMsg = strMsg + " BO2 Limit Price=" + str(lt_price) + " SL=" + str(crude_sl)
if order['status']=='success':
# buy_order2_crude = order['data']['oms_order_id']
strMsg = strMsg + " 2nd BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' buy_crude() 2nd BO Failed.'+ order['message']
#---- Third Bracket order for open target
if enableBO3_crude:
lt_price, crude_sl = get_trade_price("CRUDE","BUY",crude_ord_exec_level3) # Get trade price and SL for BO3
order = buy_signal(ins_crude, crude_bo3_qty, lt_price, crude_sl, crude_tgt3, crude_tsl)
strMsg = strMsg + " BO3 Limit Price=" + str(lt_price) + " SL=" + str(crude_sl)
if order['status']=='success':
strMsg = strMsg + " 3rd BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg=strMsg + ' buy_crude() 3rd BO Failed.' + order['message']
iLog(strMsg,sendTeleMsg=True)
# Not required as its already called above
#-- Exit from sell order if any
# close_all_orders("CRUDE","SELL")
# strMsg = "CRUDE open SELL orders cancelled."
# iLog(strMsg,sendTeleMsg=True)
def sell_crude(strMsg):
global df_crude
df_crude.iat[-1,5] = "S" # v1.1 set signal column value
lt_price, crude_sl = get_trade_price("CRUDE","SELL",crude_ord_exec_level1) # Get trade price and SL for BO1
df_crude.iat[-1,6] = crude_sl # v3.7 set sl column value. This is only for BO1; rest BOs will different SLs
strMsg = strMsg + " Limit Price=" + str(lt_price) + " SL=" + str(crude_sl)
if not tradeMCX:
strMsg = strMsg + " In sell_crude(): tradeMCX=0. Order not initiated."
iLog(strMsg,2,sendTeleMsg=True)
return
if not check_trade_time_zone("CRUDE"):
strMsg = strMsg + " In sell_crude(): No trade time zone. Order not initiated."
iLog(strMsg,2,sendTeleMsg=True)
return
# position_crude = get_position('CRUDE')
print("pos_crude=",pos_crude)
#---- First Bracket order for initial target
if pos_crude < 0 : # Position updated in MTM check
strMsg = "sell_crude(): BO1 Position already exists. " + strMsg #do not buy if position already exists;
else:
if trade_limit_reached("CRUDE"):
strMsg = strMsg + "In sell_crude(): Trade limit reached."
iLog(strMsg,2,sendTeleMsg=True)
return
# if check_pending_orders("CRUDE","SELL"):
# iLog("Pending CRUDE SELL Order exists. Cancelling SELL Orders.")
# close_all_orders("NIFTY","SELL")
# else:
# iLog("Cancelling and CRUDE BUY Orders if exists.")
# close_all_orders("CRUDE","BUY")
close_all_orders("CRUDE")
if crude_ord_type == "MIS" :
# If not first order, make it double qty
if pos_crude == 0 :
crude_ord_qty = crude_bo1_qty
else:
crude_ord_qty = crude_bo1_qty * 2
#---- Intraday order (MIS)
# order = sell_signal(ins_crude,crude_ord_qty,lt_price,crude_sl,crude_tgt1,crude_tsl,ProductType.Intraday)
# Place a market order using squareOff_MIS
order = squareOff_MIS(TransactionType.Sell, ins_crude,crude_ord_qty)
if order['status'] == 'success':
strMsg = strMsg + " MIS order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' sell_crude() MIS Order Failed.' + order['message']
elif crude_ord_type == "BO" :
#---- First Bracket order for initial target
order = sell_signal(ins_crude,crude_bo1_qty,lt_price,crude_sl,crude_tgt1,crude_tsl)
if order['status']=='success':
# sell_order1_crude = order['data']['oms_order_id']
strMsg = strMsg + " 1st BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' sell_crude() 1st BO Failed.'+ order['message']
#---- Second Bracket order for open target
if enableBO2_crude:
lt_price, crude_sl = get_trade_price("CRUDE","SELL",crude_ord_exec_level2) # Get trade price and SL for BO2
order = sell_signal(ins_crude,crude_bo2_qty,lt_price,crude_sl,crude_tgt2,crude_tsl)
strMsg = strMsg + " BO2 Limit Price=" + str(lt_price) + " SL=" + str(crude_sl)
if order['status']=='success':
# sell_order2_crude = order['data']['oms_order_id']
strMsg = strMsg + " 2nd BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' sell_crude() 2nd BO Failed.'+ order['message']
#---- Third Bracket order for open target
if enableBO3_crude:
lt_price, crude_sl = get_trade_price("CRUDE","SELL",crude_ord_exec_level3) # Get trade price and SL for BO3
order = sell_signal(ins_crude,crude_bo3_qty,lt_price,crude_sl,crude_tgt3,crude_tsl)
strMsg = strMsg + " BO3 Limit Price=" + str(lt_price) + " SL=" + str(crude_sl)
if order['status'] == 'success':
# sell_order2_crude = order['data']['oms_order_id']
strMsg = strMsg + " 3rd BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' sell_crude() 3rd BO Failed.'+ order['message']
iLog(strMsg,sendTeleMsg=True)
# Not required as close_all_orders(CRUDE) is already called
#-- Exit from buy order if any
# close_all_orders("CRUDE","BUY")
# strMsg = "CRUDE open BUY orders cancelled."
# iLog(strMsg,sendTeleMsg=True)
# #if position_crude>0:
# try:
# strMsg="No crude buy order positions to cancel."
# if buy_order1_crude:
# cancel_status=alice.cancel_order(buy_order1_crude)
# strMsg="Cancelling CRUDE BUY OrderID="+buy_order1_crude+' cancel_status=' + cancel_status['status']
# buy_order1_crude=''
# if buy_order2_crude:
# cancel_status=alice.cancel_order(buy_order2_crude)
# strMsg=strMsg +", OrderID=" + buy_order2_crude + " cancel_status=" + cancel_status['status']
# buy_order2_crude=''
# except Exception as ex:
# strMsg='cancel_order() in sell_crude() failed.' + str(ex)
# iLog(strMsg,sendTeleMsg=True)
def buy_nifty(strMsg):
global df_nifty
df_nifty.iat[-1,5] = "B" # v1.1 set signal column value
lt_price, nifty_sl = get_trade_price("NIFTY","BUY",nifty_ord_exec_level1) # Get trade price and SL for BO1
df_nifty.iat[-1,6] = nifty_sl # v3.7 set sl column value. This is only for BO1; rest BOs will different SLs
strMsg = strMsg + " Limit Price=" + str(lt_price) + " SL=" + str(nifty_sl)
if not tradeNFO:
strMsg = strMsg + " buy_nifty(): tradeNFO=0. Order not initiated."
iLog(strMsg,2,sendTeleMsg=True)
return
if not check_trade_time_zone("NIFTY"):
strMsg = strMsg + " buy_nifty(): No trade time zone. Order not initiated."
iLog(strMsg,2,sendTeleMsg=True)
return
# position_nifty = get_position('NIFTY')
# if position_nifty!=0 : position_nifty=position_nifty/75 # Calculate Nifty number of Positions
if pos_nifty > 0: # Position updates in MTM check
strMsg = "buy_nifty(): BO1 Position already exists. " + strMsg #do not buy if position already exists;
else:
if trade_limit_reached("NIFTY"):
strMsg = strMsg + "buy_nifty(): NIFTY Trade limit reached."
iLog(strMsg,2,sendTeleMsg=True)
return
# may not be required as in case of positions you have to cancel it
# and in case of pending also you have to cancel it and create fresh orders
# if check_pending_orders("NIFTY","BUY"):
# iLog("Pending BUY Order exists. Cancelling BUY Orders.")
# close_all_orders("NIFTY","BUY")
# else:
# iLog("Cancelling any SELL Orders if exists.")
# close_all_orders("NIFTY","SELL")
# Cancel pending buy orders and close existing sell orders if any
close_all_orders("NIFTY")
if nifty_ord_type == "MIS" :
if pos_nifty == 0 :
nifty_ord_qty = nifty_bo1_qty
else:
nifty_ord_qty = nifty_bo1_qty * 2
#---- Intraday order (MIS) , Market Order
# order = buy_signal(ins_nifty,nifty_ord_qty,lt_price,nifty_sl,nifty_tgt1,nifty_tsl,ProductType.Intraday) #SL to be float;
order = squareOff_MIS(TransactionType.Buy, ins_nifty,nifty_ord_qty)
if order['status'] == 'success':
# sell_order1_nifty = order1['data']['oms_order_id']
strMsg = strMsg + " MIS order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' buy_nifty() MIS Order Failed.' + order['message']
elif nifty_ord_type == "BO" :
#---- First Bracket order for initial target
order = buy_signal(ins_nifty,nifty_bo1_qty,lt_price,nifty_sl,nifty_tgt1,nifty_tsl) #SL to be float;
if order['status'] == 'success' :
# buy_order1_nifty = order['data']['oms_order_id']
strMsg = strMsg + " 1st BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' buy_nifty() 1st BO Failed.' + order['message']
#---- Second Bracket order for open target
if enableBO2_nifty:
lt_price, nifty_sl = get_trade_price("NIFTY","BUY",nifty_ord_exec_level2) # Get trade price and SL for BO2
order = buy_signal(ins_nifty,nifty_bo2_qty,lt_price,nifty_sl,nifty_tgt2,nifty_tsl)
strMsg = strMsg + " BO2 Limit Price=" + str(lt_price) + " SL=" + str(nifty_sl)
if order['status'] == 'success':
# buy_order2_nifty = order['data']['oms_order_id']
strMsg = strMsg + " 2nd BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg=strMsg + ' buy_nifty() 2nd BO Failed.' + order['message']
#---- Third Bracket order for open target
if enableBO3_nifty:
lt_price, nifty_sl = get_trade_price("NIFTY","BUY",nifty_ord_exec_level3) # Get trade price and SL for BO3
order = buy_signal(ins_nifty,nifty_bo3_qty,lt_price,nifty_sl,nifty_tgt3,nifty_tsl)
strMsg = strMsg + " BO3 Limit Price=" + str(lt_price) + " SL=" + str(nifty_sl)
if order['status']=='success':
# buy_order3_nifty = order['data']['oms_order_id']
strMsg = strMsg + " 3rd BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg=strMsg + ' buy_nifty() 3rd BO Failed.' + order['message']
iLog(strMsg,sendTeleMsg=True)
#-- Exit from sell order if any
# close_all_orders("NIFTY","SELL")
# strMsg = "NIFTY open SELL orders cancelled."
# iLog(strMsg,sendTeleMsg=True)
def sell_nifty(strMsg):
global df_nifty
df_nifty.iat[-1,5] = "S" # v1.1 set signal column value
lt_price, nifty_sl = get_trade_price("NIFTY","SELL",nifty_ord_exec_level1) # Get trade price and SL for BO1
df_nifty.iat[-1,6] = nifty_sl # v3.7 set sl column value. This is only for BO1; rest BOs will different SLs
strMsg = strMsg + " Limit Price=" + str(lt_price) + " SL=" + str(nifty_sl)
if not tradeNFO:
strMsg = strMsg + " In sell_nifty(): tradeNFO=0. Order not initiated."
iLog(strMsg,2,sendTeleMsg=True)
return
if not check_trade_time_zone("NIFTY"):
strMsg = strMsg + " In sell_nifty(): No trade time zone. Order not initiated."
iLog(strMsg,2,sendTeleMsg=True)
return
# position_nifty = get_position('NIFTY')
# if position_nifty!=0 : position_nifty=position_nifty/75
if pos_nifty < 0 : # Position updated in MTM check
strMsg = "sell_nifty() BO1 Position already exists. "+strMsg #do not buy if position already exists;
else:
if trade_limit_reached("NIFTY"):
strMsg = strMsg + "In sell_nifty(). NIFTY Trade limit reached."
iLog(strMsg,2,sendTeleMsg=True)
return
# if check_pending_orders("NIFTY","SELL"):
# iLog("Pending SELL Order exists. Cancelling SELL Orders.")
# close_all_orders("NIFTY","SELL")
# else:
# iLog("Cancelling any BUY Orders if exists.")
# close_all_orders("NIFTY","BUY")
# Cancel pending buy orders and close existing sell orders if any
close_all_orders("NIFTY")
if nifty_ord_type == "MIS" :
if pos_nifty == 0 :
nifty_ord_qty = nifty_bo1_qty
else:
nifty_ord_qty = nifty_bo1_qty * 2
#---- Intraday order (MIS) , Market Order
# order = sell_signal(ins_nifty,nifty_ord_qty,lt_price,nifty_sl,nifty_tgt1,nifty_tsl,ProductType.Intraday) #SL to be float
order = squareOff_MIS(TransactionType.Sell, ins_nifty,nifty_ord_qty)
if order['status'] == 'success':
# sell_order1_nifty = order1['data']['oms_order_id']
strMsg = strMsg + " MIS order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' sell_nifty() MIS Order Failed.' + order['message']
elif nifty_ord_type == "BO" :
#---- First Bracket order for initial target
order = sell_signal(ins_nifty,nifty_bo1_qty,lt_price,nifty_sl,nifty_tgt1,nifty_tsl) #SL to be float
if order['status'] == 'success':
# sell_order1_nifty = order1['data']['oms_order_id']
strMsg = strMsg + " 1st BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' sell_nifty() 1st BO Failed.' + order['message']
#---- Second Bracket order for 2nd target
if enableBO2_nifty:
lt_price, nifty_sl = get_trade_price("NIFTY","SELL",nifty_ord_exec_level2) # Get trade price and SL for BO2
order = sell_signal(ins_nifty,nifty_bo2_qty,lt_price,nifty_sl,nifty_tgt2,nifty_tsl)
strMsg = strMsg + " BO2 Limit Price=" + str(lt_price) + " SL=" + str(nifty_sl)
if order['status'] == 'success':
# sell_order2_nifty = order['data']['oms_order_id']
strMsg = strMsg + " 2nd BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' sell_nifty() 2nd BO Failed.' + order['message']
#---- Third Bracket order for open target
if enableBO3_nifty:
lt_price, nifty_sl = get_trade_price("NIFTY","SELL",nifty_ord_exec_level3) # Get trade price and SL for BO3
order = sell_signal(ins_nifty,nifty_bo3_qty,lt_price,nifty_sl,nifty_tgt3,nifty_tsl)
strMsg = strMsg + " BO3 Limit Price=" + str(lt_price) + " SL=" + str(nifty_sl)
if order['status'] == 'success':
# sell_order3_nifty = order['data']['oms_order_id']
strMsg = strMsg + " 3rd BO order_id=" + str(order['data']['oms_order_id'])
else:
strMsg = strMsg + ' sell_nifty() 3rd BO Failed.' + order['message']
iLog(strMsg,sendTeleMsg=True)
#-- Exit from buy order if any
close_all_orders("NIFTY","BUY")
strMsg = "NIFTY open BUY orders cancelled."
iLog(strMsg,sendTeleMsg=True)
def subscribe_ins():
global alice,ins_nifty,ins_crude
try:
if enable_NFO_data : alice.subscribe(ins_nifty, LiveFeedType.COMPACT)
if enable_MCX_data : alice.subscribe(ins_crude, LiveFeedType.COMPACT)
except Exception as ex:
iLog("subscribe_ins(): Exception="+ str(ex),3)
iLog("subscribe_ins().")
def close_all_orders(crude_nifty="ALL",buy_sell="ALL",ord_open_time=0):
'''Cancel pending orders. crude_nifty=ALL/CRUDE/NIFTY , buy_sell = ALL/BUY/SELL'''
# print(datetime.datetime.now(),"In close_all_orders().",crude_nifty,flush=True)
#Square off CRUDE/NIFTY MIS Positions if any
if crude_nifty=='NIFTY' and nifty_ord_type == "MIS":
if pos_nifty > 0 :
squareOff_MIS(TransactionType.Sell, ins_nifty,pos_nifty)
elif pos_nifty < 0 :
squareOff_MIS(TransactionType.Buy, ins_nifty, abs(pos_nifty))
if crude_nifty=='CRUDE' and crude_ord_type == "MIS":
# Squareoff CRUDE/NIFTY MIS Positions
if pos_crude > 0 :
squareOff_MIS(TransactionType.Sell, ins_crude, pos_crude)
elif pos_crude < 0 :
squareOff_MIS(TransactionType.Buy, ins_crude, abs(pos_crude))
# Get pending orders
try:
orders = alice.get_order_history()['data']['pending_orders'] #Get all orders
if not orders:
# print(datetime.datetime.now(),"In close_all_orders(). No Pending Orders found.",crude_nifty,flush=True)
iLog("close_all_orders(): No Pending Orders found for "+ str(crude_nifty))
return
# Else is captured below exception
except Exception as ex:
orders = None
# print("In close_all_orders(). Exception="+ str(ex),flush=True)
iLog("close_all_orders(): Exception="+ str(ex),3)
return
if crude_nifty == "ALL":
# If this proc is called in each interval, Check for order open time and leg indicator is blank for main order
if ord_open_time > 0 :
today = datetime.datetime.now()
for c_order in orders:
diff = today - datetime.datetime.fromtimestamp(c_order['order_entry_time'])
# print("diff.total_seconds()=",diff.total_seconds(), "c_order['leg_order_indicator']=",c_order['leg_order_indicator'], flush=True)
if (c_order['leg_order_indicator'] == '') and (diff.total_seconds() / 60) > ord_open_time :
iLog("close_all_orders(): Cancelling order due to order open limit time crossed for Ord. no. : " + c_order['oms_order_id'],sendTeleMsg=True)
alice.cancel_order(c_order['oms_order_id'])
else:
#Cancel all open orders
iLog("close_all_orders(): Cancelling all order " + c_order['oms_order_id'])
alice.cancel_all_orders()
else:
for c_order in orders:
#if c_order['leg_order_indicator']=='' then its actual pending order not leg order
if crude_nifty == c_order['trading_symbol'][:5]:
if buy_sell == "ALL" :
iLog("close_all_orders(): Cancelling order "+c_order['oms_order_id'])
alice.cancel_order(c_order['oms_order_id'])
elif buy_sell == c_order['transaction_type']:
iLog("close_all_orders(): Cancelling order "+c_order['oms_order_id'])
alice.cancel_order(c_order['oms_order_id'])