-
Notifications
You must be signed in to change notification settings - Fork 20
/
crypto-genie.py
4158 lines (3761 loc) · 371 KB
/
crypto-genie.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
#!/usr/bin/python
# INSTALLATION
#
# Install Python 3.8+
# Install Pip3
#
# Then run in terminal:
#
# pip3 install pybit
# pip3 install wheel
# pip3 install pandas
# pip3 install pandas_ta
# pip3 install matplotlib
# pip3 install mysql-connector-python
# pip3 install pydash
# pip3 install pyyaml
#
# USAGE
#
# Edit config.yaml with your API keys and set the variables to your liking.
# Make more copies of config.yaml for other setups you want to run
#
#
# You can run this script multiple times, one in each terminal, with a different config file for each!
#
# At command line:
#
# python3 crypto-genie.py config_file=config.yaml
import random
import string
import numpy as np
import pandas as pd
import pandas_ta as ta
import matplotlib.pyplot as plt
import math
import json
from types import SimpleNamespace
import logging
from time import sleep
import time
import calendar
from datetime import datetime, timedelta
from typing import Union
from decimal import Decimal
from pybit import HTTP, WebSocket
import mysql.connector
from pydash import _
import yaml
import sys
from sklearn.linear_model import LinearRegression
###### Terminal passed Arguments
args = {}
for arg in sys.argv[1:]:
arg_key = arg.split('=')[0]
arg_value = arg.split('=')[1]
args[arg_key] = arg_value
# Load config parameters from given file or default config.yaml
if "config_file" in args:
config_file = args['config_file']
else:
config_file = "config.yaml"
config = {}
with open(config_file) as f:
config = yaml.safe_load(f)
### CONFIG VARIABLES FROM CONFIG FILE
# MySQL Database
enable_db_features = config['enable_db_features']
db_host = config['db_host']
db_username = config['db_username']
db_password = config['db_password']
db_name = config['db_name']
# ByBit Exchange API
api_key = config['api_key']
api_secret = config['api_secret']
network = config['network']
log_label = config['log_label']
exchange_market_taker_fee = 0.075
exchange_market_maker_fee = -0.025
wait_time = config['wait_time']
recv_window = config['recv_window']
enforce_sl_static = config['enforce_sl_static']
default_sl_static_cap_ratio = config['default_sl_static_cap_ratio']
override_sl_static_cap_ratio = config['override_sl_static_cap_ratio'] or {}
enforce_tb_sl_static = config['enforce_tb_sl_static']
enforce_tb_sl_static_emergency_exit = config['enforce_tb_sl_static_emergency_exit']
enforce_tb_sl_static_range = config['enforce_tb_sl_static_range']
enforce_tb_sl_max_cum_loss = config['enforce_tb_sl_max_cum_loss']
enforce_tb_sl_db_stored = config['enforce_tb_sl_db_stored']
default_tb_initial_sl_static_cap_ratio = config['default_tb_initial_sl_static_cap_ratio']
default_tb_initial_sl_static_pos_size_ratio = config['default_tb_initial_sl_static_pos_size_ratio']
default_tb_sl_static_cap_ratio = config['default_tb_sl_static_cap_ratio']
default_tb_sl_static_pos_size_ratio = config['default_tb_sl_static_pos_size_ratio']
override_tb_sl_static = config['override_tb_sl_static'] or {}
enforce_tb_hedge = config['enforce_tb_hedge']
default_tb_hedge_cap_ratio = config['default_tb_hedge_cap_ratio']
default_tb_hedge_pos_size_ratio = config['default_tb_hedge_pos_size_ratio']
default_tb_hedge_balancer_cap_ratio = config['default_tb_hedge_balancer_cap_ratio']
default_tb_hedge_sl_static_cap_ratio = config['default_tb_hedge_sl_static_cap_ratio']
override_tb_hedge = config['override_tb_hedge'] or {}
enforce_sl_range = config['enforce_sl_range']
default_sl_range_cap_ratio = config['default_sl_range_cap_ratio']
override_sl_range_cap_ratio = config['override_sl_range_cap_ratio']
enforce_tp = config['enforce_tp']
enforce_tp_limit = config['enforce_tp_limit']
default_tp_tolerance_ratio = config['default_tp_tolerance_ratio']
default_tp = config['default_tp']
enforce_lock_in_p_sl = config['enforce_lock_in_p_sl']
default_lock_in_p_sl = config['default_lock_in_p_sl']
enforce_tp_dynamic = config['enforce_tp_dynamic']
tp_dynamic = config['tp_dynamic']
enforce_smart_dynamic_entries = config['enforce_smart_dynamic_entries']
smart_dynamic_entries = config['smart_dynamic_entries']
default_smart_dynamic_entries_wallet_balance_order_ratio = config['default_smart_dynamic_entries_wallet_balance_order_ratio']
default_smart_dynamic_entries_minimum_average_distance_multiplier = config['default_smart_dynamic_entries_minimum_average_distance_multiplier']
default_smart_dynamic_entries_price_chaser_minimum_ticks = config['default_smart_dynamic_entries_price_chaser_minimum_ticks']
default_smart_dynamic_entries_rsi_length = config['default_smart_dynamic_entries_rsi_length']
default_smart_dynamic_entries_level_1_from = config['default_smart_dynamic_entries_level_1_from']
default_smart_dynamic_entries_level_1_to = config['default_smart_dynamic_entries_level_1_to']
default_smart_dynamic_entries_level_1_max_effective_leverage = config['default_smart_dynamic_entries_level_1_max_effective_leverage']
default_smart_dynamic_entries_level_2_from = config['default_smart_dynamic_entries_level_2_from']
default_smart_dynamic_entries_level_2_to = config['default_smart_dynamic_entries_level_2_to']
default_smart_dynamic_entries_level_2_max_effective_leverage = config['default_smart_dynamic_entries_level_2_max_effective_leverage']
default_smart_dynamic_entries_level_3_from = config['default_smart_dynamic_entries_level_3_from']
default_smart_dynamic_entries_level_3_to = config['default_smart_dynamic_entries_level_3_to']
default_smart_dynamic_entries_level_3_max_effective_leverage = config['default_smart_dynamic_entries_level_3_max_effective_leverage']
default_smart_dynamic_entries_level_4_from = config['default_smart_dynamic_entries_level_4_from']
default_smart_dynamic_entries_level_4_max_effective_leverage = config['default_smart_dynamic_entries_level_4_max_effective_leverage']
enforce_db_exit_strategies = config['enforce_db_exit_strategies']
# Connect to Crypto Genie Database
if(enable_db_features):
mydb = mysql.connector.connect(
host=db_host,
user=db_username,
password=db_password,
database=db_name
)
mydb.autocommit = True
def round_step_size(quantity: Union[float, Decimal], step_size: Union[float, Decimal], min_qty: Union[float, Decimal] = 0) -> float:
"""Rounds a given quantity to a specific step size
:param quantity: required
:param step_size: required
:return: decimal
"""
precision: int = int(round(-math.log(step_size, 10), 0))
return float(round(quantity, precision)) if float(round(quantity, precision)) > min_qty else min_qty
def get_random_string(length):
# choose from all lowercase letter
letters = string.ascii_lowercase
result_str = ''.join(random.choice(letters) for i in range(length))
return result_str
def close_enough_match(price1, price2, size1, size2, positionType=False):
# price1 is the fixed target and price2 is the dynamic one being checked
if positionType=="Buy":
price_matches = price2 <= price1 # Price can be at the exact level or closer to entry
elif positionType=="Sell":
price_matches = price2 >= price1 # Price can be at the exact level or closer to entry
else:
price_matches = price2 == price1
size_matches = size1 == size2 or math.floor(size1 * 10)/10.0 == size2 or math.floor(size1 * 100)/100.0 == size2 or math.floor(size1 * 1000)/1000.0 == size2 or math.floor(size1 * 10000)/10000.0 == size2
return price_matches and size_matches
def round_to_tick(price,tick_size):
decimals_count = str(tick_size)[::-1].find('.') # Tick Size number of decimals
return round(round(float(price)/float(tick_size))*float(tick_size), decimals_count)
###### ByBit Base Endpoints (only edit if they don't match the currently published ones by ByBit at: https://bybit-exchange.github.io/docs/linear/#t-websocket
wsURL_USDT_mainnet = "wss://stream.bybit.com/realtime_private"
wsURL_USDT_testnet = "wss://stream-testnet.bybit.com/realtime_private"
wsURL_Inverse_mainnet = "wss://stream.bybit.com/realtime"
wsURL_Inverse_testnet = "wss://stream-testnet.bybit.com/realtime"
sessionURL_mainnet = "https://api.bybit.com"
sessionURL_testnet = "https://api-testnet.bybit.com"
######
if network == 'testnet':
wsURL_USDT = wsURL_USDT_testnet
wsURL_Inverse = wsURL_Inverse_testnet
sessionURL = sessionURL_testnet
elif network == 'mainnet':
wsURL_USDT = wsURL_USDT_mainnet
wsURL_Inverse = wsURL_Inverse_mainnet
sessionURL = sessionURL_mainnet
if __name__ == "__main__":
session = HTTP(endpoint=sessionURL, api_key=api_key, api_secret=api_secret, recv_window=recv_window)
tick_size = {}
base_currency = {}
quote_currency = {}
max_leverage = {}
qty_step = {}
min_trading_qty = {}
instruments = []
symbols = session.query_symbol()["result"]
for symbol in symbols:
tick_size[symbol["name"]] = symbol["price_filter"]["tick_size"]
base_currency[symbol["name"]] = symbol["base_currency"]
quote_currency[symbol["name"]] = symbol["quote_currency"]
max_leverage[symbol["name"]] = symbol["leverage_filter"]["max_leverage"]
qty_step[symbol["name"]] = symbol["lot_size_filter"]["qty_step"]
min_trading_qty[symbol["name"]] = symbol["lot_size_filter"]["min_trading_qty"]
instruments.append(symbol["name"])
'''
# CUSTOM CODE TO SET LEVERAGE OF ALL PAIRS TO THE MAX
if symbol["name"].endswith('USDT'): # USDT Perpetual
try:
session.set_leverage(symbol=symbol["name"], buy_leverage=12.5, sell_leverage=12.5)
print(symbol["name"] + " now set to Leverage 12.5")
except Exception:
pass
try:
session.set_leverage(symbol=symbol["name"], buy_leverage=25, sell_leverage=25)
print(symbol["name"] + " now set to Leverage 25")
except Exception:
pass
try:
session.set_leverage(symbol=symbol["name"], buy_leverage=50, sell_leverage=50)
print(symbol["name"] + " now set to Leverage 50")
except Exception:
pass
try:
session.set_leverage(symbol=symbol["name"], buy_leverage=100, sell_leverage=100)
print(symbol["name"] + " now set to Leverage 100")
except Exception:
pass
else: # Inverse Perpetuals or Futures
try:
session.set_leverage(symbol=symbol["name"], leverage=12.5)
print(symbol["name"] + " now set to Leverage 12.5")
except Exception:
pass
try:
session.set_leverage(symbol=symbol["name"], leverage=25)
print(symbol["name"] + " now set to Leverage 25")
except Exception:
pass
try:
session.set_leverage(symbol=symbol["name"], leverage=50)
print(symbol["name"] + " now set to Leverage 50")
except Exception:
pass
try:
session.set_leverage(symbol=symbol["name"], leverage=100)
print(symbol["name"] + " now set to Leverage 100")
except Exception:
pass
'''
# print("Max Leverage changed for all pairs!")
# sleep(3600) # Wait for an hour to manually exit the script
''' *** We wil not use WebSockets for now, only REST API due to missing fields in the WebSocket API ***
ws_USDT = WebSocket(wsURL_USDT, subscriptions=['position'], api_key=api_key, api_secret=api_secret)
ws_Inverse = WebSocket(wsURL_Inverse, subscriptions=['position'], api_key=api_key, api_secret=api_secret)
while(1):
# Fetch Active Positions through WebSockets (USDT and Inverse)
fetched_websockets = []
fetched_positions = ws_USDT.fetch('position')
if(fetched_positions):
positions = json.loads(json.dumps(fetched_positions, default=lambda s: vars(s)))
for coins, coin_data in positions.items():
for side, position in coin_data.items():
fetched_websockets.append(position)
fetched_positions = ws_Inverse.fetch('position')
if fetched_positions:
positions = json.loads(json.dumps(fetched_positions, default=lambda s: vars(s)))
for coin, position in positions.items():
fetched_websockets.append(position)
# Now we set Stop Losses
for position in fetched_websockets:
'''
while(1):
if(enable_db_features):
### First check if Database has any actions ###
# Any Scaled Orders requests in the Database queued?
mycursor = mydb.cursor(dictionary=True)
mycursor.execute("SELECT * FROM scaled_orders WHERE api_key='"+api_key+"' AND api_secret='"+api_secret+"'")
myresult = mycursor.fetchall()
for scaled_order in myresult:
error = False
# First check if Symbol exists on the Exchange
if scaled_order['symbol'] not in instruments:
error = "Instrument not found on exchange"
# Distribute an amount based on weighting
if (int(scaled_order['orderCount']) < 2 or int(scaled_order['orderCount']) > 200):
error = "Number of orders must be between 2 and 200"
if not error:
weights = map(lambda x: 100 / int(scaled_order['orderCount']), _.range(int(scaled_order['orderCount']))) # Get distribution weights
weightsList = list(weights)
distributedTotal = []
distributionSum = _.sum(weightsList)
for weight in weightsList:
if _.sum(distributedTotal) < float(scaled_order['amount']):
val = round_step_size((weight * float(scaled_order['amount'])) / distributionSum,qty_step[scaled_order['symbol']],min_trading_qty[scaled_order['symbol']])
if _.sum(distributedTotal) + val <= float(scaled_order['amount']):
distributedTotal.append(val)
else:
val = round_step_size((float(scaled_order['amount']) - _.sum(distributedTotal)),qty_step[scaled_order['symbol']],min_trading_qty[scaled_order['symbol']])
distributedTotal.append(val)
priceDiff = float(scaled_order['priceUpper']) - float(scaled_order['priceLower'])
stepsPerPricePoint = priceDiff / (int(scaled_order['orderCount']) - 1)
# Generate the prices we're placing orders at
final_decimals_count = str(tick_size[scaled_order['symbol']])[::-1].find('.') # Tick Size number of decimals - 1
orderPrices = map(lambda i: float(scaled_order['priceLower']) if i is 0 else (float(scaled_order['priceUpper']) if i is int(scaled_order['orderCount']) - 1 else float(scaled_order['priceLower']) + stepsPerPricePoint * i), _.range(int(scaled_order['orderCount']))) # Get distribution weights
orderPrices = map(lambda price: round(float(price), final_decimals_count), orderPrices)
orders = {}
minPrice = float('inf')
maxPrice = float('-inf')
orderPrices = list(orderPrices)
for index in range(len(distributedTotal)):
minPrice = min(minPrice, orderPrices[index])
maxPrice = max(maxPrice, orderPrices[index])
orders.update( {orderPrices[index] : distributedTotal[index]} )
# Verify that the generated orders match the specification
if (minPrice < float(scaled_order['priceLower'])):
error = "Order is lower than the specified lower price"
if (maxPrice > float(scaled_order['priceUpper'])):
error = "Order is higher than the specified upper price"
if not error:
# Now place the orders on exchange's order book
for order_price, order_amount in orders.items():
if scaled_order['orderExec'] == 'Open':
try:
session.place_active_order(symbol=scaled_order['symbol'], side=scaled_order['side'], order_type=scaled_order['ordertype'], qty=order_amount, price=order_price, close_on_trigger=False, reduce_only=False, time_in_force="PostOnly")
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + scaled_order['symbol'] + " Scaled Open Order Placed: "+str(scaled_order['side'])+" "+str(scaled_order['ordertype'])+" "+str(order_amount)+" @ "+str(order_price)+"."
print(log)
with open("ScaledOrders.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
elif scaled_order['orderExec'] == 'Close':
try:
session.place_active_order(symbol=scaled_order['symbol'], side=scaled_order['side'], order_type=scaled_order['ordertype'], qty=order_amount, price=order_price, close_on_trigger=True, reduce_only=True, time_in_force="PostOnly")
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + scaled_order['symbol'] + " Scaled Close Order Placed: "+str(scaled_order['side'])+" "+str(scaled_order['ordertype'])+" "+str(order_amount)+" @ "+str(order_price)+"."
print(log)
with open("ScaledOrders.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
try:
mycursor.execute("DELETE FROM scaled_orders WHERE id="+str(scaled_order['id']))
mydb.commit()
except Exception:
pass
### Now we work with active Positions ###
# Fetch list of active positions
fetched_sessions = []
fetched_positions = []
try:
fetched_positions = session.my_position(endpoint="/private/linear/position/list")['result'] # USDT Perpetual
except Exception:
pass
if(fetched_positions):
for position in fetched_positions:
if position['is_valid'] == True and position['data']["size"] > 0: # Required per the ByBit API to be is_valid=True data, and we only want the active positions (size>0)
fetched_sessions.append(position['data'])
try:
fetched_positions = session.my_position(endpoint="/v2/private/position/list")['result'] # Inverse Perpetual
except Exception:
pass
if(fetched_positions):
for position in fetched_positions:
if position['is_valid'] == True and position['data']["size"] > 0: # Required per the ByBit API to be is_valid=True data, and we only want the active positions (size>0)
fetched_sessions.append(position['data'])
try:
fetched_positions = session.my_position(endpoint="/futures/private/position/list")['result'] # Inverse Futures
except Exception:
pass
if(fetched_positions):
for position in fetched_positions:
if position['is_valid'] == True and position['data']["size"] > 0: # Required per the ByBit API to be is_valid=True data, and we only want the active positions (size>0)
fetched_sessions.append(position['data'])
# First we clear all
# 1) TB SLs and Initial Total Balance SLs database (if exists). We loop through active positions, and DELETE from DB any position for pairs other than those (that are active and got Initial Total Balance Stop Loss executed for).
# 2) Position Sessions that are not active anymore
active_positions_string_excluded = ""
active_positions_sessions_string_excluded = ""
for position in fetched_sessions:
symbol = position["symbol"]
side = position["side"]
active_positions_string_excluded += " AND NOT (symbol = '"+symbol+"' AND side = '"+side+"')"
active_positions_sessions_string_excluded += " AND NOT (symbol = '"+symbol+"')"
# Now we remove all DB entries for any positions other than the currently Active ones
try:
mycursor.execute("DELETE FROM positions_stops WHERE api_key = '"+api_key+"' AND api_secret = '"+api_secret+"' "+active_positions_string_excluded)
mydb.commit()
except Exception:
pass
try:
mycursor.execute("DELETE FROM positions_tb_sl WHERE api_key = '"+api_key+"' AND api_secret = '"+api_secret+"' "+active_positions_string_excluded)
mydb.commit()
except Exception:
pass
try:
mycursor.execute("DELETE FROM positions_sessions WHERE api_key = '"+api_key+"' AND api_secret = '"+api_secret+"' "+active_positions_sessions_string_excluded)
mydb.commit()
except Exception:
pass
# Now we INSERT Positions Sessions that are active OR UPDATE their Total Balance value if a hedge already locked the full position value
for position in fetched_sessions:
symbol = position["symbol"]
side = position["side"]
long_pos_size = 0
short_pos_size = 0
long_pos_value = 0
short_pos_value = 0
hedge_found = False
balanced_hedge_found = False
if position['side'] == "Sell":
opposite_side = "Buy"
short_pos_size = position['size']
short_pos_value = position['position_value']
elif position['side'] == "Buy":
opposite_side = "Sell"
long_pos_size = position['size']
long_pos_value = position['position_value']
# Now we loop open positions to find is opposite position side exists and is balanced (same sizes)
for position2 in fetched_sessions:
if position2['symbol'] == position['symbol'] and position2['side'] == opposite_side:
if position['side'] == "Sell":
long_pos_size = position2['size']
long_pos_value = position2['position_value']
elif position['side'] == "Buy":
short_pos_size = position2['size']
short_pos_value = position2['position_value']
hedge_found = True
if position2['size'] == position['size']:
balanced_hedge_found = True
# Fetch latest Balance value
if quote_currency[symbol] == "USDT":
equity = session.get_wallet_balance(coin="USDT")["result"]["USDT"]["equity"]
else:
equity = session.get_wallet_balance(coin=base_currency[symbol])["result"][base_currency[symbol]]["equity"]
# Fetch last_price to store it realtime
try:
fetched_latest_tickers = session.latest_information_for_symbol(symbol=symbol)['result']
except Exception:
pass
if(fetched_latest_tickers):
for ticker in fetched_latest_tickers:
if ticker['symbol'] == symbol:
last_price = float(ticker['last_price'])
if hedge_found:
if balanced_hedge_found:
# Balanced hedge exists, so UPDATE the Balance of the session
try:
mycursor_add_positions_sessions = mydb.cursor(dictionary=True)
insert_sql = "INSERT INTO positions_sessions (api_key, api_secret, symbol, last_balanced_equity, realtime_equity, realtime_price, hedged, balanced_hedge, last_updated, current_long_pos_size, current_short_pos_size, current_long_pos_value, current_short_pos_value, current_balancer_hedge_price) VALUES (%s, %s, %s, %s, %s, %s, 1, 1, NOW(), %s, %s, %s, %s, NULL) ON DUPLICATE KEY UPDATE last_balanced_equity=%s, highest_equity = GREATEST(highest_equity, %s), hedged=1, balanced_hedge=1, last_updated=NOW(), realtime_equity=%s, realtime_price=%s, current_long_pos_size=%s, current_short_pos_size=%s, current_long_pos_value=%s, current_short_pos_value=%s, current_balancer_hedge_price=NULL;"
vals = (api_key, api_secret, symbol, equity, equity, last_price, long_pos_size, short_pos_size, long_pos_value, short_pos_value, equity, equity, equity, last_price, long_pos_size, short_pos_size, long_pos_value, short_pos_value)
mycursor_add_positions_sessions.execute(insert_sql, vals)
mydb.commit()
except Exception:
pass
else:
# Just a hedge exists, so UPDATE just mark that
try:
mycursor_add_positions_sessions = mydb.cursor(dictionary=True)
insert_sql = "INSERT INTO positions_sessions (api_key, api_secret, symbol, hedged, last_updated, current_long_pos_size, current_short_pos_size, current_long_pos_value, current_short_pos_value, realtime_equity, realtime_price) VALUES (%s, %s, %s, 1, NOW(), %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE hedged=1, last_updated=NOW(), current_long_pos_size=%s, current_short_pos_size=%s, current_long_pos_value=%s, current_short_pos_value=%s, realtime_equity=%s, realtime_price=%s;"
vals = (api_key, api_secret, symbol, long_pos_size, short_pos_size, long_pos_value, short_pos_value, equity, last_price, long_pos_size, short_pos_size, long_pos_value, short_pos_value, equity, last_price)
mycursor_add_positions_sessions.execute(insert_sql, vals)
mydb.commit()
except Exception:
pass
else:
# No Balanced hedge exists, so only INSERT new row to the database (if it doesn't exist)
try:
mycursor_add_positions_sessions = mydb.cursor(dictionary=True)
insert_sql = "INSERT INTO positions_sessions (api_key, api_secret, symbol, initial_equity, highest_equity, realtime_equity, realtime_price, current_long_pos_size, current_short_pos_size, current_long_pos_value, current_short_pos_value) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE current_long_pos_size=%s, current_short_pos_size=%s, current_long_pos_value=%s, current_short_pos_value=%s, realtime_equity=%s, realtime_price=%s;"
vals = (api_key, api_secret, symbol, equity, equity, equity, last_price, long_pos_size, short_pos_size, long_pos_value, short_pos_value, long_pos_size, short_pos_size, long_pos_value, short_pos_value, equity, last_price)
mycursor_add_positions_sessions.execute(insert_sql, vals)
mydb.commit()
except Exception:
pass
# Now we clear any Genie Hedges pending Conditional Orders (stored in the DB) left if opposite positions already closed manually OR positions of both sides exist and it is not a Balancer Hedge
mycursor = mydb.cursor(dictionary=True)
mycursor.execute("SELECT * FROM positions_hedges WHERE api_key='"+api_key+"' AND api_secret='"+api_secret+"'")
myresult = mycursor.fetchall()
for position_hedge in myresult:
if position_hedge['order_link_id'].startswith('CryptoGenieHedge'):
# Note: order side should be opposite of position side
same_side_position_found = False
opposite_side_position_found = False
if position_hedge['side'] == "Sell":
conditional_opposite_side = "Buy"
elif position_hedge['side'] == "Buy":
conditional_opposite_side = "Sell"
# Now we loop open positions to find what position sides are open for this asset
for position in fetched_sessions:
if position["symbol"] == position_hedge['symbol'] and position["side"] == position_hedge['side']:
same_side_position_found = True
if position["symbol"] == position_hedge['symbol'] and position["side"] == conditional_opposite_side:
opposite_side_position_found = True
if not opposite_side_position_found or (opposite_side_position_found and same_side_position_found):
# Position opposite of Hedge not found, so we remove this Hedge conditional order
# OR If we found both sides positions open
try:
session.cancel_conditional_order(symbol=position_hedge['symbol'], stop_order_id=position_hedge['stop_order_id'])
except Exception:
pass
try:
mycursor.execute("DELETE FROM positions_hedges WHERE stop_order_id='"+position_hedge['stop_order_id']+"' and api_key='"+api_key+"' AND api_secret='"+api_secret+"'")
mydb.commit()
except Exception:
pass
# Now we go through all positions to perform Genie's operations :-)
for position in fetched_sessions:
position_idx = ""
mode = ""
symbol = position["symbol"]
side = position["side"]
size = float(position["size"])
position_value = float(position["position_value"])
leverage = float(position["leverage"])
stop_loss = float(position["stop_loss"])
entry_price = float(position["entry_price"])
# unrealised_pnl = float(position["unrealised_pnl"]) # We will not use this as the current API is not returning the real-time unrealised_pnl value properly, we will need to manually calculate it for each position
final_decimals_count = str(tick_size[symbol])[::-1].find('.') # Tick Size number of decimals
tp_sl_mode = position["tp_sl_mode"] # "Partial" or "Full" position TP/SL mode [Currently not supported in WebSocket API]
if "position_idx" in position:
position_idx = position["position_idx"] # 0 for One-Way Mode, 1 for Buy in Hedge Mode, 2 for Sell in Hedge Mode [Currently not supported in WebSocket API]
if "mode" in position:
mode = position["mode"] # 0 for One-Way Mode, 3 for Hedge Mode
#######################################################
# Enforce Static Stop Loss feature
#######################################################
if(enforce_sl_static):
if symbol in override_sl_static_cap_ratio: # Look if any custom stop ratio for this symbol
stop_loss_cap_ratio = override_sl_static_cap_ratio[symbol]
else:
stop_loss_cap_ratio = default_sl_static_cap_ratio
if stop_loss_cap_ratio != 0:
# FIRST check if immediate market close is needed in case price already breached with no Stop Loss in place
# Fetch latest tickers
try:
fetched_latest_tickers = session.latest_information_for_symbol(symbol=symbol)['result']
except Exception:
pass
if(fetched_latest_tickers):
for ticker in fetched_latest_tickers:
if ticker['symbol'] == symbol:
last_price = float(ticker['last_price'])
if side == 'Buy':
position_leveraged_stop_loss = round_to_tick(entry_price - (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if last_price < position_leveraged_stop_loss:
try:
session.place_active_order(position_idx=position_idx, symbol=symbol, side="Sell", order_type="Market", qty=size, time_in_force="GoodTillCancel", reduce_only=True, close_on_trigger=True)
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + symbol + " LONG Force-Stopped: "+str(last_price)+"."
print(log)
with open("SL_forced.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
elif side == 'Sell':
position_leveraged_stop_loss = round_to_tick(entry_price + (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if last_price > position_leveraged_stop_loss:
try:
session.place_active_order(position_idx=position_idx, symbol=symbol, side="Buy", order_type="Market", qty=size, time_in_force="GoodTillCancel", reduce_only=True, close_on_trigger=True)
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + symbol + " SHORT Force-Stopped: "+str(last_price)+"."
print(log)
with open("SL_forced.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
# Otherwise, search Conditional Orders if Stop Loss already exists with 'qty'=position size AND 'trigger_price' at the required price
full_static_sl_found = False
try:
fetched_conditional_orders = session.query_conditional_order(symbol=symbol)
except Exception:
pass
if(fetched_conditional_orders):
for conditional_order in fetched_conditional_orders["result"]:
# Note: order side should be opposite of position side
if side == "Buy" and conditional_order['side'] == "Sell" and conditional_order['order_type'] == 'Market' and conditional_order['order_status'] == 'Untriggered': # Stop Loss for a Long
if symbol.endswith('USDT'): # USDT Perpetual
stop_price = float(conditional_order['trigger_price'])
stop_order_id = conditional_order['stop_order_id']
if stop_price < entry_price and conditional_order['close_on_trigger'] == True and conditional_order['reduce_only'] == True:
position_leveraged_stop_loss = round_to_tick(entry_price - (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if (stop_price == position_leveraged_stop_loss or (stop_price > entry_price and last_price > entry_price)) and conditional_order['qty'] == size:
# Stop Loss found at the static ratio OR in profit, keep it
full_static_sl_found = True
else:
# Stop Loss found but not at the static price, remove it
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
else: # Inverse Perpetuals or Futures
stop_price = float(conditional_order['stop_px'])
stop_order_id = conditional_order['order_id']
position_leveraged_stop_loss = round_to_tick(entry_price - (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if (stop_price == position_leveraged_stop_loss or (stop_price > entry_price and last_price > entry_price)) and conditional_order['qty'] == size:
# Stop Loss found at the static ratio OR in profit, keep it
full_static_sl_found = True
else:
# Stop Loss found but not at the static price, remove it
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
elif side == "Sell" and conditional_order['side'] == "Buy" and conditional_order['order_type'] == 'Market' and conditional_order['order_status'] == 'Untriggered': # Stop Loss for a Short
if symbol.endswith('USDT'): # USDT Perpetual
stop_price = float(conditional_order['trigger_price'])
stop_order_id = conditional_order['stop_order_id']
if stop_price > entry_price and conditional_order['close_on_trigger'] == True and conditional_order['reduce_only'] == True:
position_leveraged_stop_loss = round_to_tick(entry_price + (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if (stop_price == position_leveraged_stop_loss or (stop_price < entry_price and last_price < entry_price)) and conditional_order['qty'] == size:
# Stop Loss found at the static ratio OR in profit, keep it
full_static_sl_found = True
else:
# Stop Loss found but not at the static price, remove it
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
else: # Inverse Perpetuals or Futures
stop_price = float(conditional_order['stop_px'])
stop_order_id = conditional_order['order_id']
position_leveraged_stop_loss = round_to_tick(entry_price + (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if (stop_price == position_leveraged_stop_loss or (stop_price < entry_price and last_price < entry_price)) and conditional_order['qty'] == size:
# Stop Loss found at the static ratio OR in profit, keep it
full_static_sl_found = True
else:
# Stop Loss found but not at the static price, remove it
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
if full_static_sl_found == False:
# We couldn't find a static Stop Loss, so add it
# Prepare set_trading_stop arguments to pass to API
set_trading_stop_args = {'position_idx': position_idx, 'symbol': symbol, 'side': side}
if tp_sl_mode == "Partial":
set_trading_stop_args['sl_size'] = size # If Partial Mode then we need to send full size to close full position
if side == 'Buy':
position_leveraged_stop_loss = round_to_tick(entry_price - (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if stop_loss == 0 or stop_loss < position_leveraged_stop_loss:
try:
set_trading_stop_args['stop_loss'] = position_leveraged_stop_loss
session.set_trading_stop(**set_trading_stop_args)
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + symbol + " LONG Maximum Static Stop-Loss adjusted to: "+str(position_leveraged_stop_loss)+" (" + str(stop_loss_cap_ratio) + "%)."
print(log)
with open("SL_protected.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
elif side == 'Sell':
position_leveraged_stop_loss = round_to_tick(entry_price + (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if stop_loss == 0 or stop_loss > position_leveraged_stop_loss:
try:
set_trading_stop_args['stop_loss'] = position_leveraged_stop_loss
session.set_trading_stop(**set_trading_stop_args)
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + symbol + " SHORT Maximum Static Stop-Loss adjusted to: "+str(position_leveraged_stop_loss)+" (" + str(stop_loss_cap_ratio) + "%)."
print(log)
with open("SL_protected.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
#######################################################
# Enforce Stop Loss Range feature
#######################################################
if(enforce_sl_range):
if symbol in override_sl_range_cap_ratio: # Look if any custom stop ratio for this symbol
stop_loss_cap_ratio = override_sl_range_cap_ratio[symbol]
else:
stop_loss_cap_ratio = default_sl_range_cap_ratio
if stop_loss_cap_ratio != 0:
# FIRST check if immediate market close is needed in case price already breached with no Stop Loss in place
# Fetch latest tickers
try:
fetched_latest_tickers = session.latest_information_for_symbol(symbol=symbol)['result']
except Exception:
pass
if(fetched_latest_tickers):
for ticker in fetched_latest_tickers:
if ticker['symbol'] == symbol:
last_price = float(ticker['last_price'])
if side == 'Buy':
position_leveraged_stop_loss = round_to_tick(entry_price - (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if last_price < position_leveraged_stop_loss:
try:
session.place_active_order(position_idx=position_idx, symbol=symbol, side="Sell", order_type="Market", qty=size, time_in_force="GoodTillCancel", reduce_only=True, close_on_trigger=True)
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + symbol + " LONG Force-Stopped: "+str(last_price)+"."
print(log)
with open("SL_forced.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
elif side == 'Sell':
position_leveraged_stop_loss = round_to_tick(entry_price + (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if last_price > position_leveraged_stop_loss:
try:
session.place_active_order(position_idx=position_idx, symbol=symbol, side="Buy", order_type="Market", qty=size, time_in_force="GoodTillCancel", reduce_only=True, close_on_trigger=True)
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + symbol + " SHORT Force-Stopped: "+str(last_price)+"."
print(log)
with open("SL_forced.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
# Otherwise, search Conditional Orders if Stop Loss already exists with 'qty'=position size AND 'trigger_price' within allowed range
total_allowed_stop_loss_found = 0.0
try:
fetched_conditional_orders = session.query_conditional_order(symbol=symbol)
except Exception:
pass
if(fetched_conditional_orders):
for conditional_order in fetched_conditional_orders["result"]:
# Note: order side should be opposite of position side
if side == "Buy" and conditional_order['side'] == "Sell" and conditional_order['order_type'] == 'Market' and conditional_order['order_status'] == 'Untriggered': # Stop Loss for a Long
if symbol.endswith('USDT'): # USDT Perpetual
stop_price = float(conditional_order['trigger_price'])
stop_order_id = conditional_order['stop_order_id']
if stop_price < entry_price and conditional_order['close_on_trigger'] == True and conditional_order['reduce_only'] == True:
position_leveraged_stop_loss = round_to_tick((entry_price - (((stop_loss_cap_ratio/100) / leverage) * entry_price)), tick_size[symbol])
if stop_price >= position_leveraged_stop_loss and float(conditional_order['qty']) == size:
# Stop Loss found inside the allowed range, keep it
total_allowed_stop_loss_found += float(conditional_order['qty'])
else:
# Stop Loss found outside the allowed range, useless so remove it
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
else: # Inverse Perpetuals or Futures
stop_price = float(conditional_order['stop_px'])
stop_order_id = conditional_order['order_id']
position_leveraged_stop_loss = round_to_tick((entry_price - (((stop_loss_cap_ratio/100) / leverage) * entry_price)), tick_size[symbol])
if stop_price >= position_leveraged_stop_loss and float(conditional_order['qty']) == size:
# Stop Loss found inside the allowed range, keep it
total_allowed_stop_loss_found += float(conditional_order['qty'])
else:
# Stop Loss found outside the allowed range, useless so remove it
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
elif side == "Sell" and conditional_order['side'] == "Buy" and conditional_order['order_type'] == 'Market' and conditional_order['order_status'] == 'Untriggered': # Stop Loss for a Short
if symbol.endswith('USDT'): # USDT Perpetual
stop_price = float(conditional_order['trigger_price'])
stop_order_id = conditional_order['stop_order_id']
if stop_price > entry_price and conditional_order['close_on_trigger'] == True and conditional_order['reduce_only'] == True:
position_leveraged_stop_loss = round_to_tick((entry_price + (((stop_loss_cap_ratio/100) / leverage) * entry_price)), tick_size[symbol])
if stop_price <= position_leveraged_stop_loss and float(conditional_order['qty']) == size:
# Stop Loss found inside the allowed range, keep it
total_allowed_stop_loss_found += float(conditional_order['qty'])
else:
# Stop Loss found outside the allowed range, useless so remove it
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
else: # Inverse Perpetuals or Futures
stop_price = float(conditional_order['stop_px'])
stop_order_id = conditional_order['order_id']
position_leveraged_stop_loss = round_to_tick((entry_price + (((stop_loss_cap_ratio/100) / leverage) * entry_price)), tick_size[symbol])
if stop_price <= position_leveraged_stop_loss and float(conditional_order['qty']) == size:
# Stop Loss found inside the allowed range, keep it
total_allowed_stop_loss_found += float(conditional_order['qty'])
else:
# Stop Loss found outside the allowed range, useless so remove it
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
if total_allowed_stop_loss_found < size:
# We couldn't find enough Stop Losses in the allowed range, so remove any conditional orders and add 1 Stop Loss conditional order with total size, at the correct level
# Prepare set_trading_stop arguments to pass to API
set_trading_stop_args = {'position_idx': position_idx, 'symbol': symbol, 'side': side}
if tp_sl_mode == "Partial":
set_trading_stop_args['sl_size'] = size # If Partial Mode then we need to send full size to close full position
if side == 'Buy':
position_leveraged_stop_loss = round_to_tick(entry_price - (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if stop_loss == 0 or stop_loss < position_leveraged_stop_loss:
try:
#session.place_conditional_order(symbol=symbol, order_type="Market", reduce_only=True, side= "Sell", qty=size, stop_px=position_leveraged_stop_loss,time_in_force="GoodTillCancel")
set_trading_stop_args['stop_loss'] = position_leveraged_stop_loss
session.set_trading_stop(**set_trading_stop_args)
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + symbol + " LONG Maximum Stop-Loss adjusted to: "+str(position_leveraged_stop_loss)+" (" + str(stop_loss_cap_ratio) + "%)."
print(log)
with open("SL_protected.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
elif side == 'Sell':
position_leveraged_stop_loss = round_to_tick(entry_price + (((stop_loss_cap_ratio/100) / leverage) * entry_price), tick_size[symbol])
if stop_loss == 0 or stop_loss > position_leveraged_stop_loss:
try:
#session.place_conditional_order(symbol=symbol, order_type="Market", reduce_only=True, side= "Buy", qty=size, stop_px=position_leveraged_stop_loss,time_in_force="GoodTillCancel")
set_trading_stop_args['stop_loss'] = position_leveraged_stop_loss
session.set_trading_stop(**set_trading_stop_args)
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + symbol + " SHORT Maximum Stop-Loss adjusted to: "+str(position_leveraged_stop_loss)+" (" + str(stop_loss_cap_ratio) + "%)."
print(log)
with open("SL_protected.txt", "a") as myfile:
myfile.write(log+'\n')
except Exception:
pass
#######################################################
# Enforce Take Profits feature
#######################################################
if(enforce_tp):
# Fetch latest tickers
try:
fetched_latest_tickers = session.latest_information_for_symbol(symbol=symbol)['result']
except Exception:
pass
if(fetched_latest_tickers):
for ticker in fetched_latest_tickers:
if ticker['symbol'] == symbol:
last_price = float(ticker['last_price'])
if side == 'Buy':
# Sarch Conditional Orders if Take Profits already exist
tp_found = False
try:
fetched_conditional_orders = session.query_conditional_order(symbol=symbol)
except Exception:
pass
if(fetched_conditional_orders):
for conditional_order in fetched_conditional_orders["result"]:
if not tp_found: # If we found a valid TP, no need to iterate any more
if symbol.endswith('USDT'): # USDT Perpetual
stop_price = float(conditional_order['trigger_price'])
stop_order_id = conditional_order['stop_order_id']
if conditional_order['side'] == 'Sell' and stop_price > last_price and stop_price > entry_price and conditional_order['close_on_trigger'] == True and conditional_order['reduce_only'] == True:
# Take Profit found, make sure it is one of the pre-defined ones and make sure its quantity is up to date as well
for elem in default_tp.items():
tp_price_ratio = float(elem[0])
tp_size_ratio = float(elem[1])
tp_price = round_to_tick(entry_price + (((tp_price_ratio/100) / leverage) * entry_price), tick_size[symbol])
tp_size = round_step_size(size * (tp_size_ratio / 100),qty_step[symbol],min_trading_qty[symbol])
if tp_price==stop_price and (tp_size==conditional_order['qty'] or math.floor(tp_size * 10)/10.0==conditional_order['qty'] or math.floor(tp_size * 100)/100.0==conditional_order['qty'] or math.floor(tp_size * 1000)/1000.0==conditional_order['qty'] or math.floor(tp_size * 10000)/10000.0==conditional_order['qty']):
# We found a valid pre-defined TP, keep it (note we check the floor in case the exchange did remove decimals upon creating the order)
tp_found = True
if not tp_found:
# Invalid TP (or updated position size not reflected in the TP), REMOVE IT
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
else: # Inverse Perpetuals or Futures
stop_price = float(conditional_order['stop_px'])
stop_order_id = conditional_order['order_id']
if conditional_order['side'] == 'Sell' and stop_price > last_price and stop_price > entry_price:
# Take Profit found, make sure it is one of the pre-defined ones and make sure its quantity is up to date as well
for elem in default_tp.items():
tp_price_ratio = float(elem[0])
tp_size_ratio = float(elem[1])
tp_price = round_to_tick(entry_price + (((tp_price_ratio/100) / leverage) * entry_price), tick_size[symbol])
tp_size = round_step_size(size * (tp_size_ratio / 100),qty_step[symbol],min_trading_qty[symbol])
if tp_price==stop_price and (tp_size==conditional_order['qty'] or math.floor(tp_size * 10)/10.0==conditional_order['qty'] or math.floor(tp_size * 100)/100.0==conditional_order['qty'] or math.floor(tp_size * 1000)/1000.0==conditional_order['qty'] or math.floor(tp_size * 10000)/10000.0==conditional_order['qty']):
# We found a valid pre-defined TP, keep it (note we check the floor in case the exchange did remove decimals upon creating the order)
tp_found = True
if not tp_found:
# Invalid TP (or updated position size not reflected in the TP), REMOVE IT
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)
except Exception:
pass
if not tp_found: # No TPs found, so add (this way we kind of avoid re-adding the same TP if price hit and found resistance at and retested it. so we don't TP the same level twice)
# We couldn't find any TPs, let's add the suitable one
# Prepare set_trading_stop arguments to pass to API
set_trading_stop_args = {'position_idx': position_idx, 'symbol': symbol, 'side': side}
for elem in sorted(default_tp.items(), reverse=False): # Sort Ascending to find the nearest TP level
tp_price_ratio = float(elem[0])
tp_size_ratio = float(elem[1])
set_trading_stop_args['take_profit'] = round_to_tick(entry_price + (((tp_price_ratio/100) / leverage) * entry_price), tick_size[symbol])
set_trading_stop_args['tp_size'] = tp_size = round_step_size(size * (tp_size_ratio / 100),qty_step[symbol],min_trading_qty[symbol])
if last_price < set_trading_stop_args['take_profit'] - (default_tp_tolerance_ratio/100) * (set_trading_stop_args['take_profit'] - entry_price):
try:
session.set_trading_stop(**set_trading_stop_args)
log = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ": " + (log_label + ": " if log_label != "" else "") + symbol + " LONG Take-Profit Market placed: "+str(tp_size_ratio)+"% of Quantity ("+str(set_trading_stop_args['tp_size'])+") @ "+ str(tp_price_ratio) +"% in Profit ("+str(set_trading_stop_args['take_profit'])+")."
print(log)
with open("TP.txt", "a") as myfile:
myfile.write(log+'\n')
break # No need to add more TPs, we only place 1 TP at a time
except Exception:
pass
elif side == 'Sell':
# Sarch Conditional Orders if Take Profits already exist
tp_found = False
try:
fetched_conditional_orders = session.query_conditional_order(symbol=symbol)
except Exception:
pass
if(fetched_conditional_orders):
for conditional_order in fetched_conditional_orders["result"]:
if not tp_found: # If we found a valid TP, no need to iterate any more
if symbol.endswith('USDT'): # USDT Perpetual
stop_price = float(conditional_order['trigger_price'])
stop_order_id = conditional_order['stop_order_id']
if conditional_order['side'] == 'Buy' and stop_price < last_price and stop_price < entry_price and conditional_order['close_on_trigger'] == True and conditional_order['reduce_only'] == True:
# Take Profit found, make sure it is one of the pre-defined ones and make sure its quantity is up to date as well
for elem in default_tp.items():
tp_price_ratio = float(elem[0])
tp_size_ratio = float(elem[1])
tp_price = round_to_tick(entry_price - (((tp_price_ratio/100) / leverage) * entry_price), tick_size[symbol])
tp_size = round_step_size(size * (tp_size_ratio / 100),qty_step[symbol],min_trading_qty[symbol])
if tp_price==stop_price and (tp_size==conditional_order['qty'] or math.floor(tp_size * 10)/10.0==conditional_order['qty'] or math.floor(tp_size * 100)/100.0==conditional_order['qty'] or math.floor(tp_size * 1000)/1000.0==conditional_order['qty'] or math.floor(tp_size * 10000)/10000.0==conditional_order['qty']):
# We found a valid pre-defined TP, keep it (note we check the floor in case the exchange did remove decimals upon creating the order)
tp_found = True
if not tp_found:
# Invalid TP (or updated position size not reflected in the TP), REMOVE IT
try:
session.cancel_conditional_order(symbol=symbol, stop_order_id=stop_order_id)