-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.py
2066 lines (1717 loc) · 93.7 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ccxt
from flask import Flask, request, abort
from werkzeug.middleware.proxy_fix import ProxyFix
from threading import Timer
import os
import time
import os
import json
import copy
import logging
from datetime import datetime
from decimal import Decimal, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_EVEN
from pprint import pprint
def fixVersionFormat( version )->str:
vl = version.split(".")
return f'{vl[0]}.{vl[1]}.{vl[2].zfill(3)}'
minCCXTversion = '4.2.82'
CCXTversion = fixVersionFormat(ccxt.__version__)
print( 'CCXT Version:', ccxt.__version__)
if( CCXTversion < fixVersionFormat(minCCXTversion) ):
print( '\n============== * WARNING * ==============')
print( 'WHOOK requires CCXT version', minCCXTversion,' or higher.')
print( 'While it may run with earlier versions wrong behaviors are expected to happen.' )
print( 'Please update CCXT.' )
print( '============== * WARNING * ==============\n')
###################
##### Globals #####
###################
verbose = False
debug_order = False
SHOW_BALANCE = False # print account balance at exchange initialization
SHOW_LIQUIDATION = False # in positions when available
SHOW_BREAKEVEN = True # in positions when available
SHOW_ENTRYPRICE = False # in positions
USE_PROXY = False
PORT = 80
PROXY_PORT = 50000
ALERT_TIMEOUT = 60 * 3
ORDER_TIMEOUT = 40
REFRESH_POSITIONS_FREQUENCY = 5 * 60 # refresh positions every 5 minutes
UPDATE_ORDERS_FREQUENCY = 0.25 # frametime in seconds at which the orders queue is refreshed.
LOGS_DIRECTORY = 'logs'
MARGIN_MODE_NONE = '------'
#### Open config file #####
def writeConfig():
with open('config.json', 'w') as f:
configString = '[\n\t{\n'
configString += '\t\t"ALERT_TIMEOUT":'+str(ALERT_TIMEOUT)+',\n'
configString += '\t\t"ORDER_TIMEOUT":'+str(ORDER_TIMEOUT)+',\n'
configString += '\t\t"REFRESH_POSITIONS_FREQUENCY":'+str(REFRESH_POSITIONS_FREQUENCY)+',\n'
configString += '\t\t"UPDATE_ORDERS_FREQUENCY":'+str(UPDATE_ORDERS_FREQUENCY)+',\n'
configString += '\t\t"VERBOSE":'+str(verbose).lower()+',\n'
configString += '\t\t"SHOW_BALANCE":'+str(SHOW_BALANCE).lower()+',\n'
configString += '\t\t"SHOW_ENTRYPRICE":'+str(SHOW_ENTRYPRICE).lower()+',\n'
configString += '\t\t"SHOW_LIQUIDATION":'+str(SHOW_LIQUIDATION).lower()+',\n'
configString += '\t\t"SHOW_BREAKEVEN":'+str(SHOW_BREAKEVEN).lower()+',\n'
configString += '\t\t"LOGS_DIRECTORY":"'+str(LOGS_DIRECTORY)+'",\n'
configString += '\t\t"USE_PROXY":'+str(USE_PROXY).lower()+',\n'
configString += '\t\t"PROXY_PORT":'+str(PROXY_PORT)+'\n'
configString += '\t}\n]'
f.write( configString )
f.close()
try:
with open('config.json', 'r') as config_file:
config = json.load(config_file)
config = config[0]
config_file.close()
except FileNotFoundError:
writeConfig()
print( "Config file created.\n----------------------------")
else:
# parse the config file
if( config.get('ALERT_TIMEOUT') != None ):
ALERT_TIMEOUT = int(config.get('ALERT_TIMEOUT'))
if( config.get('ORDER_TIMEOUT') != None ):
ORDER_TIMEOUT = int(config.get('ORDER_TIMEOUT'))
if( config.get('REFRESH_POSITIONS_FREQUENCY') != None ):
REFRESH_POSITIONS_FREQUENCY = int(config.get('REFRESH_POSITIONS_FREQUENCY'))
if( config.get('UPDATE_ORDERS_FREQUENCY') != None ):
UPDATE_ORDERS_FREQUENCY = float(config.get('UPDATE_ORDERS_FREQUENCY'))
if( config.get('SHOW_BALANCE') != None ):
SHOW_BALANCE = bool(config.get('SHOW_BALANCE'))
if( config.get('SHOW_ENTRYPRICE') != None ):
SHOW_ENTRYPRICE = bool(config.get('SHOW_ENTRYPRICE'))
if( config.get('SHOW_LIQUIDATION') != None ):
SHOW_LIQUIDATION = bool(config.get('SHOW_LIQUIDATION'))
if( config.get('SHOW_BREAKEVEN') != None ):
SHOW_BREAKEVEN = bool(config.get('SHOW_BREAKEVEN'))
if( config.get('VERBOSE') != None ):
verbose = bool(config.get('VERBOSE'))
if( config.get('LOGS_DIRECTORY') != None ):
LOGS_DIRECTORY = str(config.get('LOGS_DIRECTORY'))
if( config.get('USE_PROXY') != None ):
USE_PROXY = bool(config.get('USE_PROXY'))
if( config.get('PROXY_PORT') != None ):
PROXY_PORT = int(config.get('PROXY_PORT'))
#rewrite the config file
writeConfig()
##### Utils #####
def dateString():
return datetime.today().strftime("%Y/%m/%d")
def timeNow():
return time.strftime("%H:%M:%S")
def roundUpTick( value: float, tick: str ):
if type(tick) is not str: tick = str(tick)
if type(value) is not Decimal: value = Decimal( value )
return float( value.quantize( Decimal(tick), ROUND_CEILING ) )
def roundDownTick( value: float, tick: str ):
if type(tick) is not str: tick = str(tick)
if type(value) is not Decimal: value = Decimal( value )
return float( value.quantize( Decimal(tick), ROUND_FLOOR ) )
def roundToTick( value: float, tick: float ):
if type(tick) is not str: tick = str(tick)
if type(value) is not Decimal: value = Decimal( value )
return float( value.quantize( Decimal(tick), ROUND_HALF_EVEN ) )
class RepeatTimer(Timer):
def run(self):
while not self.finished.wait(self.interval):
self.function(*self.args, **self.kwargs)
class position_c:
def __init__(self, symbol, position, thisMarket = None ) -> None:
self.symbol = symbol
self.position = position
self.thisMarket = thisMarket
def getKey(self, key):
return self.position.get(key)
def generatePrintString(self)->str:
if( self.thisMarket == None ):
return ''
p = 0.0
unrealizedPnl = 0 if(self.getKey('unrealizedPnl') == None) else float(self.getKey('unrealizedPnl'))
initialMargin = 0 if(self.getKey('initialMargin') == None) else float(self.getKey('initialMargin'))
collateral = 0.0 if(self.getKey('collateral') == None) else float(self.getKey('collateral'))
if( initialMargin != 0 ):
p = ( unrealizedPnl / initialMargin ) * 100.0
elif( collateral != 0):
p = ( unrealizedPnl / (collateral - unrealizedPnl) ) * 100
positionModeChar = '[H]' if (self.thisMarket['local']['positionMode'] == 'hedged') else ''
levStr = "?x" if (self.thisMarket['local']['leverage'] == 0 ) else str(self.thisMarket['local']['leverage']) + 'x'
string = self.symbol + positionModeChar
string += ' * ' + self.thisMarket['local']['marginMode'] + ':' + levStr
string += ' * ' + self.getKey('side')
string += ' * ' + str( self.getKey('contracts') )
if( initialMargin != 0 ) : string += ' * ' + "{:.4f}[$]".format(initialMargin)
elif( collateral != 0) : string += ' * ' + "{:.4f}[$]".format(collateral)
string += ' * ' + "{:.2f}[$]".format(unrealizedPnl)
string += ' * ' + "{:.2f}".format(p) + '%'
if( self.getKey('entryPrice') != None and SHOW_ENTRYPRICE ):
string += ' * ' + "[ep]{:.3f}".format(float(self.getKey('entryPrice')))
if( self.getKey('liquidationPrice') != None and SHOW_LIQUIDATION ):
string += ' * ' + "[li]{:.3f}".format(float(self.getKey('liquidationPrice')))
# OKX and Bitget provide the position breakeven price info:bePx. Let's print that too
if( self.getKey('info') != None ):
be = self.getKey('info').get('bePx')
if( be == None ):
be = self.getKey('info').get('breakEvenPrice')
if( be != None and SHOW_BREAKEVEN ):
string += ' * ' + "[be]{:.4f}".format(float(be))
return string
class order_c:
def __init__(self, symbol = "", side = "", quantity = 0.0, leverage = 1, delay = 0, reduceOnly = False) -> None:
self.symbol = symbol
self.type = 'market'
self.side = side
self.quantity = quantity
self.leverage = leverage
self.price = None
self.customID = None
self.reduced = False
self.reduceOnly = True if leverage == 0 else reduceOnly
self.id = ""
self.delay = delay
self.timestamp = time.monotonic()
def timedOut(self):
return ( self.timestamp + ORDER_TIMEOUT < time.monotonic() )
def delayed(self):
return (self.timestamp + self.delay > time.monotonic() )
class account_c:
def __init__(self, exchange = None, name = 'default', apiKey = None, secret = None, password = None, marginMode = None, settleCoin = None )->None:
self.accountName = name
self.refreshPositionsFailed = 0
self.positionslist = []
self.ordersQueue = []
self.activeOrders = []
self.latchedAlerts = []
self.MARGIN_MODE = 'cross' if ( marginMode != None and marginMode.lower() == 'cross') else 'isolated'
self.SETTLE_COIN = 'USDT' if( settleCoin == None ) else settleCoin
if( exchange == None ):
raise ValueError('Exchange not defined')
if( name.isnumeric() ):
print( " * FATAL ERROR: Account 'id' can not be only numeric" )
raise ValueError('Invalid Account Name')
if( exchange.lower() == 'kucoinfutures' ):
self.exchange = ccxt.kucoinfutures( {
'apiKey': apiKey,
'secret': secret,
'password': password,
'enableRateLimit': False,
"options": {'defaultType': 'swap', 'defaultMarginMode':self.MARGIN_MODE, 'adjustForTimeDifference' : True},
} )
elif( exchange.lower() == 'bitget' ):
self.exchange = ccxt.bitget({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'defaultMarginMode':self.MARGIN_MODE, 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": False
})
elif( exchange.lower() == 'bingx' ):
self.exchange = ccxt.bingx({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'defaultMarginMode':self.MARGIN_MODE, 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": False
})
elif( exchange.lower() == 'coinex' ):
self.exchange = ccxt.coinex({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": False
})
elif( exchange.lower() == 'phemex' ):
self.exchange = ccxt.phemex({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'defaultMarginMode':self.MARGIN_MODE, 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": False
})
###HACK!! phemex does NOT have setMarginMode when the type is SWAP
self.exchange.has['setMarginMode'] = False
elif( exchange.lower() == 'phemexdemo' ):
self.exchange = ccxt.phemex({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'defaultMarginMode':self.MARGIN_MODE, 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": False
})
self.exchange.set_sandbox_mode( True )
###HACK!! phemex does NOT have setMarginMode when the type is SWAP
self.exchange.has['setMarginMode'] = False
elif( exchange.lower() == 'bybit' ):
self.exchange = ccxt.bybit({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'defaultMarginMode':self.MARGIN_MODE, 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": True
})
elif( exchange.lower() == 'bybitdemo' ):
self.exchange = ccxt.bybit({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'defaultMarginMode':self.MARGIN_MODE, 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": True
})
self.exchange.set_sandbox_mode( True )
elif( exchange.lower() == 'binance' ):
self.exchange = ccxt.binance({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": False
})
elif( exchange.lower() == 'binancedemo' ):
self.exchange = ccxt.binance({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": False
})
self.exchange.set_sandbox_mode( True )
elif( exchange.lower() == 'krakenfutures' ):
self.exchange = ccxt.krakenfutures({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'defaultMarginMode':self.MARGIN_MODE, 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": True
})
self.SETTLE_COIN = 'USD'
if( settleCoin != None ) : self.SETTLE_COIN = settleCoin
# 'options': { 'settlementCurrencies': { 'flex': ['USDT', 'BTC', 'USD', 'GBP', 'EUR', 'USDC'],
elif( exchange.lower() == 'krakendemo' ):
self.exchange = ccxt.krakenfutures({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'defaultMarginMode':self.MARGIN_MODE, 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": True
})
self.exchange.set_sandbox_mode( True )
self.SETTLE_COIN = 'USD'
if( settleCoin != None ) : self.SETTLE_COIN = settleCoin
# 'options': { 'settlementCurrencies': { 'flex': ['USDT', 'BTC', 'USD', 'GBP', 'EUR', 'USDC'],
elif( exchange.lower() == 'okx' ):
self.exchange = ccxt.okx ({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": True
})
elif( exchange.lower() == 'okxdemo' ):
self.exchange = ccxt.okx ({
"apiKey": apiKey,
"secret": secret,
'password': password,
"options": {'defaultType': 'swap', 'adjustForTimeDifference' : True},
#"timeout": 60000,
"enableRateLimit": True
})
self.exchange.set_sandbox_mode( True )
else:
raise ValueError('Unsupported exchange')
if( self.exchange == None ):
raise ValueError('Exchange creation failed')
# crate a logger for each account
# make sure the logs directory exists
if( LOGS_DIRECTORY == '' ):
path = f'{self.accountName}.log'
else:
path = f'{LOGS_DIRECTORY}/{self.accountName}.log'
script_dir = os.path.dirname(os.path.realpath(__file__))
if not os.path.exists(os.path.join(script_dir, LOGS_DIRECTORY)):
os.makedirs(os.path.join(script_dir, LOGS_DIRECTORY))
self.logger = logging.getLogger( self.accountName )
fh = logging.FileHandler( path )
self.logger.addHandler( fh )
self.logger.level = logging.INFO
# Some exchanges don't have all fields properly filled, but we can find out
# the values in another field. Instead of adding exceptions at each other function
# let's reconstruct the markets dictionary trying to fix those values
self.markets = {}
markets = self.exchange.load_markets()
marketKeys = markets.keys()
for key in marketKeys:
thisMarket = markets[key]
if( thisMarket.get('settle') != self.SETTLE_COIN ): # double check
continue
if( thisMarket.get('contractSize') == None ):
# in Phemex we can extract the contractSize from the description.
# it's always going to be 1, but let's handle it in case they change it
if( self.exchange.id == 'phemex' ):
description = thisMarket['info'].get('description')
s = description[ description.find('Each contract is worth') + len('Each contract is worth ') : ]
list = s.split( ' ', 1 )
cs = float( list[0] )
if( cs != 1.0 ):
print( "* WARNING: phemex", key, "contractSize reported", cs )
thisMarket['contractSize'] = cs
else:
print( "WARNING: Market", self.exchange.id, "doesn't have contractSize" )
# make sure the market has a precision value
try:
precision = thisMarket['precision'].get('amount')
except Exception as e:
raise ValueError( "Market", self.exchange.id, "doesn't have precision value" )
# some exchanges don't have a minimum purchase amount defined
try:
minAmount = thisMarket['limits']['amount'].get('min')
except Exception as e:
minAmount = None
l = thisMarket.get('limits')
if( l != None ):
a = l.get('amount')
if( a != None ):
minAmount = a.get('min')
if( minAmount == None ): # replace minimum amount with precision value
thisMarket['limits']['amount']['min'] = float(precision)
# HACK: Bingx has wrong leverage limits defined
if( self.exchange.id == 'bingx' ):
thisMarket['limits']['leverage']['max'] = None if self.exchange.has['fetchLeverage'] else max( 100, thisMarket['limits']['leverage']['max'] )
# also generate a local list to keep track of marginMode and Leverage status
thisMarket['local'] = { 'marginMode':MARGIN_MODE_NONE, 'leverage':0, 'positionMode':'' }
if( self.exchange.has.get('setPositionMode') != True ):
thisMarket['local']['positionMode'] = 'oneway'
# Store the market into the local markets dictionary
self.markets[key] = thisMarket
if( verbose ):
pprint( self.markets['BTC/' + self.SETTLE_COIN + ':' + self.SETTLE_COIN] )
self.refreshPositions(True)
## methods ##
def print( self, *args, sep=" ", **kwargs ): # adds account and exchange information to the message
print( timeNow(), '['+ self.accountName +'/'+ self.exchange.id +'] '+ sep.join(map(str,args)), **kwargs )
self.logger.info( '['+ dateString()+']['+timeNow()+'] ' +sep.join(map(str,args)), **kwargs)
def verifyLeverageRange( self, symbol, leverage )->int:
leverage = max( leverage, 1 )
maxLeverage = self.findMaxLeverageForSymbol( symbol )
if( maxLeverage != None and maxLeverage < leverage ):
self.print( " * WARNING: Leverage out of bounds. Readjusting to", str(maxLeverage)+"x" )
leverage = maxLeverage
# coinex has a list of valid leverage values
if( self.exchange.id != 'coinex' ):
return leverage
thisMarket = self.markets.get( symbol )
leverages = thisMarket['info'].get('leverage')
if( leverages == None ):
leverages = thisMarket['info'].get('leverages')
validLeverages = list(map(int, leverages))
safeLeverage = 1
for value in validLeverages:
if( value > leverage ):
break
safeLeverage = value
return safeLeverage
def updateSymbolPositionMode( self, symbol ):
# Make sure the exchange is in oneway mode
if( self.exchange.has.get('setPositionMode') != True and self.markets[ symbol ]['local']['positionMode'] != 'oneway' ):
self.print( " * E: updateSymbolPositionMode: Exchange", self.exchange.id, "doesn't have setPositionMode nor is set to oneway" )
return
if( self.markets[ symbol ]['local']['positionMode'] != 'oneway' and self.exchange.has.get('setPositionMode') == True ):
if( self.getPositionBySymbol(symbol) != None ):
self.print( ' * W: Cannot change position mode while a position is open' )
return
try:
response = self.exchange.set_position_mode( False, symbol )
except ccxt.NoChange as e:
self.markets[ symbol ]['local']['positionMode'] = 'oneway'
except Exception as e:
for a in e.args:
if( '"retCode":140025' in a or '"code":-4059' in a
or 'retCode":110025' in a or '"code":"59000"' in a ):
# this is not an error, but just an acknowledge
# bybit {"retCode":140025,"retMsg":"position mode not modified","result":{},"retExtInfo":{},"time":1690530385019}
# bybit {"retCode":110025,"retMsg":"Position mode is not modified","result":{},"retExtInfo":{},"time":1694988241696}
# binance {"code":-4059,"msg":"No need to change position side."}
# okx {"code":"59000","data":[],"msg":"Setting failed. Cancel any open orders, close positions, and stop trading bots first."}
self.markets[ symbol ]['local']['positionMode'] = 'oneway'
else:
print( " * E: updateSymbolLeverage->set_position_mode:", a, type(e) )
else:
# was everything correct, tho?
code = 0
if( self.exchange.id == 'bybit' ): # they didn't receive enough love as children
code = int(response.get('retCode'))
else:
code = int(response.get('code'))
# 'code': '0' <- coinex
# 'code': '00000' <- bitget
# 'code': '0' <- phemex
# 'retCode': '0' <- bybit
# {'code': '200', 'msg': 'success'} <- binance
if( self.exchange.id == 'binance' and code == 200 or code == -4059 ):
code = 0
if( code != 0 ):
print( " * E: updateSymbolLeverage->set_position_mode:", response )
return
self.markets[ symbol ]['local']['positionMode'] = 'oneway'
def updateSymbolLeverage( self, symbol, leverage ):
# also sets marginMode
if( leverage < 1 ): # leverage 0 indicates we are closing a position
return
# Notice: Kucoin is never going to make any of these.
# Coinex doesn't accept any number as leverage. It must be on the list. Also clamp to max allowed
leverage = self.verifyLeverageRange( symbol, leverage )
##########################################
# Update marginMode if needed
##########################################
if( self.markets[ symbol ]['local']['marginMode'] != self.MARGIN_MODE and self.exchange.has.get('setMarginMode') == True ):
params = {}
# coinex and bybit expect the leverage as part of the marginMode call
if( self.exchange.id == 'coinex' or self.exchange.id == 'bybit' ):
params['leverage'] = leverage
elif( self.exchange.id == 'okx' ):
params['lever'] = leverage
try:
response = self.exchange.set_margin_mode( self.MARGIN_MODE, symbol, params )
except ccxt.NoChange as e:
self.markets[ symbol ]['local']['marginMode'] = self.MARGIN_MODE
except ccxt.MarginModeAlreadySet as e:
self.markets[ symbol ]['local']['marginMode'] = self.MARGIN_MODE
except Exception as e:
for a in e.args:
if( '"retCode":140026' in a or "No need to change margin type" in a
or '"retCode":110026' in a ):
# bybit throws an exception just to inform us the order wasn't neccesary (doh)
# bybit {"retCode":140026,"retMsg":"Isolated not modified","result":{},"retExtInfo":{},"time":1690530385642}
# bybit setMarginMode() marginMode must be either ISOLATED_MARGIN or REGULAR_MARGIN or PORTFOLIO_MARGIN
# bybit {"retCode":110026,"retMsg":"Cross/isolated margin mode is not modified","result":{},"retExtInfo":{},"time":1695526888984}
# binance {'code': -4046, 'msg': 'No need to change margin type.'}
# updateSymbolLeverage->set_margin_mode: {'code': -4046, 'msg': 'No need to change margin type.'}
self.markets[ symbol ]['local']['marginMode'] = self.MARGIN_MODE
if( self.exchange.id == 'bitget' and 'code":"45117' in a):
print( " * W: Bitget: Currently holding positions or orders, the margin mode cannot be adjusted" )
#self.markets[ symbol ]['local']['marginMode'] = 'cross' if self.MARGIN_MODE == 'isolated' else 'isolated'
# * E: updateSymbolLeverage->set_margin_mode: bitget {"code":"45117","msg":"Currently holding positions or orders, the margin mode cannot be adjusted","requestTime":1734896200804,"data":null} <class 'ccxt.base.errors.ExchangeError'>
# * E: UpdateOrdersQueue: Unhandled exception. Cancelling: bitget {"code":"45117","msg":"Currently holding positions or orders, the margin mode cannot be adjusted","requestTime":1734896201207,"data":null} <class 'ccxt.base.errors.ExchangeError'>
else:
print( " * E: updateSymbolLeverage->set_margin_mode:", a, type(e) )
else:
# was everything correct, tho?
code = 0
if( self.exchange.id == 'bybit' ): # they didn't receive enough love as children
code = int(response.get('retCode'))
else:
code = int(response.get('code'))
# 'code': '0' <- coinex
# 'code': '00000' <- bitget
# 'code': '0' <- phemex
# 'retCode': '0' <- bybit
# {'code': '200', 'msg': 'success'} <- binance
if( self.exchange.id == 'binance' and code == 200 or code == -4046 ):
code = 0
if( code != 0 ):
print( " * E: updateSymbolLeverage->set_margin_mode:", response )
else:
self.markets[ symbol ]['local']['marginMode'] = self.MARGIN_MODE
# coinex and bybit don't need to continue since they have already updated the leverage
if( self.exchange.id == 'coinex' or self.exchange.id == 'bybit' ):
self.markets[ symbol ]['local']['leverage'] = leverage
return
##########################################
# Finally update leverage
##########################################
if( self.markets[ symbol ]['local']['leverage'] != leverage and self.exchange.has.get('setLeverage') == True ):
# from phemex API documentation: The sign of leverageEr indicates margin mode,
# i.e. leverage <= 0 means cross-margin-mode, leverage > 0 means isolated-margin-mode.
params = {}
if( self.exchange.id == 'coinex' ): # coinex always updates leverage and marginMode at the same time
params['marginMode'] = self.markets[ symbol ]['local']['marginMode'] # use current marginMode to avoid triggering an error
elif( self.exchange.id == 'okx' ):
params['marginMode'] = self.markets[ symbol ]['local']['marginMode']
params['posSide'] = 'net'
elif( self.exchange.id == 'bingx' ):
if( self.markets[ symbol ]['local']['positionMode'] != 'oneway' ):
response = self.exchange.set_leverage( leverage, symbol, params = {'side':'LONG'} )
response2 = self.exchange.set_leverage( leverage, symbol, params = {'side':'SHORT'} )
if( response.get('code') == '0' and response2.get('code') == '0' ):
self.markets[ symbol ]['local']['leverage'] = leverage
return
else:
params['side'] = 'BOTH'
try:
response = self.exchange.set_leverage( leverage, symbol, params )
except ccxt.NoChange as e:
self.markets[ symbol ]['local']['leverage'] = leverage
except Exception as e:
for a in e.args:
if( '"retCode":140043' in a or '"retCode":110043' in a ):
# bybit throws an exception just to inform us the order wasn't neccesary (doh)
# bybit {"retCode":110043,"retMsg":"Set leverage not modified","result":{},"retExtInfo":{},"time":1694988242174}
# bybit {"retCode":140043,"retMsg":"leverage not modified","result":{},"retExtInfo":{},"time":1690530386264}
pass
elif( 'MAX_LEVERAGE_OUT_OF_BOUNDS' in a ):
self.print( " * E: Maximum leverage exceeded [", leverage, "]" )
return
# {"status":"INTERNAL_SERVER_ERROR","result":"error","errors":[{"code":98,"message":"MAX_LEVERAGE_OUT_OF_BOUNDS"}],"serverTime":"2023-09-24T00:57:08.908Z"}
else:
print( " * E: updateSymbolLeverage->set_leverage:", a, type(e) )
else:
# was everything correct, tho?
code = 0
if( self.exchange.id == 'bybit' ): # they didn't receive enough love as children
code = int(response.get('retCode'))
elif( self.exchange.id == 'krakenfutures' ):
#{'result': 'success', 'serverTime': '2023-09-22T21:25:47.729Z'}
# Error: updateSymbolLeverage->set_leverage: {'result': 'success', 'serverTime': '2023-09-22T21:30:17.767Z'}
if( 'success' not in response ):
code = -1 if response.get('result') != 'success' else 0
elif( self.exchange.id != 'binance' ):
code = int(response.get('code'))
# 'code': '0' <- coinex
# 'code': '00000' <- bitget
# 'code': '0' <- phemex
# 'retCode': '0' <- bybit
# binance doesn't send any code #{'symbol': 'BTCUSDT', 'leverage': '7', 'maxNotionalValue': '40000000'}
if( code != 0 ):
print( " * E: updateSymbolLeverage->set_leverage:", response )
else:
self.markets[ symbol ]['local']['leverage'] = leverage
def fetchBalance(self):
params = { "settle":self.SETTLE_COIN }
if( self.exchange.id == 'krakenfutures' ):
params['type'] = 'flex'
response = self.exchange.fetch_balance( params )
if( self.exchange.id == 'krakenfutures' ):
data = response['info']['accounts']['flex']
return { 'free':float(data.get('availableMargin')), 'used':float(data.get('initialMarginWithOrders')), 'total': float(data.get('balanceValue')) }
if( response.get(self.SETTLE_COIN) == None ):
balance = { 'free':0.0, 'used':0.0, 'total':0.0 }
return balance
return response.get(self.SETTLE_COIN)
def fetchAvailableBalance(self)->float:
return float( self.fetchBalance().get( 'free' ) )
def fetchBuyPrice(self, symbol)->float:
orderbook = self.exchange.fetch_order_book(symbol)
ask = orderbook['asks'][0][0] if len (orderbook['asks']) > 0 else None
if( ask == None ):
raise ValueError( "Couldn't fetch ask price" )
return ask
def fetchSellPrice(self, symbol)->float:
orderbook = self.exchange.fetch_order_book(symbol)
bid = orderbook['bids'][0][0] if len (orderbook['bids']) > 0 else None
if( bid == None ):
raise ValueError( "Couldn't fetch bid price" )
return bid
def fetchAveragePrice(self, symbol)->float:
orderbook = self.exchange.fetch_order_book(symbol)
bid = orderbook['bids'][0][0] if len (orderbook['bids']) > 0 else None
ask = orderbook['asks'][0][0] if len (orderbook['asks']) > 0 else None
if( bid == None and ask == None ):
raise ValueError( "Couldn't fetch orderbook" )
if( bid == None ): bid = ask
if( ask == None ): ask = bid
return ( bid + ask ) * 0.5
def getPositionBySymbol(self, symbol)->position_c:
for pos in self.positionslist:
if( pos.symbol == symbol ):
return pos
return None
def findSymbolFromPairName(self, pairString):
# this is only for the pair name we receive in the alert.
# Once it's converted to ccxt symbol format there is no
# need to use this method again.
paircmd = pairString.upper()
if( paircmd.endswith('.P' ) ):
paircmd = paircmd[:-2]
# first let's check if the pair string contains
# a backslash. If it does it's probably already a symbol
if '/' not in paircmd and paircmd.endswith(self.SETTLE_COIN):
paircmd = paircmd[:-len(self.SETTLE_COIN)]
paircmd += '/' + self.SETTLE_COIN + ':' + self.SETTLE_COIN
# but it also may not include the ':USDT' ending
if '/' in paircmd and not paircmd.endswith(':'+ self.SETTLE_COIN ):
paircmd += ':' + self.SETTLE_COIN
# try the more direct approach
m = self.markets.get(paircmd)
if( m != None ):
return m.get('symbol')
# so now let's find it in the list using the id
for m in self.markets:
id = self.markets[m]['id']
symbol = self.markets[m]['symbol']
if( symbol == paircmd or id == paircmd ):
return symbol
return None
def findContractSizeForSymbol(self, symbol)->float:
return self.markets[symbol].get('contractSize')
def findPrecisionForSymbol(self, symbol)->float:
if( self.exchange.id == 'binance' or self.exchange.id == 'bingx' ):
precision = 1.0 / (10.0 ** self.markets[symbol]['precision'].get('amount'))
else :
precision = self.markets[symbol]['precision'].get('amount')
return precision
def findMinimumAmountForSymbol(self, symbol)->float:
return self.markets[symbol]['limits']['amount'].get('min')
def findMaxLeverageForSymbol(self, symbol)->float:
maxLeverage = self.markets[symbol]['limits']['leverage'].get('max')
if( maxLeverage == None ):
maxLeverage = 100
if( self.exchange.has['fetchLeverage'] ):
info = self.exchange.fetch_leverage( symbol ).get('info')
if( info != None and info.get('maxLongLeverage') != None and info.get('maxShortLeverage') != None ):
maxLeverage = min(int(info['maxLongLeverage']), int(info['maxShortLeverage']))
self.markets[symbol]['limits']['leverage']['max'] = maxLeverage
return maxLeverage
def contractsFromUSDT(self, symbol, amount, price, leverage = 1.0 )->float :
contractSize = self.findContractSizeForSymbol( symbol )
coin = Decimal( (amount * leverage) / (contractSize * price) )
precision = str(self.findPrecisionForSymbol( symbol ))
return roundDownTick( coin, precision ) if ( coin > 0 ) else roundUpTick( coin, precision )
def refreshPositions(self, v = verbose):
### https://docs.ccxt.com/#/?id=position-structure ###
failed = False
try:
symbols = None
if( self.exchange.id == 'bitget' ):
symbols = list(self.markets.keys())
positions = self.exchange.fetch_positions( symbols, params = {'settle':self.SETTLE_COIN} ) # the 'settle' param is only required by phemex
except Exception as e:
a = e.args[0]
if 'OK' in a: # Coinex raises an exception to give an OK message when there are no positions... don't look at me, look at them
positions = []
elif( isinstance(e, ccxt.OnMaintenance) or isinstance(e, ccxt.NetworkError)
or isinstance(e, ccxt.RateLimitExceeded) or isinstance(e, ccxt.RequestTimeout)
or isinstance(e, ccxt.ExchangeNotAvailable) or 'not available' in a ):
failed = True
if( 'Remote end closed connection' in a
or '500 Internal Server Error' in a
or '502 Bad Gateway' in a
or 'Internal Server Error' in a
or 'Server busy' in a or 'System busy' in a
or '"retCode":10002' in a ):
print( timeNow(), self.exchange.id, '* E: Refreshpositions:(old)', a, type(e) )
elif( 'Remote end closed connection' in a
or '500 Internal Server Error' in a
or '502 Bad Gateway' in a
or 'Internal Server Error' in a
or 'Server busy' in a or 'System busy' in a
or 'not available' in a # ccxt.base.errors.ExchangeError
or 'failure to get a peer' in a # ccxt.base.errors.ExchangeError (okx)
or '"code":39999' in a
or '"retCode":10002' in a ):
failed = True
# this print is temporary to try to replace the string with the error type if possible
print( timeNow(), self.exchange.id, '* E: Refreshpositions:', a, type(e) )
else:
print( timeNow(), self.exchange.id, '* E: Refreshpositions:', a, type(e) )
failed = True
if( failed ):
self.refreshPositionsFailed += 1
if( self.refreshPositionsFailed == 10 ):
print( timeNow(), self.exchange.id, '* W: Refreshpositions has failed 10 times in a row' )
return
if (self.refreshPositionsFailed >= 10 ):
print( timeNow(), self.exchange.id, '* W: Refreshpositions has returned to activity' )
self.refreshPositionsFailed = 0
# Phemex returns positions that were already closed
# reconstruct the list of positions only with active positions
cleanPositionsList = []
for thisPosition in positions:
if( thisPosition.get('contracts') == 0.0 ):
continue
cleanPositionsList.append( thisPosition )
positions = cleanPositionsList
numPositions = len(positions)
if v:
tab = ' '
if( numPositions > 0 ) : print('------------------------------')
# fetch balance
balanceString = ''
if SHOW_BALANCE:
balance = self.fetchBalance()
balanceString = " Balance: {:.2f}[$]".format(balance['total'])
balanceString += " - Available {:.2f}[$]".format(balance['free'])
print( tab + str(numPositions), "positions found.", balanceString )
self.positionslist.clear()
for thisPosition in positions:
symbol = thisPosition.get('symbol')
# HACK!! bybit response doesn't contain a 'hedge' key, but it contains the information in the 'info' block
if( self.exchange.id == 'bybit' ):
thisPosition['hedged'] = True if( thisPosition['info'].get( 'positionIdx' ) != '0' ) else False
if( self.exchange.id == 'bingx' ): # 'onlyOnePosition': True,
thisPosition['hedged'] = not thisPosition['info'].get( 'onlyOnePosition' )
# if the position contains positionMode information update our local data
if( thisPosition.get('hedged') != None ) : # None means the exchange only supports oneWay
self.markets[ symbol ]['local'][ 'positionMode' ] = 'hedged' if( thisPosition.get('hedged') == True ) else 'oneway'
# if the position contains the marginMode information also update the local data
#some exchanges have the key set to None. Fix it when possible
if( thisPosition.get('marginMode') == None ) :
if( self.exchange.id == 'bybit' ): # tradeMode - Classic & UTA (inverse): 0: cross-margin, 1: isolated margin
self.markets[ symbol ]['local'][ 'marginMode' ] = 'isolated' if thisPosition['info']['tradeMode'] == '1' else 'cross'
elif( self.exchange.has.get('setMarginMode') != True ):
thisPosition['marginMode'] = MARGIN_MODE_NONE
else:
print( ' * W: refreshPositions: Could not get marginMode for', symbol )
thisPosition['marginMode'] = MARGIN_MODE_NONE
else:
self.markets[ symbol ]['local'][ 'marginMode' ] = thisPosition.get('marginMode')
# update the local leverage as well as we can
leverage = -1
if( thisPosition.get('leverage') != None ):
leverage = int(thisPosition.get('leverage'))
if( leverage != thisPosition.get('leverage') ): # kucoin sends weird fractional leverage. Ignore it
leverage = -1
# still didn't find the leverage, but the exchange has the fetchLeverage method so we can try that.
if( leverage == -1 and self.exchange.has.get('fetchLeverage') == True ):
try:
response = self.exchange.fetch_leverage( symbol )
except Exception as e:
pass
else:
if( self.exchange.id == 'bitget' ):
if( response['data']['marginMode'] == 'crossed' ):
leverage = int(response['data'].get('crossMarginLeverage'))
else:
# they should always be the same
longLeverage = int(response['data'].get('fixedLongLeverage'))
shortLeverage = int(response['data'].get('fixedShortLeverage'))
if( longLeverage == shortLeverage ):
leverage = longLeverage
elif( self.exchange.id == 'bingx' ):
# they should always be the same
longLeverage = response['data'].get('longLeverage')
shortLeverage = response['data'].get('shortLeverage')
if( longLeverage == shortLeverage ):
leverage = longLeverage
if( leverage != -1 ):
self.markets[ symbol ]['local'][ 'leverage' ] = leverage
elif( self.exchange.id != "kucoinfutures" ): # we know kucoin is helpless
print( " * W: refreshPositions: Couldn't find leverage for", self.exchange.id )
self.positionslist.append(position_c( symbol, thisPosition, self.markets[ symbol ] ))
if v:
for pos in self.positionslist:
print( tab + pos.generatePrintString() )
print('------------------------------')
def activeOrderForSymbol(self, symbol ):
for o in self.activeOrders:
if( o.symbol == symbol ):
return True
return False
def fetchClosedOrderById(self, symbol, id ):
try:
response = self.exchange.fetch_closed_orders( symbol, params = {'settleCoin':self.SETTLE_COIN} )
except Exception as e:
#Exception: ccxt.base.errors.ExchangeError: phemex {"code":39999,"msg":"Please try again.","data":null}
return None
for o in response:
if o.get('id') == id :
return o
if verbose : print( "r...", end = '' )
return None
def fetchOpenOrderById(self, symbol, id ):
try:
response = self.exchange.fetch_open_orders( symbol, params = {'settleCoin':self.SETTLE_COIN} )
except Exception as e:
#Exception: ccxt.base.errors.ExchangeError: phemex {"code":39999,"msg":"Please try again.","data":null}
return None
for o in response:
if o.get('id') == id :
return o
if verbose : print( "r...", end = '' )
return None
def removeFirstCompletedOrder(self):
# go through the queue and remove the first completed order
for order in self.activeOrders:
if( order.timedOut() ):
self.print( " * E: Active Order Timed out", order.symbol, order.side, order.quantity, str(order.leverage)+'x' )