-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinance_client.py
1756 lines (1363 loc) · 76.9 KB
/
binance_client.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 datetime
import os
import time
import platform
from enums import *
from binance import Client
from order_type import OrderType, PositionSideType, SideType
from threading import Thread, Event
from log import Log
from ast import literal_eval
from binance.client import BinanceAPIException
class Binance_Client():
def __init__(self, parameter_dict: dict, exit_event: Event, log_file: Log):
self.api_key = parameter_dict['binance_api_key']
self.api_secret = parameter_dict['binance_secret_key']
self.client = Client(self.api_key, self.api_secret, tld='com')
self.open_orders = list()
self.al_limit_orders = list()
self.current_day = self.get_current_date()
self.hedge_entry_price = 0.0
self.exit_event = exit_event
self.log_file = log_file
self.limit_order_future = datetime.datetime.now()
self.has_saved_open_orders = False
self.end_handle = False
self.has_started_mr_threshold = False
self.has_started_reopen_threshold = False
self.al_procedure_active = False
self.has_set_limit_orders = False
self.has_hedge_stop_loss = False
def exception_log(self, e, message):
# self.log_file.check_date(self.current_day)
print( f"[!] {self.get_current_time()} ERROR: {e}, {type(e).__name__}, {__file__}, {e.__traceback__.tb_lineno}")
print( f"[!] {self.get_current_time()} ERROR: {message}")
self.log_file.write(f"[!] {self.get_current_time()} ERROR: {message}")
self.log_file.write(f"[!] {self.get_current_time()} ERROR: {e}, {type(e).__name__}, {__file__}, {e.__traceback__.tb_lineno}")
def handle_exception(self, e, message):
self.exception_log(e, message)
# if type(e).__name__ == "ConnectionError": # ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')")), ConnectionError
self.client = None
if self.wait(30):
return
self.client = Client(self.api_key, self.api_secret, tld='com')
self.print_log("Reset binance client")
if isinstance(e, BinanceAPIException):
if str(e.code) == ERROR_TIME: # resync windows time
self.windows_sync_time()
def print_log(self, message, money=False):
"""Prints to console and writes data to log file"""
if not money:
print( f"[*] {self.get_current_time()} {message}")
self.log_file.write(f"[*] {self.get_current_time()} {message}")
else:
print( f"[$] {self.get_current_time()} {message}")
self.log_file.write(f"[$] {self.get_current_time()} {message}")
def get_current_date(self):
"""Gets current date"""
return datetime.date.today()
def get_current_time(self):
"""Gets current time in hour, minute, second format"""
return datetime.datetime.now().strftime("%H:%M:%S")
# https://stackoverflow.com/questions/43441883/how-can-i-make-a-file-hidden-on-windows
def hide_file(self, filename):
"""Hides a file from the user"""
os.system(f"attrib +h {filename}")
# https://stackoverflow.com/questions/43441883/how-can-i-make-a-file-hidden-on-windows
def unhide_file(self, filename):
"""Un-hides a file from the user"""
os.system(f"attrib -h {filename}")
def file_create(self):
"""Creates a .txt file"""
try:
if not os.path.exists(LIMIT_ORDERS_FILE):
file = open(LIMIT_ORDERS_FILE, "w+") # create the file
file.close()
self.hide_file(LIMIT_ORDERS_FILE)
except Exception as e:
self.handle_exception(e, f"can't create {LIMIT_ORDERS_FILE}")
def write(self, text):
"""Writes to the end of the file"""
try:
if os.path.exists(LIMIT_ORDERS_FILE):
self.unhide_file(LIMIT_ORDERS_FILE)
with open(LIMIT_ORDERS_FILE, 'a') as file:
file.write(f"{text}\n")
self.hide_file(LIMIT_ORDERS_FILE)
except Exception as e:
self.handle_exception(e, f"can't write to {LIMIT_ORDERS_FILE}")
def read(self):
"""Read data from LIMIT_ORDERS_FILE"""
data = []
try:
if os.path.exists(LIMIT_ORDERS_FILE):
self.unhide_file(LIMIT_ORDERS_FILE)
with open(LIMIT_ORDERS_FILE, 'r') as file:
lines = file.readlines()
for line in lines:
line = literal_eval(line.strip("\n")) # convert line to dictionary
data.append(line)
self.hide_file(LIMIT_ORDERS_FILE)
except Exception as e:
self.handle_exception(e, f"can't write to {LIMIT_ORDERS_FILE}")
return data
def windows_sync_time(self):
"""Sync windows time in case we get disconnected from Binance API
WARNING: This function only works if the user runs the .exe as administrator!"""
if platform == "linux" or platform == "linux2": # linux
pass
elif platform == "darwin": # OS X
pass
elif platform == "win32": # Windows...
try:
# https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/error-message-run-w32tm-resync-no-time-data-available
self.print_log("w32tm /resync")
if os.system("w32tm /resync") != 0:
self.print_log("windows time sync failed")
os.system("w32tm /config /manualpeerlist:time.nist.gov /syncfromflags:manual /reliable:yes /update")
os.system("Net stop w32time")
os.system("Net start w32time")
else:
self.print_log("windows time sync successful")
except Exception as e:
self.handle_exception(e, "failed to sync windows time")
def futures_get_max_precision(self, symbol):
precision = 0
with open(FUTURES_MAX_PRECISION_FILE, 'r') as file:
lines = file.readlines()
for line in lines:
symbol_ = line.split()
if symbol_[0] == symbol:
decimal = float(symbol_[1])
if decimal == 1:
precision = 0
else:
precision = len(str(decimal)) - 2
break
return precision
def futures_get_symbol_min_trade_quantity(self, symbol):
min_trade = 0.001
with open(FUTURES_MIN_TRADE_AMOUNTS, 'r') as file:
lines = file.readlines()
for line in lines:
symbol_ = line.split()
if symbol_[0] == symbol:
min_trade = float(symbol_[1])
break
return min_trade
###################################################################################################
### BNB RESUPPLY ###
###################################################################################################
def bnb_resupply(self):
"""If BNB quantity in futures account is 0, buy 1% of futures account value.
If 1% is below $11.00, buy $11 instead. Then transfer BNB back into futures wallet to get 10% trading fee discount"""
if not BUY_BNB:
return
try:
bnb_current_quantity = 1.0
bnb_quantity_to_buy = 0.0
balance = self.client.futures_account_balance()
for dictionary in balance:
if dictionary['asset'] == BNB:
bnb_current_quantity = float(dictionary['balance'])
break
bnb_current_quantity = round(bnb_current_quantity, 2)
if bnb_current_quantity == NOTHING:
usdt_spot_quantity = self.get_spot_coin_balance(symbol=USDT)
available_usdt = self.futures_get_available_tether()
bnb_mark_price = self.futures_get_mark_price("BNBUSDT")
usdt_quantity_to_transfer = available_usdt * 0.01
if available_usdt < BNB_BUY_MIN:
self.print_log(f"Can't buy bnb. Need at least $10. Available usdt is ${available_usdt}")
return
if bnb_mark_price == 0.0:
self.print_log(f"Can't buy bnb. Mark price of BNB is ${bnb_mark_price}")
return
if usdt_quantity_to_transfer <= BNB_BUY_MIN:
usdt_quantity_to_transfer = BNB_BUY_MIN
self.print_log("USDT transfer too low, setting transfer amount to $11.00")
if usdt_spot_quantity < BNB_BUY_MIN:
# transfer money to spot account
self.futures_to_spot_transfer(usdt_quantity_to_transfer)
# check if the transfer from futures to spot was successful
usdt_spot_quantity = self.get_spot_coin_balance(symbol=USDT)
if usdt_spot_quantity < usdt_quantity_to_transfer:
self.print_log(f"Can't buy bnb. Spot transfer failed")
return
bnb_quantity_to_buy = (usdt_quantity_to_transfer - 0.90) / bnb_mark_price
bnb_quantity_to_buy = round(bnb_quantity_to_buy, 4)
# min amount of BNB to buy is BNB_BUY_MIN
notional = self.get_notional_value(bnb_mark_price, bnb_quantity_to_buy, BNB_MIN)
if bnb_quantity_to_buy < notional:
bnb_quantity_to_buy = notional
self.client.order_market(
symbol = "BNBUSDT",
side = SideType.SIDE_BUY,
quantity = bnb_quantity_to_buy,
recvWindow = RECV_WINDOW)
self.print_log(f"Bought BNB/USDT {bnb_quantity_to_buy}")
# check the quantity of bnb we just bought
bnb_spot_qty = self.get_spot_coin_balance(symbol=BNB)
# transfer BNB back in futures
self.spot_to_futures_transfer(asset=BNB, amount=bnb_spot_qty)
except Exception as e:
self.handle_exception(e, "Could not resupply bnb")
###################################################################################################
### LONG ###
###################################################################################################
def futures_close_long_position(self, symbol, quantity):
"""Closes a long position in futures account"""
if quantity <= NOTHING:
self.print_log(f"can't close {symbol} long position because you own {quantity}")
return
try:
self.client.futures_create_order(
symbol = symbol,
side = SideType.SIDE_SELL,
type = OrderType.FUTURE_ORDER_TYPE_MARKET,
quantity = quantity,
reduceOnly = True,
recvWindow = RECV_WINDOW)
self.print_log(f"closed {symbol} {quantity} long position")
except Exception as e:
self.handle_exception(e, "Could not close futures long position")
def futures_place_long_position(self, quantity, symbol=HEDGE_SYMBOL):
"""Creates a long position"""
usdt_futures_quantity = float(self.futures_get_available_tether())
quantity = abs(round(quantity, 3))
if quantity <= NOTHING:
self.print_log(f"Can't place {symbol} long with {quantity} quantity")
return
if usdt_futures_quantity <= NOTHING:
self.print_log(f"Not enough USDT available to place the {HEDGE_SYMBOL} {quantity} long hedge. Current USDT: {usdt_futures_quantity}")
return
try:
self.client.futures_create_order(
symbol = symbol,
side = SideType.SIDE_BUY,
positionSide = PositionSideType.BOTH,
type = OrderType.FUTURE_ORDER_TYPE_MARKET,
quantity = quantity,
recvWindow = RECV_WINDOW)
self.print_log(f"Placed {symbol} {quantity} long hedge")
except BinanceAPIException as b:
if str(b.code) == ERROR_MARGIN_INSUFFICIENT:
self.print_log(f"Insufficient margin: {symbol} {quantity}")
return ERROR_MARGIN_INSUFFICIENT
except Exception as e:
self.handle_exception(e, f"Could not place {symbol} {quantity} long position")
def futures_get_open_long_interest(self):
"""Gets the total amount of all long positions by adding them all together"""
open_long_interest = 0.0
try:
positions = self.client.futures_position_information(recvWindow=RECV_WINDOW)
for dictionary in positions:
if float(dictionary['positionAmt']) > NOTHING: # for long positions
open_long_interest += (float(dictionary['positionAmt']) * float(dictionary['entryPrice'])) / float(dictionary['leverage'])
except Exception as e:
self.handle_exception(e, "Could not get open long interest")
return open_long_interest
def futures_get_open_long_interest_with_leverage(self):
"""Gets the total amount of all long positions by adding them all together"""
open_long_interest = 0.0
try:
positions = self.client.futures_position_information(recvWindow=RECV_WINDOW)
for dictionary in positions:
if float(dictionary['positionAmt']) > NOTHING: # for long positions
open_long_interest += float(dictionary['positionAmt']) * float(dictionary['entryPrice'])
except Exception as e:
self.handle_exception(e, "Could not get open long interest with leverage")
return open_long_interest
###################################################################################################
### SHORT ###
###################################################################################################
def futures_close_short_position(self, symbol, quantity):
"""Closes a short position in futures account"""
try:
self.client.futures_create_order(
symbol = symbol,
side = SideType.SIDE_BUY,
type = OrderType.FUTURE_ORDER_TYPE_MARKET,
quantity = abs(float(quantity)),
reduceOnly = True,
recvWindow = RECV_WINDOW)
self.print_log(f"closed {symbol} {quantity} short position")
except Exception as e:
self.handle_exception(e, f"Could not close {symbol} {quantity} short position")
def futures_get_open_short_interest(self):
"""Gets the total amount of all short positions by adding them all together without leverage"""
open_short_interest = 0.0
try:
positions = self.client.futures_position_information(recvWindow=RECV_WINDOW)
for dictionary in positions:
if float(dictionary['positionAmt']) < NOTHING: # for short positions
open_short_interest += (float(dictionary['positionAmt']) * float(dictionary['entryPrice']) ) / float(dictionary['leverage'])
except Exception as e:
self.handle_exception(e, "Could not open short interest")
return open_short_interest
def futures_get_open_short_interest_with_leverage(self):
"""Gets the total amount of all short positions by adding them all together with leverage factored in"""
open_short_interest = 0.0
try:
positions = self.client.futures_position_information(recvWindow=RECV_WINDOW)
for dictionary in positions:
if float(dictionary['positionAmt']) < NOTHING:
open_short_interest += float(dictionary['positionAmt']) * float(dictionary['entryPrice'])
except Exception as e:
self.handle_exception(e, "Could not open short interest with leverage")
return open_short_interest
def futures_place_short_position(self, quantity, symbol=HEDGE_SYMBOL):
"""Creates a short position"""
usdt_futures_quantity = float(self.futures_get_available_tether())
quantity = abs(round(quantity, 3))
if quantity <= NOTHING:
self.print_log(f"Can't place {HEDGE_SYMBOL} short with {quantity} quantity")
return
if usdt_futures_quantity <= NOTHING:
self.print_log(f"Not enough USDT available to place the {HEDGE_SYMBOL} {quantity} short hedge. Current USDT: {usdt_futures_quantity}")
return
try:
self.client.futures_create_order(
symbol = symbol,
side = SideType.SIDE_SELL,
positionSide = PositionSideType.BOTH,
type = OrderType.FUTURE_ORDER_TYPE_MARKET,
quantity = quantity,
recvWindow = RECV_WINDOW)
self.futures_set_hedge_entry_price()
self.print_log(f"Placed {HEDGE_SYMBOL} {quantity} Short hedge")
except BinanceAPIException as b:
if str(b.code) == ERROR_MARGIN_INSUFFICIENT:
self.print_log(f"Insufficient margin: {symbol} {quantity}")
return ERROR_MARGIN_INSUFFICIENT
except Exception as e:
self.handle_exception(e, f"could not place short position {HEDGE_SYMBOL} {quantity}")
###################################################################################################
### QUANTITY ###
###################################################################################################
def futures_get_short_position_quantity(self, symbol):
"""Gets the quantity of a short position"""
result = 0.0
try:
positions = self.client.futures_position_information(recvWindow=RECV_WINDOW)
for dictionary in positions:
if dictionary['symbol'] == symbol:
if float(dictionary['positionAmt']) < NOTHING: # for long positions
result = dictionary['positionAmt']
break
except Exception as e:
self.handle_exception(e, f"could not get short position {symbol}")
return result
def futures_get_long_position_quantity(self, symbol):
"""Gets the quantity of the long position"""
result = 0.0
try:
positions = self.client.futures_position_information(recvWindow=RECV_WINDOW)
for dictionary in positions:
if dictionary['symbol'] == symbol:
if float(dictionary['positionAmt']) > NOTHING: # for long positions
result = dictionary['positionAmt']
break
except Exception as e:
self.handle_exception(e, "Could not get futures long position quantity")
return result
def futures_get_position_quantity(self, symbol):
"""Gets the quantity of the coin we own"""
quantity = 0.0
try:
positions = self.client.futures_position_information(recvWindow=RECV_WINDOW)
for dictionary in positions:
if dictionary['symbol'] == symbol:
quantity = dictionary['positionAmt']
break
except Exception as e:
self.handle_exception(e, "Could not get futures position quantity")
return float(quantity)
###################################################################################################
### HEDGE ###
###################################################################################################
def auto_decide_hedge_mode(self):
"""
Decide which direction is better to hedge.
This is done by adding up every long position and every short position in our futures account.
If our long_count is greater than our short_count, then we will hedge in the short direction.
If our short_count is greater than our long_count, then we will hedge in the long direction.
Upon error, return -1,-1,-1
"""
short_count = 0
long_count = 0
hedge_decision = "Short"
try:
positions = self.client.futures_account(recvWindow=RECV_WINDOW)['positions']
""" Adds up the amount of money we are using with leverage"""
for dictionary in positions:
if float(dictionary["positionAmt"]) < 0.0:
short_count += float(dictionary['positionAmt']) * float(dictionary['entryPrice'])
elif float(dictionary["positionAmt"]) > 0.0:
long_count += float(dictionary['positionAmt']) * float(dictionary['entryPrice'])
if abs(short_count) > long_count:
hedge_decision = "Long"
if abs(short_count) < long_count:
hedge_decision = "Short"
except Exception as e:
self.handle_exception(e, "Could not decide hedge mode")
return -1, -1, -1
return round(short_count,3), round(long_count,3), hedge_decision
def futures_set_hedge_leverage(self):
"""Set the leverage for our hedge position. This works for both short and long"""
try:
self.client.futures_change_leverage(
symbol = HEDGE_SYMBOL,
leverage = HEDGE_LEVERAGE,
recvWindow = RECV_WINDOW)
except Exception as e:
self.handle_exception(e, "Could not set hedge leverage")
def futures_get_current_hedge_entry_price(self):
"""Gets the average buy price (entry_price) for HEDGE_SYMBOL.
Helpful Hint:
The term "entry_price" on Binance is a little deceiving because when read literally,
we think of the price the coin was originally bought at.
While this is true if the coin was bought once and only once,
this is not true if the coin was bought 2 or more times at different prices.
Once the coin is bought 2 or more times at different prices, the "entry_price"
becomes the break even price or average buy price."""
current_entry_price = 0
try:
hedge_position = self.client.futures_position_information(symbol=HEDGE_SYMBOL, recvWindow=RECV_WINDOW)
for dictionary in hedge_position:
current_entry_price = float(dictionary['entryPrice'])
break
except Exception as e:
self.handle_exception(e, "Could not set hedge leverage")
return current_entry_price
def futures_set_hedge_entry_price(self):
"""Sets the entry price for our hedge position.
This function is used in conjunction with setting the hedge stop loss."""
try:
if self.hedge_entry_price == 0:
hedge_position = self.client.futures_position_information(symbol=HEDGE_SYMBOL, recvWindow=RECV_WINDOW)
for dictionary in hedge_position:
self.hedge_entry_price = float(dictionary['entryPrice'])
break
except Exception as e:
self.handle_exception(e, "Could not set hedge entry price")
def create_hedge_stop_loss(self, side, stop_percent):
"""Puts a market stop loss in for our hedge position"""
try:
# if the hedge entry_price is the same as when the position was originally filled and there is already a hedge order open
# get HEDGE_SYMBOL current entry price and compare with self.hedge_entry_price
current_entry_price = self.futures_get_current_hedge_entry_price()
if self.has_hedge_stop_loss:
if self.hedge_entry_price == current_entry_price: # when we first create the hedge, this condition will always be true
# self.print_log(f"Not placing new stop loss order for hedge {HEDGE_SYMBOL}. Hedge entry price ({self.hedge_entry_price}) = Current entry price ({current_entry_price})")
return
self.has_hedge_stop_loss = True
mark_price = self.futures_get_mark_price(HEDGE_SYMBOL)
quantity = self.futures_get_position_quantity(HEDGE_SYMBOL)
stop_price = mark_price + (mark_price * stop_percent)
quantity = abs(round(quantity, 3)) # might need to get the min quantity from the .txt file
stop_price = round(stop_price, 2)
if quantity <= NOTHING:
self.print_log(f"Can't place {HEDGE_SYMBOL} hedge stop loss with {quantity} quantity")
return
self.client.futures_create_order(
symbol = HEDGE_SYMBOL,
side = side,
positionSide = PositionSideType.BOTH,
type = OrderType.FUTURE_ORDER_TYPE_STOP_MARKET,
quantity = abs(quantity),
stopPrice = stop_price,
reduceOnly = True,
recvWindow = RECV_WINDOW)
self.futures_set_hedge_entry_price()
self.print_log(f"Placed {HEDGE_SYMBOL} {quantity} {'${:,.2f}'.format(float(stop_price))} stop")
except Exception as e:
self.handle_exception(e, f"could not place {HEDGE_SYMBOL} {stop_price} stop")
def create_hedge(self):
"""
create_hedge(): (This is the main component for creating a hedge).
Based on the SHORT_LONG_RATIO_LIMIT_PERCENT that is set in config, gets the balance of shorts to longs to find out how much to hedge in either direction
If we already have a HEDGE_SYMBOL position open in the opposite direction that we are trying to hedge, close it first then make the hedge.
After the hedge is created, put a stop loss in for 10% lower than entry price for a long, 10 percent higher than entry price for a short.
"""
usdt_available = self.futures_get_available_tether()
_, _, hedge_mode = self.auto_decide_hedge_mode()
long_interest = round(self.futures_get_open_long_interest_with_leverage(), 1)
short_interest = round(abs(self.futures_get_open_short_interest_with_leverage()), 1)
hedge_limit = long_interest * HEDGE_PERCENT
usdt_amount_to_hedge = hedge_limit - short_interest
self.futures_change_margin_type(symbol=HEDGE_SYMBOL, margin_type=CROSS)
self.futures_set_hedge_leverage()
if self.end_handle:
return
if hedge_mode == "Short":
if long_interest == 0:
return
balance = abs(short_interest / long_interest)
if balance >= SHORT_LONG_RATIO_LIMIT_PERCENT and balance <= 100:
"""If the open interest on our hedge position is within SHORT_TO_LONG_BALANCE_RATIO of the hedge we want to make, don't make the new hedge"""
self.print_log(f"short to long open interest balance is {'{:,.2f}'.format(balance*100)}%")
return
elif balance > 100:
if self.futures_get_position_quantity(HEDGE_SYMBOL) != 0: # check if position exists
self.print_log("Rebalancing short interest")
short_interest = round(abs(self.futures_get_open_short_interest_with_leverage()), 1)
long_interest = round(self.futures_get_open_long_interest_with_leverage(), 1)
interest_diff = short_interest - long_interest
# in order to rebalance, we need to close some of our HEDGE_SYMBOL position
mark_price = self.futures_get_mark_price(HEDGE_SYMBOL) # calculate how much we need to short based on open long positions
quantity = round((interest_diff/mark_price), 3) # calculate quantity of coin to short
self.futures_cancel_order(HEDGE_SYMBOL)
self.futures_close_short_position(HEDGE_SYMBOL, quantity)
self.create_hedge_stop_loss(side=SideType.SIDE_BUY, stop_percent=HEDGE_STOP_PERCENT)
return
mark_price = self.futures_get_mark_price(HEDGE_SYMBOL) # calculate how much we need to short based on open long positions
quantity = round((usdt_amount_to_hedge/mark_price), 3) # calculate quantity of coin to short
self.futures_cancel_order(HEDGE_SYMBOL)
result = ERROR_MARGIN_INSUFFICIENT
if quantity != 0:
result = self.futures_place_short_position(symbol=HEDGE_SYMBOL, quantity=quantity)
if result == ERROR_MARGIN_INSUFFICIENT:
"""We couldn't make the hedge with the desired quantity,
therefore try to make the hedge with any USDT we have available."""
self.print_log(f"Going to place {HEDGE_SYMBOL} hedge with USDT available...")
quantity = round((usdt_available/mark_price), 3)
notional_quantity = self.get_notional_value(mark_price, quantity, ETH_MIN)
result = self.futures_place_short_position(symbol=HEDGE_SYMBOL, quantity=notional_quantity)
if result != ERROR_MARGIN_INSUFFICIENT:
self.create_hedge_stop_loss(side=SideType.SIDE_BUY, stop_percent=HEDGE_STOP_PERCENT)
elif hedge_mode == "Long":
if short_interest == 0:
return
balance = abs(long_interest / short_interest)
if balance >= SHORT_LONG_RATIO_LIMIT_PERCENT and balance <= 100:
"""If the open interest on our hedge position is within SHORT_TO_LONG_BALANCE_RATIO of the hedge we want to make, don't make the new hedge"""
# self.print_log(f"long to short open interest balance is {'{:,.2f}'.format(balance*100)}%")
return
elif balance > 100:
if self.futures_get_position_quantity(HEDGE_SYMBOL) != 0: # check if position exists
self.print_log("Rebalancing long interest")
long_interest = round(self.futures_get_open_long_interest_with_leverage(), 1)
short_interest = round(abs(self.futures_get_open_short_interest_with_leverage()), 1)
interest_diff = long_interest - short_interest
# in order to rebalance, we need to close some of our HEDGE_SYMBOL position
mark_price = self.futures_get_mark_price(HEDGE_SYMBOL) # calculate how much we need to short based on open long positions
quantity = round((interest_diff/mark_price), 3) # calculate quantity of coin to short
self.futures_cancel_order(HEDGE_SYMBOL)
self.futures_close_long_position(HEDGE_SYMBOL, quantity)
self.create_hedge_stop_loss(side=SideType.SIDE_SELL, stop_percent=-HEDGE_STOP_PERCENT)
return
mark_price = self.futures_get_mark_price(HEDGE_SYMBOL) # calculate how much we need to long based on open short positions
quantity = round((usdt_amount_to_hedge/mark_price), 3)
self.futures_cancel_order(HEDGE_SYMBOL)
result = ERROR_MARGIN_INSUFFICIENT
if quantity != 0:
result = self.futures_place_long_position(symbol=HEDGE_SYMBOL, quantity=quantity)
if result == ERROR_MARGIN_INSUFFICIENT:
"""We couldn't make the hedge with the desired quantity,
therefore try to make the hedge with any USDT we have available."""
self.print_log(f"Going to try to place {HEDGE_SYMBOL} hedge with USDT available...")
quantity = round((usdt_available/mark_price), 3)
notional_quantity = self.get_notional_value(mark_price, quantity, ETH_MIN)
result = self.futures_place_long_position(symbol=HEDGE_SYMBOL, quantity=notional_quantity)
if result != ERROR_MARGIN_INSUFFICIENT:
self.create_hedge_stop_loss(side=SideType.SIDE_SELL, stop_percent=-HEDGE_STOP_PERCENT)
def close_hedge(self):
"""Closes the HEDGE_SYMBOL position"""
quantity = self.futures_get_position_quantity(HEDGE_SYMBOL)
if quantity > 0.0:
self.futures_close_long_position(HEDGE_SYMBOL, quantity)
elif quantity < 0.0:
self.futures_close_short_position(HEDGE_SYMBOL, quantity)
else:
self.print_log(f"cannot close {HEDGE_SYMBOL} position because it doesn't exist.")
def futures_get_hedge_position(self, symbol, hedge_mode):
"""Checks if there is an open position on the symbol we want to hedge"""
try:
positions = self.client.futures_position_information(recvWindow=RECV_WINDOW)
for dictionary in positions:
if dictionary['symbol'] == symbol:
if hedge_mode == "Short":
if float(dictionary['positionAmt']) < 0.0: # SHORT position
return True
elif hedge_mode == "Long":
if float(dictionary['positionAmt']) > 0.0: # LONG position
return True
except Exception as e:
self.handle_exception(e, "Could not get hedge position")
return False
###################################################################################################
### S/L DIFFERENCE ###
###################################################################################################
def get_short_long_difference(self):
"""Gets the difference between short and long open positions with leverage factored in"""
long_interest = self.futures_get_open_long_interest_with_leverage()
short_interest = self.futures_get_open_short_interest_with_leverage()
difference_interest = abs(short_interest) - long_interest
return round(difference_interest, 2)
###################################################################################################
### THREADED FUNCTIONS ###
###################################################################################################
def thread_reopen_orders_threshold(self):
"""If our margin ratio has dropped below MARGIN_RATIO_THRESHOLD, then lets reopen all of our closed orders"""
while True:
if self.futures_get_account_margin_ratio() < REOPEN_ORDERS_THRESHOLD:
self.futures_reopen_all_closed_orders()
self.has_started_reopen_threshold = True
break
if self.exit_event.wait(timeout=2):
self.has_started_reopen_threshold = True
break
###################################################################################################
### TICK/STEP SIZE ###
###################################################################################################
def futures_get_tick_and_step_size(self, symbol):
"""Gets the tick and step size for a given symbol.
Tick size can be used to get the maximum decimal places for price in terms of USDT of an order.
Step size is the min quantity of coin that we can order"""
tick_size = None
step_size = None
try:
symbol_info = self.client.get_symbol_info(symbol)
if symbol_info is None:
"""If we couldn't find the data from binance, search the file"""
# tick_size = self.futures_get_max_precision(symbol)
# step_size = self.futures_get_symbol_min_trade_quantity(symbol)
tick_size = float(FUTURES_MAX_PRECISION_DICT[symbol])
step_size = float(FUTURES_MIN_TRADE_DICT[symbol])
if tick_size == 1:
tick_size = 0
else:
tick_size = len(str(tick_size)) - 2
return tick_size, step_size
for filter in symbol_info['filters']:
if filter['filterType'] == 'PRICE_FILTER':
tick_size = float(filter['tickSize'])
if tick_size == 1:
tick_size = 0
else:
tick_size = len(str(tick_size)) - 2
elif filter['filterType'] == 'LOT_SIZE':
step_size = float(filter['stepSize'])
if step_size == 1:
step_size = 0
else:
step_size = len(str(step_size)) - 2
except Exception as e:
self.print_log(message=f"Could not get tick and step size for {symbol}", e=e)
return tick_size, step_size
###################################################################################################
### LIMIT ORDERS ###
###################################################################################################
def futures_get_open_limit_orders_from_file(self):
"""Returns a list of open orders from LIMIT_ORDERS_FILE. Old orders that are no longer open will not be included."""
try:
old_limit_orders = self.read()
open_limit_orders_list = list()
current_open_orders = self.client.futures_get_open_orders(recvWindow=RECV_WINDOW)
# Do we need to remove it from the list if the orderId's match or don't match?
for old_order in old_limit_orders:
for open_order in current_open_orders:
if old_order['orderId'] == open_order['orderId']:
open_limit_orders_list.append(old_order)
except Exception as e:
self.handle_exception(e, f"could not get open orders from {LIMIT_ORDERS_FILE}")
return open_limit_orders_list
def futures_cancel_managed_limit_order(self, symbol, new_limit_price):
"""Creates and manages the data in LIMIT_ORDERS_FILE.
If the order is still open, cancel it because we are about to make a new limit order which will render our previous limit order useless.
Return a list of orders that are still open that the AL bot is managing."""
try:
# create and manage all the limit orders AL has created
self.file_create()
open_limit_orders_list = self.futures_get_open_limit_orders_from_file() # Returns a list of open orders from LIMIT_ORDERS_FILE
# no orders to cancel
if len(open_limit_orders_list) == 0:
return True
# we only want to cancel the order if the new price if different than the old price
for open_order in open_limit_orders_list:
if open_order['symbol'] == symbol and float(open_order['price']) != float(new_limit_price):
self.client.futures_cancel_order(symbol=open_order['symbol'], orderId=open_order['orderId'], recvWindow=RECV_WINDOW)
self.print_log(f" Cancelled order: {open_order}")
return True # cancelled the order
elif float(open_order['price']) == float(new_limit_price):
# self.print_log(f"Not cancelling {symbol} limit order. Current limit price (${open_order['price']}) = New limit price (${new_limit_price})")
pass
except Exception as e:
self.handle_exception(e, f"could not manage data in {LIMIT_ORDERS_FILE}")
return False # didn't cancelled order
def futures_update_limit_orders_file(self, result_list):
"""Truncate LIMIT_ORDERS_FILE file with the new data"""
try:
if os.path.exists(LIMIT_ORDERS_FILE):
self.unhide_file(LIMIT_ORDERS_FILE)
file = open(LIMIT_ORDERS_FILE, 'w+')
file.truncate()
for i in result_list:
file.write(str(i)+"\n")
file.close()
self.hide_file(LIMIT_ORDERS_FILE)
except Exception as e:
self.handle_exception(e, f"could not update {LIMIT_ORDERS_FILE}")
def futures_place_limit_orders(self):
"""Cancel all orders inside of LIMIT_ORDERS_FILE and place new
limit orders for all open positions CLOSE_PERCENT higher than entry price.
LIMIT_ORDERS_FILE contains all of AL's previous limit orders that should be cancelled before putting in new ones."""
limit_price = 0
symbol = None
order = None
orders_list = list()
try:
open_positions = self.client.futures_position_information(recvWindow=RECV_WINDOW)
for position in open_positions:
if float(position['positionAmt']) == NOTHING or position['symbol'] == HEDGE_SYMBOL:
continue
symbol = position['symbol']
entry_price = float(position['entryPrice'])
quantity = float(position['positionAmt'])
tick_size, step_size = self.futures_get_tick_and_step_size(symbol)
side = SideType.SIDE_BUY
limit_price = entry_price - (entry_price * CLOSE_PERCENT)
if quantity > 0:
limit_price = entry_price + (entry_price * CLOSE_PERCENT)
side = SideType.SIDE_SELL
limit_price = '{:.{precision}f}'.format(limit_price, precision=tick_size)
# we only want to cancel the order if the new price if different than the old price
result = self.futures_cancel_managed_limit_order(symbol, limit_price)
if result:
"""if there are no open orders that AL is managing, you are free to put in any limit order that you want!"""
order = self.futures_create_limit_order(symbol, side, quantity, limit_price)
if order != -1:
orders_list.append(order)
else:
continue
else:
# self.print_log(f"Not placing new limit order for {symbol}.")
pass
except Exception as e:
self.handle_exception(e, f"Could not set limit order for {symbol}.")
if len(orders_list) != 0:
self.futures_update_limit_orders_file(orders_list)
def futures_create_limit_order(self, symbol, side, quantity, limit_price):
try:
order = self.client.futures_create_order(
symbol = symbol,
side = side,
positionSide = PositionSideType.BOTH,
type = OrderType.FUTURE_ORDER_TYPE_LIMIT,
quantity = abs(quantity),
price = limit_price,
reduceOnly = True,
timeInForce = "GTC",
recvWindow = RECV_WINDOW)
self.print_log(f"Created limit order: {str(order)}")
# orders_list.append(order)
return order
except Exception as e:
self.handle_exception(e, f"Could not set limit order for {symbol}")
return -1
###################################################################################################
### TRANSFERS ###
###################################################################################################
def futures_to_spot_transfer(self, quantity_to_transfer, symbol="USDT"):
"""Transfer asset from futures wallet to spot wallet
1: transfer from spot account to USDT-Ⓜ futures account.
2: transfer from USDT-Ⓜ futures account to spot account."""
try:
self.client.futures_account_transfer(
asset = symbol,
amount = quantity_to_transfer,
type = 2,
dualSidePosition = False,
recvWindow = RECV_WINDOW)