-
Notifications
You must be signed in to change notification settings - Fork 6
/
app.py
1530 lines (1256 loc) · 65.5 KB
/
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
# import from TWS API
from ibapi.client import EClient # needs to be inherited
from ibapi.wrapper import EWrapper # needs to be inherited
from ibapi.contract import Contract
from ibapi.order import Order
# import custom code
from filled_orders import update_filled_orders
from acc_summary import get_acc_summary, update_acc_pnl, post_acc_pnl
from current_positions import get_position, update_positions
from open_orders import get_order_position_except_manual, get_order_id, get_order_status
from dublicate_orders import get_dublicate_orders
# import others
import threading
import time
from datetime import datetime
import pandas as pd
import socket
import asyncio, requests
import nest_asyncio # patches asyncio to allow nested use of asyncio
import logging.handlers
from pathlib import Path
import configparser
# inherit EWrapper and EClient classes, and edit instance methods
class TradingApp(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.errors_received = pd.DataFrame(
columns=["reqId", "errorCode", "errorString"]
)
self.order_df = pd.DataFrame(
columns=[
"PermId",
"ClientId",
"OrderId",
"Account",
"Symbol",
"SecType",
"Exchange",
"Action",
"OrderType",
"TotalQty",
"CashQty",
"LmtPrice",
"AuxPrice",
"Status",
]
)
def error(self, reqId, errorCode, errorString):
print("Error {} {} {}".format(reqId, errorCode, errorString))
logger.error("Error {} {} {}".format(reqId, errorCode, errorString))
self.errors_received.loc[len(self.errors_received)] = [
reqId,
errorCode,
errorString,
]
def nextValidId(self, orderId):
super().nextValidId(orderId)
# print("NextValidId:", orderId)
self.nextValidOrderId = orderId
def openOrder(self, orderId, contract, order, orderState):
super().openOrder(orderId, contract, order, orderState)
dictionary = {
"PermId": order.permId,
"ClientId": order.clientId,
"OrderId": orderId,
"Account": order.account,
"Symbol": contract.symbol,
"SecType": contract.secType,
"Exchange": contract.exchange,
"Action": order.action,
"OrderType": order.orderType,
"TotalQty": order.totalQuantity,
"CashQty": order.cashQty,
"LmtPrice": order.lmtPrice,
"AuxPrice": order.auxPrice,
"Status": orderState.status,
}
self.order_df = self.order_df.append(dictionary, ignore_index=True)
# socket function to handle winerror 1003 problem
def _socketShutdown(self):
self.conn.lock.acquire()
try:
if self.conn.socket is not None:
self.conn.socket.shutdown(socket.SHUT_WR)
finally:
self.conn.lock.release()
# added time_str to make it easy to timestamp print statements
def time_str():
return datetime.now().strftime("%H:%M:%S.%f")
def websocket_con():
app.run()
# creating object of the Contract class for US stocks
# SMART is selected as default, but can be problematic with some certain stocks
# In case of ERROR 200 order should be rerouted to another exchange (exp: ISLAND)
def contractIB(
symbol, sec_type="STK", currency="USD", exchange="SMART", primaryExchange="ISLAND"
):
contract = Contract()
contract.symbol = symbol
contract.secType = sec_type
contract.currency = currency
contract.exchange = exchange
# Specify the Primary Exchange attribute to avoid contract ambiguity
contract.primaryExchange = primaryExchange
return contract
# creating object of the limit order class
# not used at the moment, kept for later use
def limitOrder(direction, quantity, lmt_price, tif="DAY"):
order = Order()
order.eTradeOnly = False
order.firmQuoteOnly = False
order.action = direction
order.orderType = "LMT"
order.totalQuantity = quantity
order.lmtPrice = lmt_price
order.account = ACCOUNT_NUMBER # Edit for other accounts
order.tif = tif
return order
# creating object of the market order class
def marketOrder(direction, quantity, tif="DAY"):
order = Order()
order.eTradeOnly = False
order.firmQuoteOnly = False
order.action = direction
order.orderType = "MKT"
order.totalQuantity = quantity
order.account = ACCOUNT_NUMBER # Edit for other accounts
order.tif = tif
return order
# creating object of the relative order class
def relativeOrder(direction, quantity, tif="DAY"):
order = Order()
order.eTradeOnly = False
order.firmQuoteOnly = False
order.action = direction
order.orderType = "REL" # https://www.interactivebrokers.com/en/index.php?f=613
order.totalQuantity = quantity
order.account = ACCOUNT_NUMBER
order.tif = tif
# you can define an absolute cap that works like a limit price,
# and will prevent your order from being executed above or below a specified price level
# Orders with a "0" offset are submitted as limit orders at the best bid/ask
# and will move up and down with the market to continue to match the inside quote.
# order.auxPrice = offsetAmount
order.auxPrice = "0"
# enable if you want to bid/offer more aggresive price(such as 0.2% better than best bid/offer)
# order.percentOffset = "0.002"
return order
# TODO: problem creating this type of order. Gettin Error 387
# creating object of the relative passive order class
# Passive Relative orders provide a means for traders to seek a less aggressive price than the National Best Bid and Offer (NBBO)
# The Passive Relative order is similar to the Relative/Pegged-to-Primary order,
# except that the Passive relative subtracts the offset from the bid and the Relative adds the offset to the bid.
def relativepassiveOrder(direction, quantity):
order = Order()
order.eTradeOnly = False
order.firmQuoteOnly = False
order.action = direction
order.orderType = "PASSV REL"
order.totalQuantity = quantity
order.account = ACCOUNT_NUMBER
order.auxPrice = "0"
# order.percentOffset = "0.002"
return order
# TODO: has to set a limit price for this type of order
def peggedtomidOrder(direction, quantity, limitPrice):
order = Order()
order.eTradeOnly = False
order.firmQuoteOnly = False
order.action = direction
order.orderType = "PEG MID"
order.totalQuantity = quantity
order.account = ACCOUNT_NUMBER
order.auxPrice = "0"
order.lmtPrice = limitPrice
return order
# Create a function to simplify order creation
def MyOrder(**order_details):
print(order_details["direction"].upper())
print(order_details["order_quantity"])
print(order_details["order_type"])
order_direction = order_details["direction"].upper()
order_quantity = order_details["order_quantity"]
order_type = order_details["order_type"]
# relative order as default
my_order = relativeOrder(order_direction, abs(order_quantity))
if order_type == "MARKET":
my_order = marketOrder(order_direction, abs(order_quantity))
elif order_type == "LIMIT" and "limit_price" in order_details:
order_price = order_details["limit_price"]
print(order_details["limit_price"])
my_order = limitOrder(order_direction, abs(order_quantity), order_price)
return my_order
# main function to check webhooks and send orders.
# get waiting trade signals dictionary from the web backend.
# loosely coupled architecture is used, when server app is down or there is no connection to it
# ,then the trading signals start waiting in a 'message queue'
# waiting signals are handled with LIFO method.
async def check_signals():
# define global variables
global app
response_list_dic = []
signal_dic = {}
# print checking message and time
print(f"\n{time_str()} - checking for tradingview webhook signals")
try:
response = requests.get(API_GET_SIGNAL_WAITING, timeout=5)
response_list_dic = response.json()[
"signals"
] # creates a list of dictionaries from json
except requests.Timeout:
# back off and retry
print(f"\n{time_str()} - timeout error")
pass
except requests.ConnectionError:
print(f"\n{time_str()} - connection error")
pass
if response_list_dic:
print(f"\n{time_str()} - order(waiting or rerouted) received from the server")
logger.info("order(waiting or rerouted) received from the server")
# define variables to update in the loop
trade_confirm = True
cancel_order = False
status_msg = ""
synced_order = False
# 1-check if there are more than one orders waiting for the same ticker
duplicate_orders = get_dublicate_orders(response_list_dic)
if duplicate_orders:
print(f"\n{time_str()} - duplicate orders detected")
logger.warning("duplicate orders detected")
# cancel duplicate waiting orders, keep the most recent
for i in range(len(duplicate_orders)):
api_url = API_GET_SIGNAL + str(duplicate_orders[i])
try:
signal_dic = requests.get(api_url, timeout=5).json()
except requests.Timeout:
print(f"\n{time_str()} - timeout error (dub. order)")
pass
except requests.ConnectionError:
print(f"\n{time_str()} - connection error (dub. order)")
pass
signal_dic["passphrase"] = PASSPHRASE
signal_dic["order_status"] = "canceled"
signal_dic["status_msg"] = "duplicate order"
response = requests.put(API_PUT_SIGNAL, json=signal_dic)
if response.status_code == 200:
print(
f"\n{time_str()} - duplicate order information updated for rowid:",
str(duplicate_orders[i]),
)
logger.info(
f"duplicate order information updated for rowid:{duplicate_orders[i]}"
)
else:
print(
f"\n{time_str()}- duplicate order information update problem; code:",
response.status_code,
)
logger.error(
f"duplicate order information update problem; code:{response.status_code}"
)
# 1-continue if no duplicate tickers
else:
# get the first available ticker dictionary in the waiting list
signal_dic = response_list_dic[0]
# assign dic values
order_status = signal_dic["order_status"]
rowid = signal_dic["rowid"]
order_action = signal_dic["order_action"]
order_contracts = signal_dic["order_contracts"]
hedge_param = signal_dic["hedge_param"]
new_order_action = "none"
# negate short positions
if signal_dic["mar_pos"] == "short":
mar_pos_size = -signal_dic["mar_pos_size"]
else:
mar_pos_size = signal_dic["mar_pos_size"]
if signal_dic["pre_mar_pos"] == "short":
pre_mar_pos_size = -signal_dic["pre_mar_pos_size"]
else:
pre_mar_pos_size = signal_dic["pre_mar_pos_size"]
print(f'\n{time_str()} - received signal (Equation:{signal_dic["ticker"]})')
logger.info(f'received signal (Equation:{signal_dic["ticker"]})')
# 2-check pyramiding (assumes fixed order size) and order validity
# pyramiding is not allowed, only one position is allowed per ticker
# order position sizes should also be valid
# check rare condition (if waiting order created due to sync)
if signal_dic["status_msg"] == "created due to sync":
status_msg = "+synced(new order)"
cancel_order = False
synced_order = True
else:
# check if order positions have value or not
if [
x
for x in (
mar_pos_size,
pre_mar_pos_size,
mar_pos_size,
pre_mar_pos_size,
)
if x is None
]:
print(f"\n{time_str()} - order positions size is missing")
logger.warning(f"order position size is missing")
cancel_order = True
status_msg = "missing position size"
# check if positions add up
if (
signal_dic["order_action"] == "buy"
and mar_pos_size != pre_mar_pos_size + order_contracts
) or (
signal_dic["order_action"] == "sell"
and mar_pos_size != pre_mar_pos_size - order_contracts
):
print(f"\n{time_str()} - order positions mismatch")
logger.warning(f"order positions mismatch")
cancel_order = True
status_msg = "position size mismatch"
# check pyramiding
elif (mar_pos_size > 0 and pre_mar_pos_size > 0) or (
mar_pos_size < 0 and pre_mar_pos_size < 0
):
cancel_order = True
status_msg = "pyramiding"
# cancel order if true
if cancel_order:
trade_confirm = False
signal_dic["passphrase"] = PASSPHRASE
signal_dic["order_status"] = "canceled"
signal_dic["status_msg"] = status_msg
response = requests.put(API_PUT_SIGNAL, json=signal_dic)
if response.status_code == 200:
print(
f"\n{time_str()} - order information ({status_msg}) updated for rowid:",
rowid,
)
logger.info(
f"order information ({status_msg}) updated for rowid:{rowid}"
)
else:
print(
f"\n{time_str()}- order information ({status_msg}) update problem; code:",
response.status_code,
)
logger.error(
f"order information ({status_msg}) updated problem; code:{response.status_code}"
)
# 3-check active orders
# only one active order is allowed at once, cancel the others
# manual orders (with IB API order ID 0) cannot be modified/cancelled from the IB API
if trade_confirm:
# TODO: check this rare error
# Error 2718 10148 OrderId 2718 that needs to be cancelled cannot be cancelled, state: PendingCancel.
# Active order canceled due to multiple active orders, ID: 2710
# get the list of active orders with the same ticker
order_id_list = get_order_id(signal_dic["ticker1"], CONNECTION_PORT)
# TODO: can you get the order id list for the order created for SYNC_PAIR and then cancel?
if len(order_id_list) > 0:
print(f"\n{time_str()} - Multiple active order detected")
logger.info("Multiple active order detected")
# IB connection parameters
app = TradingApp()
app.connect("127.0.0.1", CONNECTION_PORT, clientId=1)
# starting a separate daemon thread to execute the websocket connection
con_thread = threading.Thread(target=websocket_con, daemon=True)
con_thread.start()
time.sleep(
0.5
) # some latency added to ensure that the connection is established
if not app.isConnected():
print(
f"\n{time_str()} - Client 1 cannot establish TWS connection to cancel orders"
)
logger.warning(
"Client 1 cannot establish TWS connection to cancel orders"
)
else:
print(
f"\n{time_str()} - Client 1 established TWS connection to cancel orders"
)
logger.info(
"Client 1 established TWS connection to cancel orders"
)
# check for active orders before sending new order
for index in range(len(order_id_list)):
orderid_to_cancel = order_id_list[index]
# If there are partially filled orders, get_order_status as a list of the following:
# order_status_list[0] = remaining contacts
# order_status_list[1] = filled contracts
# order_status_list[2] = avg_price of filled order
order_status_list = get_order_status(
int(orderid_to_cancel), CONNECTION_PORT
)
if signal_dic["ticker_type"] == "pair":
orderid2_to_cancel = (
order_id_list[index] + 1
) # next order ID as the child
order_status2_list = get_order_status(
int(orderid2_to_cancel), CONNECTION_PORT
)
print(
f"\n{time_str()} - Order amount to cancel(ticker1): ",
str(order_status_list[0]),
)
print(
f"\n{time_str()} - Order amount filled (ticker1): ",
str(order_status_list[1]),
)
logger.info(
f"Order amount to cancel(ticker1):{order_status_list[0]}"
)
logger.info(
f"Order amount filled(ticker1): {order_status_list[1]}"
)
if signal_dic["ticker_type"] == "pair":
print(
f"\n{time_str()} - Order amount to cancel(ticker2): ",
str(order_status2_list[0]),
)
print(
f"\n{time_str()} - Order amount filled(ticker2): ",
str(order_status2_list[1]),
)
logger.info(
f"Order amount to cancel(ticker2:{order_status2_list[0]}"
)
logger.info(
f"Order amount filled(ticker2): {order_status2_list[1]}"
)
# update filled orders before cancellation
update_filled_orders(
CONNECTION_PORT, PASSPHRASE, API_PUT_UPDATE
)
# cancel old active order before sending new order
app.cancelOrder(orderid_to_cancel)
time.sleep(
0.5
) # some latency added to ensure that the connection is established
# updating canceled order status
send_data = {
# update fill prices
"passphrase": PASSPHRASE,
"symbol": signal_dic["ticker1"],
"order_id": orderid_to_cancel,
# indicate that this order is canceled
"cancel": True,
"price": -1, # needs any value
"filled_qty": -1, # needs any value
}
response = requests.put(API_PUT_UPDATE, json=send_data)
if response.status_code == 200:
print(
f"\n{time_str()} - Active order canceled due to multiple active orders, ID: ",
orderid_to_cancel,
)
logger.info(
f"Active order canceled due to multiple active orders, ID: {orderid_to_cancel}"
)
else:
print(
f"\n{time_str()} - an error occurred updating the order ID {orderid_to_cancel}"
)
logger.error(
f"an error occurred updating the order ID {orderid_to_cancel}"
)
# close socket connection
app._socketShutdown()
time.sleep(0.5)
app.disconnect()
# the following join will wait for the thread to end
con_thread.join()
print(
f"\n{time_str()} - TWS disconnected after processing orders"
)
logger.info("TWS disconnected after processing orders")
# 4-sync market position with the latest valid order data (sync to mar_pos_size)
# attention: manual orders are not taken into account
# calculate expected ticker position with active orders and before new(current) order is sent
# (i.e. the expected previous position)
# get current ticker portfolio position
pos_ticker1 = get_position(signal_dic["ticker1"], CONNECTION_PORT)
# get open order position
# this is a precaution: active orders should already be canceled in the previous step
order_pos_ticker1 = get_order_position_except_manual(
signal_dic["ticker1"], CONNECTION_PORT
)
# expected portfolio with active orders (without considering new(current) order)
expected_pre_mar_pos_size = order_pos_ticker1 + pos_ticker1
# keep this to be used later
old_order_contracts = order_contracts
# compare calculation to ticker's previous position,
# then sync according to market position
if expected_pre_mar_pos_size != pre_mar_pos_size:
# set current order to sync with the latest signal 'mar_pos_size'
order_contracts = int(mar_pos_size - expected_pre_mar_pos_size)
print(
f"\n{time_str()} - order contract amount changed due to sync: ",
order_contracts,
)
logger.info(
f"order contract amount changed due to sync: {order_contracts}"
)
# prepare status msg for sync
status_msg = (
"+synced("
+ str(old_order_contracts)
+ "->"
+ str(order_contracts)
+ ")"
)
if order_contracts < 0:
order_action = "sell"
elif order_contracts > 0:
order_action = "buy"
else:
# no order if zero
trade_confirm = False
# mark active order as canceled due to sync
signal_dic["passphrase"] = PASSPHRASE
signal_dic["order_status"] = "canceled"
signal_dic["status_msg"] = status_msg
response = requests.put(API_PUT_SIGNAL, json=signal_dic)
if response.status_code == 200:
print(
f"\n{time_str()} - order not created due to zero order amount after sync."
)
logger.info(
"order not created due to zero order amount after sync."
)
else:
print(
f"\n{time_str()} - an error occurred updating status after sync."
)
logger.info("an error occurred updating status after sync.")
# 4-sync cont.> sync second pair if SYNC_PAIR is activated
if SYNC_PAIR and signal_dic["ticker_type"] == "pair":
print(f"\n{time_str()} - SYNC_PAIR is active")
# get second ticker portfolio position
pos_size_ticker2 = int(
get_position(signal_dic["ticker2"], CONNECTION_PORT)
)
# get open order position for second ticker
# this is necessary, open orders for ticker2 are not cancelled before
order_pos_ticker2 = get_order_position_except_manual(
signal_dic["ticker2"], CONNECTION_PORT
)
# calculate expected and market positions, order_contracts are always positive
if signal_dic["order_action"] == "buy":
expected_pos_ticker2 = (
-int(order_contracts * float(hedge_param))
+ pos_size_ticker2
+ order_pos_ticker2
)
else:
expected_pos_ticker2 = (
int(order_contracts * float(hedge_param))
+ pos_size_ticker2
+ order_pos_ticker2
)
# calculate expected and market positions, mar_pos_size is directional
mar_pos_size_ticker2 = -int(
round(mar_pos_size * float(hedge_param))
)
new_order_contracts2 = (
mar_pos_size_ticker2 - pos_size_ticker2 - order_pos_ticker2
)
print(
f"\n{time_str()} -\n pos tick2: {pos_size_ticker2},\n exp pos tick2: {expected_pos_ticker2},\n mar pos tick2: {mar_pos_size_ticker2},\n new_order_contracts2(ticker2): {new_order_contracts2}"
)
logger.info(
f"pos tick2: {pos_size_ticker2}, exp pos tick2: {expected_pos_ticker2}, mar pos tick2: {mar_pos_size_ticker2}, new_order_contracts2(ticker2): {new_order_contracts2}"
)
# prepare new order details
if mar_pos_size_ticker2 < 0:
new_mar_pos = "short"
elif mar_pos_size_ticker2 > 0:
new_mar_pos = "long"
else:
new_mar_pos = "flat"
if pos_size_ticker2 < 0:
new_pos = "short"
elif pos_size_ticker2 > 0:
new_pos = "long"
else:
new_pos = "flat"
if new_order_contracts2 >= 0:
new_order_action = "buy"
new_comment = "Enter Long due to sync"
elif new_order_contracts2 < 0:
new_order_action = "sell"
new_comment = "Enter Short due to sync"
# create a new order for ticker2 if 1st ticker has "zero" order size
if order_contracts == 0 and new_order_contracts2 != 0:
send_data = {
"passphrase": PASSPHRASE,
# bypass is needed to create an order with a ticker that is already active in a pair
"bypass_ticker_status": True,
"order_action": new_order_action,
"order_contracts": abs(new_order_contracts2),
"mar_pos": new_mar_pos,
"mar_pos_size": abs(mar_pos_size_ticker2),
"pre_mar_pos": new_pos,
"pre_mar_pos_size": abs(pos_size_ticker2),
"order_comment": new_comment,
"order_status": "waiting",
"ticker": signal_dic["ticker2"],
"status_msg": "created due to sync",
}
# print(send_data)
# create new webhook with post request
response = requests.post(API_PUT_SIGNAL, json=send_data)
# check if created successfully
if response.status_code == 201:
print(
f"\n{time_str()} - New webhook created due to sync for ticker: {signal_dic['ticker2']}"
)
logger.info(
f"New webhook created due to sync for ticker: {signal_dic['ticker2']}"
)
else:
print(
f"\n{time_str()} - an error occurred creating webhook for ticker: {signal_dic['ticker2']}"
)
logger.error(
f"an error occurred creating webhook for ticker: {signal_dic['ticker2']}"
)
# change hedge parameter if 1st ticker has valid order size
else:
if order_contracts != 0:
new_hedge_param = abs(
round(new_order_contracts2 / order_contracts, 10)
) # order_contracts is always positive
# check if contact difference is more than a certain amount, not necessary to be zero
# usually 1 or 2 contracts is in acceptable range
if abs(expected_pos_ticker2 - mar_pos_size_ticker2) > 2:
hedge_param = new_hedge_param
print(
f"\n{time_str()} - New Hedge Param to be used:",
hedge_param,
)
logger.info(
f"New Hedge Param to be used: {hedge_param}"
)
else:
print(f"\n{time_str()} - No Change on Hedge Param:")
# 5-check for available funds before sending an order
# (active orders are not taken into consideration, define fund floor considering that)
# TODO: check if it makes sense to include a margin for active order amounts
# TODO: config hard limit for order amount (in $), or stock contract size?
if (
CHECK_FUNDS_FOR_TRADE
and trade_confirm
and not mar_pos_size == 0
and not order_contracts == 0
):
# get the acc summary as dict
account_summary_dict = get_acc_summary(ACCOUNT_NUMBER, CONNECTION_PORT)
# get available funds (margin for active orders are not included)
avab_funds = float(account_summary_dict["AvailableFunds"])
print(f"\n{time_str()} - available funds: ", avab_funds)
logger.info(f"available funds: {avab_funds} ")
if avab_funds > AVAILABLE_FUND_FLOOR:
print(f"\n{time_str()} - trade is allowed, sufficient funds.")
logger.info("trade is allowed, sufficient funds.")
else:
print(f"\n{time_str()} - not sufficient funds to trade!")
logger.warning(f"not sufficient funds to trade!")
trade_confirm = False
signal_dic["passphrase"] = PASSPHRASE
signal_dic["order_status"] = ("canceled",)
signal_dic["status_msg"] = "insufficient funds"
response = requests.put(API_PUT_SIGNAL, json=signal_dic)
if response.status_code == 200:
print(
f"\n{time_str()} - server updated with insufficient fund information."
)
logger.info(
"server updated with insufficient fund information."
)
else:
print(
f"\n{time_str()} - an error occurred updating status after insufficient funds."
)
logger.info(
"an error occurred updating status after insufficient funds."
)
# 6-send order if confirmed
# TODO: how to filter last minute orders, if exchange is closed no error message is received
# for exp.: cancel all open orders x min before session is closed
# reqContractDetails(id, contract) will return a contractDetails object with tradingHours as a field.
# https://stackoverflow.com/questions/48380455/interactive-brokers-tws-api-python-how-to-get-trading-day-info
# - day orders submitted with “RTH ONLY” will be canceled between 4:00-4:05 pm.
# - day orders submitted after 4:05 pm with “RTH ONLY” will be queued for the next day.
if trade_confirm:
# orders for pairs: 2nd order is dependent to first order
# best practice: 1st order is relative & 2nd order is set to market order
# IB connection parameters
app = TradingApp()
app.connect(
"127.0.0.1", CONNECTION_PORT, clientId=1
) # check for port number
# if there is a critical TWS or Gateway connection error
if not app.isConnected():
print(
f"\n{time_str()} - Client 1 cannot establish TWS connection, will try again"
)
logger.warning(
"Client 1 cannot establish TWS connection, will try again"
)
order_created = False
# not updating the server with connection errors, will try again
else:
print(f"\n{time_str()} - Client 1 established TWS connection")
logger.info("Client 1 established TWS connection")
# starting a separate daemon thread to execute the websocket connection
con_thread = threading.Thread(target=websocket_con, daemon=True)
con_thread.start()
time.sleep(
1
) # some latency added to ensure that the connection is established
# check connection error status
errors_con_df = app.errors_received
# define critical errors that blocks order creation
con_error_codes_array = [2110, 2157]
# critical errors
con_critical_errors_df = errors_con_df.loc[
errors_con_df["errorCode"].isin(con_error_codes_array)
]
# define error boolean flags
critical_con_err = not con_critical_errors_df.empty
if critical_con_err:
print(
f"\n{time_str()} - critical errors detected during connection, will not create orders"
)
logger.warning(
"critical errors detected during connection, will not create orders"
)
order_created = False
# not updating the server with connection errors, will try again
else:
# get security and exchange data for ticker 1
api_url = API_GET_TICKER + str(signal_dic["ticker1"])
try:
stock_dic = requests.get(api_url, timeout=5).json()
except requests.Timeout:
print(f"\n{time_str()} - timeout error (get stock details)")
pass
except requests.ConnectionError:
print(
f"\n{time_str()} - connection error (get stock details)"
)
pass
order_exchange1 = stock_dic["xch"]
primary_exchange1 = stock_dic["prixch"]
sec_type1 = stock_dic["sectype"]
currency1 = stock_dic["currency"]
order_type1 = stock_dic["order_type"]
# prepare crypto time in force
if sec_type1 == "CRYPTO":
timeinforce1 = "IOC"
# prepare symbolticker 1
if sec_type1 == "STK":
symbol1 = signal_dic["ticker1"]
else:
symbolarray1 = signal_dic["ticker1"].split(".", 1)
symbol1 = symbolarray1[0]
if len(symbolarray1) > 1:
symbol1_2 = symbolarray1[1]
# DELETE: check if the FX pair is suitable to trade
# if sec_type1 == "CASH":
# if currency1 != symbol1_2 :
# print(f"\n{time_str()} -pair currencies does not match!")
# logger.warning(f"pair currencies does not match!")
# trade_confirm = False
# signal_dic["passphrase"] = PASSPHRASE
# signal_dic["order_status"] = ("canceled",)
# signal_dic["status_msg"] = "currency mismatch"
# response = requests.put(API_PUT_SIGNAL, json=signal_dic)
# get exchange data for ticker 2
if signal_dic["ticker_type"] == "pair":
api_url = API_GET_TICKER + str(signal_dic["ticker2"])
try:
stock_dic = requests.get(api_url, timeout=5).json()
except requests.Timeout:
print(
f"\n{time_str()} - timeout error (get stock details)"
)
pass
except requests.ConnectionError:
print(
f"\n{time_str()} - connection error (get stock details)"
)
pass
order_exchange2 = stock_dic["xch"]
primary_exchange2 = stock_dic["prixch"]
sec_type2 = stock_dic["sectype"]
currency2 = stock_dic["currency"]
order_type2 = stock_dic["order_type"]
# prepare symbol
if sec_type2 == "STK":
symbol2 = signal_dic["ticker2"]
else:
symbolarray2 = signal_dic["ticker2"].split(".", 1)
symbol2 = symbolarray2[0]
if len(symbolarray2) > 1:
symbol2_2 = symbolarray2[1]
# prepare order for single trading
if signal_dic["ticker_type"] == "single":
app.reqIds(-1) # function to trigger nextValidId function
time.sleep(
0.5
) # need to provide some lag for the nextValidId
order_id1 = app.nextValidOrderId
print(f"\n{time_str()} - Order ID1 is: {order_id1}")
logger.info(f"Order ID1 is: {order_id1}")
# prepare the order
# if enabled: send with market order if rerouted
# if order_status == "rerouted":