-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmy_class.py
More file actions
2241 lines (1840 loc) · 107 KB
/
my_class.py
File metadata and controls
2241 lines (1840 loc) · 107 KB
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
# Mathematical
from decimal import getcontext, ROUND_DOWN, Decimal
import math
# Logs
import traceback
from pprint import pprint
# Python Binance Lib
from binance.client import Client, BinanceAPIException
# My
import utility
class BinanceAPI:
def __init__(self, p_api_pub_key = None, p_api_secret_key = None, p_symbol_first = None, p_symbol_second = None, p_wallet = None):
# Symbol
if p_wallet:
self.wallet = p_wallet.lower()
else:
self.wallet = 'spot'
if p_symbol_first:
self.symbol_first = p_symbol_first.upper()
if p_symbol_second:
self.symbol_second = p_symbol_second.upper()
if p_symbol_first and p_symbol_second:
self.symbol = f"{p_symbol_first}{p_symbol_second}".upper()
# Working
self.client_builded = None
self.client = None
# Build Client
self.request_timeout = 20
self.client_builded = self.build_client(p_api_pub_key, p_api_secret_key)
if self.check_client_build_ok():
self.client = self.client_builded[1]
"""""""""""""""""""""
UTILITY
"""""""""""""""""""""
# Build Client
def build_client(self, p_api_pub_key = None, p_api_secret_key = None):
# Prepare
_inputs = f"{self.request_timeout}|{'API_PUB_KEY_SETTED' if p_api_pub_key else None}|{'API_SECRET_KEY_SETTED' if p_api_secret_key else None} "
_response_tuple = None
_temp = None
# Instance Binance Client
try:
if p_api_pub_key and p_api_secret_key:
_temp = Client( api_key = p_api_pub_key, api_secret = p_api_secret_key, requests_params = { "timeout" : self.request_timeout } )
else:
_temp = Client( requests_params = { "timeout" : self.request_timeout } )
_response_tuple = ('OK', _temp)
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
except:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','build_client',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# Check if the client build was successful
def check_client_build_ok(self):
if self.client_builded[0] == 'OK':
return True
else:
return False
# Return error when the client build went wrong
def get_client_msg_nok(self):
return self.client_builded[1]
# Truncate Asset Qta (p_qta_start) to the largest multiple of p_step_size for LOT_SIZE
def truncate_by_step_size(self, p_qta_start, p_step_size):
# Prepare
_inputs = f"{p_qta_start}|{p_step_size}"
_response_tuple = None
_digits_int = None
_qta_start_decimal = None
_qta_end = None
# By default rounding setting in python is ROUND_HALF_EVEN
getcontext().rounding = ROUND_DOWN
# Convert p_qta_start into Decimal
try:
_qta_start_decimal = Decimal(p_qta_start)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','truncate_by_step_size',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# Calculate Digits 4 Round
try:
_digits_int = int( round( -math.log(Decimal(p_step_size), 10) , 0 ) )
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','truncate_by_step_size',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# Calculate Tot End
try:
_qta_end = Decimal(round( _qta_start_decimal , _digits_int ))
_response_tuple = ('OK',_qta_end)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','truncate_by_step_size',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
"""""""""""""""""""""
GENERAL ENDPOINTS
"""""""""""""""""""""
# Check if Symbol Exists
def general_check_if_symbol_exists(self, p_symbol_input = None):
# Prepare
_inputs = None
_response_tuple = None
_symbol_info = None
_symbol_work = None
# Choose Symbol
if not p_symbol_input:
_symbol_work = self.symbol
else:
_symbol_work = p_symbol_input
# Set Inputs
_inputs = f"{_symbol_work}"
# Work
try:
# Check
_symbol_info = self.client.get_symbol_info(symbol=_symbol_work)
if _symbol_info:
_response_tuple = ('OK', f"Symbol {_symbol_work} exist")
else:
_response_tuple = ('NOK', f"Symbol {_symbol_work} does not exist")
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','general_check_if_symbol_exists',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# Get Binance Rate Limits
def general_get_rate_limits(self):
# Prepare
_inputs = None
_response_tuple = None
_rate_limits = None
_exchange_info = None
_output_verbose = {}
try:
# Get Exchange Info
_exchange_info = self.client.get_exchange_info()
if _exchange_info:
_rate_limits = _exchange_info.get('rateLimits')
if len(_rate_limits) > 0:
for _rate_limit in _rate_limits:
if _rate_limit.get('rateLimitType') == 'REQUEST_WEIGHT':
_key = f"Max Requests for {_rate_limit.get('intervalNum')} {_rate_limit.get('interval').lower().capitalize()}"
_output_verbose[_key] = _rate_limit.get('limit')
elif _rate_limit.get('rateLimitType') == 'ORDERS' and _rate_limit.get('interval') == 'SECOND':
_key = f"Max Orders for {_rate_limit.get('intervalNum')} {_rate_limit.get('interval').lower().capitalize()}"
_output_verbose[_key] = _rate_limit.get('limit')
elif _rate_limit.get('rateLimitType') == 'ORDERS' and _rate_limit.get('interval')== 'DAY':
_key = f"Max Orders for {_rate_limit.get('intervalNum')} {_rate_limit.get('interval').lower().capitalize()}"
_output_verbose[_key] = _rate_limit.get('limit')
_response_tuple = ('OK', _output_verbose)
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_rate_limits',_inputs,'_rate_limits is None')}")
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_rate_limits',_inputs,'_exchange_info is None')}")
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','general_get_rate_limits',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# Get system status detail
def general_get_system_status(self):
# Prepare
_inputs = None
_response_tuple = None
_status = None
_output = None
try:
_output = self.client.get_system_status()
if _output:
if not _output.get('status'):
_status = 'System Normal'
else:
_status = 'System Maintenance'
_response_tuple = ('OK', _status)
else:
_response_tuple = ('OK', 'System Maintenance')
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','general_get_system_status',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# PRICE_FILTER
# PERCENT_PRICE
# LOT_SIZE --> It is used for both buy and sell
# MIN_NOTIONAL --> It is used for both buy and sell and it is applied on the symbol_second in the following way: quantity symbol_first * avg price symbol > minNotional of symbol
# ICEBERG_PARTS
# MARKET_LOT_SIZE
# MAX_NUM_ALGO_ORDERS
# MAX_NUM_ORDERS
def general_get_symbol_info_filter(self, p_what_filter, p_symbol_input = None):
""" PREPARE """
# Defaults
_inputs = None
_response_tuple = None
_symbol_info = None
_symbol_info_dict = {}
_symbol_work = None
_filters = None
_filter = None
_response_tuple_local = None
_output_local = {}
# Choose Symbol
if not p_symbol_input:
_symbol_work = self.symbol
else:
_symbol_work = p_symbol_input
# Set Inputs
_inputs = f"{p_what_filter}|{_symbol_work}|{self.wallet}"
""" FUNCTIONS FOR EVERY FILTER """
# Get PRICE_FILTER info
def price_filter(_symbol, _filter):
try:
if self.wallet == 'spot' or self.wallet == 'margin' or self.wallet == 'futures':
_output_local["PRICE_FILTER_symbol"] = _symbol
_output_local["PRICE_FILTER_minPrice"] = Decimal(_filter.get('minPrice')) if _filter.get('minPrice') else _filter.get('minPrice')
_output_local["PRICE_FILTER_maxPrice"] = Decimal(_filter.get('maxPrice')) if _filter.get('maxPrice') else _filter.get('maxPrice')
_output_local["PRICE_FILTER_tickSize"] = Decimal(_filter.get('tickSize')) if _filter.get('tickSize') else _filter.get('tickSize')
_response_tuple_local = ('OK', _output_local)
else:
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.price_filter',_inputs,self.wallet+': wallet is unknown')}")
except Exception:
_response_tuple_local = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_info_filter.price_filter',_inputs,traceback.format_exc(2))}")
return(_response_tuple_local)
# Get PERCENT_PRICE info
def percent_price(_symbol, _filter):
try:
if self.wallet == 'spot' or self.wallet == 'margin' or self.wallet == 'futures':
_output_local["PERCENT_PRICE_symbol"] = _symbol
if self.wallet == 'spot' or self.wallet == 'margin':
_output_local["PERCENT_PRICE_avgPriceMins"] = int(_filter.get('avgPriceMins')) if _filter.get('avgPriceMins') else _filter.get('avgPriceMins')
else:
_output_local["PERCENT_PRICE_multiplierDecimal"] = int(_filter.get('multiplierDecimal')) if _filter.get('multiplierDecimal') else _filter.get('multiplierDecimal')
_output_local["PERCENT_PRICE_multiplierUp"] = Decimal(_filter.get('multiplierUp')) if _filter.get('multiplierUp') else _filter.get('multiplierUp')
_output_local["PERCENT_PRICE_multiplierDown"] = Decimal(_filter.get('multiplierDown')) if _filter.get('multiplierDown') else _filter.get('multiplierDown')
_response_tuple_local = ('OK', _output_local)
else:
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.percent_price',_inputs,self.wallet+': wallet is unknown')}")
except Exception:
_response_tuple_local = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_info_filter.percent_price',_inputs,traceback.format_exc(2))}")
return(_response_tuple_local)
# Get LOT_SIZE info
def lot_size(_symbol, _filter):
try:
if self.wallet == 'spot' or self.wallet == 'margin' or self.wallet == 'futures':
_output_local["LOT_SIZE_symbol"] = _symbol
_output_local["LOT_SIZE_maxQty"] = Decimal(_filter.get('maxQty')) if _filter.get('maxQty') else _filter.get('maxQty')
_output_local["LOT_SIZE_minQty"] = Decimal(_filter.get('minQty')) if _filter.get('minQty') else _filter.get('minQty') # quantity to buy or sell > symbol minQty
_output_local["LOT_SIZE_stepSize"] = Decimal(_filter.get('stepSize')) if _filter.get('stepSize') else _filter.get('stepSize') # the quantity to buy or sell must be an exact multiple of symbol stepSize
_response_tuple_local = ('OK', _output_local)
else:
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.lot_size',_inputs,self.wallet+': wallet is unknown')}")
except Exception:
_response_tuple_local = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_info_filter.lot_size',_inputs,traceback.format_exc(2))}")
return(_response_tuple_local)
# Get MIN_NOTIONAL info
def min_notional(_symbol, _filter):
try:
if self.wallet == 'spot' or self.wallet == 'margin':
_output_local["MIN_NOTIONAL_symbol"] = _symbol
_output_local["MIN_NOTIONAL_minNotional"] = Decimal(_filter.get('minNotional')) if _filter.get('minNotional') else _filter.get('minNotional')
_output_local["MIN_NOTIONAL_applyToMarket"] = _filter.get('applyToMarket')
_output_local["MIN_NOTIONAL_avgPriceMins"] = int(_filter.get('avgPriceMins')) if _filter.get('avgPriceMins') else _filter.get('avgPriceMins')
_response_tuple_local = ('OK', _output_local)
elif self.wallet == 'futures':
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.min_notional',_inputs,self.wallet+': attention! for this wallet min_notional does not exist ')}")
else:
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.min_notional',_inputs,self.wallet+': wallet is unknown')}")
except Exception:
_response_tuple_local = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_info_filter.min_notional',_inputs,traceback.format_exc(2))}")
return(_response_tuple_local)
# Get ICEBERG_PARTS info
def iceberg_parts(_symbol, _filter):
try:
if self.wallet == 'spot' or self.wallet == 'margin':
_output_local["ICEBERG_PARTS_symbol"] = _symbol
_output_local["ICEBERG_PARTS_limit"] = int(_filter.get('limit')) if _filter.get('limit') else _filter.get('limit')
_response_tuple_local = ('OK', _output_local)
elif self.wallet == 'futures':
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.iceberg_parts',_inputs,self.wallet+': attention! for this wallet iceberg_parts does not exist ')}")
else:
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.iceberg_parts',_inputs,self.wallet+': wallet is unknown')}")
except Exception:
_response_tuple_local = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_info_filter.iceberg_parts',_inputs,traceback.format_exc(2))}")
return(_response_tuple_local)
# Get MARKET_LOT_SIZE info
def market_lot_size(_symbol, _filter):
try:
if self.wallet == 'spot' or self.wallet == 'margin' or self.wallet == 'futures':
_output_local["MARKET_LOT_SIZE_symbol"] = _symbol
_output_local["MARKET_LOT_SIZE_minQty"] = Decimal(_filter.get('minQty')) if _filter.get('minQty') else _filter.get('minQty')
_output_local["MARKET_LOT_SIZE_maxQty"] = Decimal(_filter.get('maxQty')) if _filter.get('maxQty') else _filter.get('maxQty')
_output_local["MARKET_LOT_SIZE_stepSize"] = Decimal(_filter.get('stepSize')) if _filter.get('stepSize') else _filter.get('stepSize')
_response_tuple_local = ('OK', _output_local)
else:
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.market_lot_size',_inputs,self.wallet+': wallet is unknown')}")
except Exception:
_response_tuple_local = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_info_filter.market_lot_size',_inputs,traceback.format_exc(2))}")
return(_response_tuple_local)
# Get MAX_NUM_ALGO_ORDERS info
def max_num_algo_orders(_symbol, _filter):
try:
if self.wallet == 'spot' or self.wallet == 'margin' or self.wallet == 'futures':
_output_local["MAX_NUM_ALGO_ORDERS_symbol"] = _symbol
if self.wallet == 'spot' or self.wallet == 'margin':
_output_local["MAX_NUM_ALGO_ORDERS_maxNumAlgoOrders"] = int(_filter.get('maxNumAlgoOrders')) if _filter.get('maxNumAlgoOrders') else _filter.get('maxNumAlgoOrders')
else:
_output_local["MAX_NUM_ALGO_ORDERS_limit"] = int(_filter.get('limit')) if _filter.get('limit') else _filter.get('limit')
_response_tuple_local = ('OK', _output_local)
else:
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.max_num_algo_orders',_inputs,self.wallet+': wallet is unknown')}")
except Exception:
_response_tuple_local = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_info_filter.max_num_algo_orders',_inputs,traceback.format_exc(2))}")
return(_response_tuple_local)
# Get MAX_NUM_ORDERS info
def max_num_orders(_symbol, _filter):
try:
if self.wallet == 'spot' or self.wallet == 'margin' or self.wallet == 'futures':
_output_local["MAX_NUM_ORDERS_symbol"] = _symbol
if self.wallet == 'spot' or self.wallet == 'margin':
_output_local["MAX_NUM_ORDERS_maxNumOrders"] = int(_filter.get('maxNumOrders')) if _filter.get('maxNumOrders') else _filter.get('maxNumOrders')
else:
_output_local["MAX_NUM_ORDERS_limit"] = int(_filter.get('limit')) if _filter.get('limit') else _filter.get('limit')
_response_tuple_local = ('OK', _output_local)
else:
_response_tuple_local = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter.max_num_orders',_inputs,self.wallet+': wallet is unknown')}")
except Exception:
_response_tuple_local = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_info_filter.max_num_orders',_inputs,traceback.format_exc(2))}")
return(_response_tuple_local)
""" GET SYMBOL INFO """
try:
if self.wallet == 'spot' or self.wallet == 'margin':
_symbol_info = self.client.get_symbol_info(symbol=_symbol_work)
elif self.wallet == 'futures':
_symbol_info_dict = self.client.futures_exchange_info()
if _symbol_info_dict['symbols']:
for f in _symbol_info_dict['symbols']:
if f.get('symbol') == _symbol_work:
_symbol_info = f
break
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter',_inputs,_symbol_info_dict['symbols']+': _symbol_info_dict[symbols] is None')}")
return(_response_tuple)
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter',_inputs,self.wallet+': wallet is unknown')}")
return(_response_tuple)
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
return(_response_tuple)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_info_filter',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
""" WORK ON SYMBOL INFO """
if _symbol_info:
_filters = _symbol_info.get('filters')
if len(_filters) > 0:
for _filter in _filters:
if _filter.get('filterType') == p_what_filter:
if p_what_filter == 'PRICE_FILTER':
_response_tuple = price_filter(_symbol_work, _filter)
break
elif p_what_filter == 'PERCENT_PRICE':
_response_tuple = percent_price(_symbol_work, _filter)
break
elif p_what_filter == 'LOT_SIZE':
_response_tuple = lot_size(_symbol_work, _filter)
break
elif p_what_filter == 'MIN_NOTIONAL':
_response_tuple = min_notional(_symbol_work, _filter)
break
elif p_what_filter == 'ICEBERG_PARTS':
_response_tuple = iceberg_parts(_symbol_work, _filter)
break
elif p_what_filter == 'MARKET_LOT_SIZE':
_response_tuple = market_lot_size(_symbol_work, _filter)
break
elif p_what_filter == 'MAX_NUM_ALGO_ORDERS':
_response_tuple = max_num_algo_orders(_symbol_work, _filter)
break
elif p_what_filter == 'MAX_NUM_ORDERS':
_response_tuple = max_num_orders(_symbol_work, _filter)
break
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter',_inputs,p_what_filter+': what_filter is unknown')}")
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter',_inputs,p_what_filter+': what_filter is unknown')}")
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter',_inputs,'_filters is None')}")
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_info_filter',_inputs,'_symbol_info is None')}")
return(_response_tuple)
# Get Symbol Fee Cost
# https://binance.zendesk.com/hc/en-us/articles/360007720071-Maker-vs-Taker
def general_get_symbol_fee_cost(self, p_what_fee='taker', p_symbol_input = None):
# Prepare
_inputs = None
_response_tuple = None
_fee_decimal = None
_trade_fee_response = None
_symbol_exists = None
_trade_fee = {}
_symbol_work = None
# Choose Symbol
if not p_symbol_input:
_symbol_work = self.symbol
else:
_symbol_work = p_symbol_input
# Set Inputs
_inputs = f"{_symbol_work}|{p_what_fee}"
# Check if Symbol Exists
_symbol_exists = self.general_check_if_symbol_exists(_symbol_work)
if _symbol_exists[0] == 'NOK':
_response_tuple = (_symbol_exists[0], _symbol_exists[1])
return(_response_tuple)
try:
# Get Trade Fee Response
_trade_fee_response = self.client.get_trade_fee(symbol=_symbol_work)
# Work on Trade Fee Response
if _trade_fee_response:
if (_trade_fee_response.get('success')):
_trade_fee = _trade_fee_response.get('tradeFee')
if len(_trade_fee) > 0: # Checking if dictionary _trade_fee is empty
for t in _trade_fee:
if t.get('symbol') == _symbol_work:
try:
_fee_decimal = Decimal(t.get(p_what_fee))
_response_tuple = ('OK', _fee_decimal)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_fee_cost',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_fee_cost',_inputs,'_trade_fee is Empty')}")
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_fee_cost',_inputs,'get_trade_fee() insuccess')}")
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_fee_cost',_inputs,'_trade_fee_response is None')}")
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_fee_cost',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# Get Average price in the last 5 minutes
def general_get_symbol_avg_price(self, p_symbol_input = None):
# Prepare
_inputs = None
_response_tuple = None
_price_decimal = None
_avg_price_response = None
_symbol_exists = None
_symbol_work = None
# Choose Symbol
if not p_symbol_input:
_symbol_work = self.symbol
else:
_symbol_work = p_symbol_input
# Set Inputs
_inputs = f"{_symbol_work}"
# Check if Symbol Exists
_symbol_exists = self.general_check_if_symbol_exists(_symbol_work)
if _symbol_exists[0] == 'NOK':
_response_tuple = (_symbol_exists[0], _symbol_exists[1])
return(_response_tuple)
# Get Avg Price
try:
_avg_price_response = self.client.get_avg_price(symbol=_symbol_work)
if _avg_price_response:
_price_decimal = Decimal(_avg_price_response.get('price'))
_response_tuple = ('OK', _price_decimal)
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_avg_price',_inputs,'_avg_price_response is None')}")
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_avg_price',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# Get Mark Price - only Futures
def general_get_symbol_mark_price(self, p_symbol_input = None):
# Prepare
_inputs = None
_response_tuple = None
_mark_price_decimal = None
_response = None
_symbol_exists = None
_symbol_work = None
# Choose Symbol
if not p_symbol_input:
_symbol_work = self.symbol
else:
_symbol_work = p_symbol_input
# Set Inputs
_inputs = f"{_symbol_work}"
# Check if Symbol Exists
_symbol_exists = self.general_check_if_symbol_exists(_symbol_work)
if _symbol_exists[0] == 'NOK':
_response_tuple = (_symbol_exists[0], _symbol_exists[1])
return(_response_tuple)
# Get Avg Price
try:
_response = self.client.futures_mark_price(symbol=_symbol_work)
if _response:
_mark_price_decimal = Decimal(_response.get('markPrice'))
_response_tuple = ('OK', _mark_price_decimal)
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','general_get_symbol_mark_price',_inputs,'_response is None')}")
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','general_get_symbol_mark_price',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
"""""""""""""""""""""""""""""""""""""""""""""
ACCOUNT ENDPOINTS (SPOT + MARGIN + FUTURES)
"""""""""""""""""""""""""""""""""""""""""""""
""" GENERIC """
# Get Account Balance Total (free & locked) --> spot + margin
def account_get_balance_total(self):
# Prepare
_inputs = f"{self.wallet}"
_response_tuple = None
_my_balance = []
_my_asset = {}
_account_info = None
_what_find = None
_what_finds = None
_symbol_temp_btc = None
_symbol_temp_usdt = None
_avg_price_temp_btc = 0
_avg_price_temp_usdt = 0
_tot_btc_free = 0
_tot_btc_locked = 0
_tot_usd_free = 0
_tot_usd_locked = 0
_tot_btc = 0
_tot_usd = 0
try:
# Get Account Info
if self.wallet == 'spot':
_account_info = self.client.get_account()
_what_finds = "balances"
elif self.wallet == 'margin':
_account_info = self.client.get_margin_account()
_what_finds = "userAssets"
elif self.wallet == 'futures':
_what_finds = 'no_what_finds'
_account_info = self.client.futures_account_balance()
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','account_get_balance_total',_inputs,traceback.format_exc(2))}")
# Get Values from Account Info
if _what_finds in _account_info:
# For every Balances
for _what_find in _account_info[_what_finds]:
if ( Decimal(_what_find.get('free')) + Decimal(_what_find.get('locked')) ) > 0: # Only Asset with something
"""""""""""""""""""""""""""""""""
Build Wallet with List Assets Dict
"""""""""""""""""""""""""""""""""
# Build Asset Dict
_my_asset = { 'asset' : _what_find.get('asset'),
'free' : Decimal(_what_find.get('free')),
'locked' : Decimal(_what_find.get('locked')) }
# Build List Assets Dict
_my_balance.append(_my_asset)
"""""""""""""""""""""""""""""""""
Build Estimated TOT Value BTC & USD
"""""""""""""""""""""""""""""""""
# Asset BTC
if _my_asset.get('asset') == 'BTC':
# Tot Btc
_tot_btc_free = _tot_btc_free + _my_asset.get('free')
_tot_btc_locked = _tot_btc_locked + _my_asset.get('locked')
# Tot Usd
_avg_price_temp = self.general_get_symbol_avg_price('BTCUSDT')
if _avg_price_temp[0] == 'OK':
_tot_usd_free = _tot_usd_free + (_avg_price_temp[1] * _my_asset.get('free'))
_tot_usd_locked = _tot_usd_locked + (_avg_price_temp[1] * _my_asset.get('locked'))
_response_tuple = ('OK', True)
else:
_response_tuple = ('NOK', _avg_price_temp[1])
# Asset USDT
elif _my_asset.get('asset') == 'USDT':
# Tot Btc
_avg_price_temp = self.general_get_symbol_avg_price('BTCUSDT')
if _avg_price_temp[0] == 'OK':
_tot_btc_free = _tot_btc_free + (_my_asset.get('free') / _avg_price_temp[1])
_tot_btc_locked = _tot_btc_locked + (_my_asset.get('locked') / _avg_price_temp[1])
_response_tuple = ('OK', True)
else:
_response_tuple = ('NOK', _avg_price_temp[1])
# Tot Usd
_tot_usd_free = _tot_usd_free + _my_asset.get('free')
_tot_usd_locked = _tot_usd_locked + _my_asset.get('locked')
# Asset BUSD
elif _my_asset.get('asset') == 'BUSD':
# Tot Btc
_avg_price_temp = self.general_get_symbol_avg_price('BTCBUSD')
if _avg_price_temp[0] == 'OK':
_tot_btc_free = _tot_btc_free + (_my_asset.get('free') / _avg_price_temp[1])
_tot_btc_locked = _tot_btc_locked + (_my_asset.get('locked') / _avg_price_temp[1])
_response_tuple = ('OK', True)
else:
_response_tuple = ('NOK', _avg_price_temp[1])
# Tot Usd
_tot_usd_free = _tot_usd_free + _my_asset.get('free')
_tot_usd_locked = _tot_usd_locked + _my_asset.get('locked')
# Asset ALTCOIN
else:
# Prepare 4 Tot Btc & Tot Usd
_symbol_temp_btc = f"{_my_asset.get('asset')}BTC"
_symbol_temp_usdt = f"{_my_asset.get('asset')}USDT"
# Tot Btc
_avg_price_temp_btc = self.general_get_symbol_avg_price(_symbol_temp_btc)
if _avg_price_temp_btc[0] == 'OK':
_tot_btc_free = _tot_btc_free + (_avg_price_temp_btc[1] * _my_asset.get('free'))
_tot_btc_locked = _tot_btc_locked + (_avg_price_temp_btc[1] * _my_asset.get('locked'))
"""
TOLTO perchè potrebbe dare 'Symbol LDsymbol_firstUSDT does not exist'
Questo perchè se si mette un symbol_first su Savings gli antenpone LD, mentre se si mettono su POOL non le elenca proprio
Esempio: {'asset': 'LDDOT', 'free': '253.08828200', 'locked': '0.00000000'}
else:
_response_tuple = ('NOK', _avg_price_temp_btc[1])
"""
# Tot Usd
_avg_price_temp_usdt = self.general_get_symbol_avg_price(_symbol_temp_usdt)
if _avg_price_temp_usdt[0] == 'OK':
_tot_usd_free = _tot_usd_free + (_avg_price_temp_usdt[1] * _my_asset.get('free'))
_tot_usd_locked = _tot_usd_locked + (_avg_price_temp_usdt[1] * _my_asset.get('locked'))
"""
TOLTO perchè potrebbe dare 'Symbol LDsymbol_firstUSDT does not exist'
Questo perchè se si mette un symbol_first su Savings gli antenpone LD, mentre se si mettono su POOL non le elenca proprio
Esempio: {'asset': 'LDDOT', 'free': '253.08828200', 'locked': '0.00000000'}
else:
_response_tuple = ('NOK', _avg_price_temp_usdt[1])
"""
_response_tuple = ('OK', True)
if _response_tuple[0] == 'OK':
# Add Estimated Value BTC & USD at the first position of the list
_tot_btc = _tot_btc_free + _tot_btc_locked
_tot_usd = _tot_usd_free + _tot_usd_locked
_my_balance.insert( 0 , { 'totals' : { 'tot_btc_free': _tot_btc_free,
'tot_btc_locked': _tot_btc_locked,
'tot_usd_free': _tot_usd_free,
'tot_usd_locked': _tot_usd_locked,
'tot_btc': _tot_btc,
'tot_usd': _tot_usd } } )
_response_tuple = ('OK', _my_balance)
else:
# Furues Wallet
if self.wallet == 'futures' and _account_info:
# For every Asset
for _what_find in _account_info:
if ( Decimal(_what_find.get('balance')) ) > 0: # Only Asset with something
"""""""""""""""""""""""""""""""""
Build Wallet with List Assets Dict
"""""""""""""""""""""""""""""""""
# Build Asset Dict
_my_asset = { 'asset' : _what_find.get('asset'),
'free' : Decimal(_what_find.get('withdrawAvailable')),
'locked' : Decimal(_what_find.get('balance')) - Decimal(_what_find.get('withdrawAvailable')) }
# Build List Assets Dict
_my_balance.append(_my_asset)
if _my_asset.get('asset') == 'USDT':
_tot_usd = _tot_usd + Decimal(_what_find.get('balance'))
# Add Total USD at the first position of the list
_my_balance.insert( 0 , { 'totals' : { 'tot_usd': _tot_usd } } )
# Result
_response_tuple = ('OK', _my_balance)
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','account_get_balance_total',_inputs,_what_finds+' not in _account_info')}")
return(_response_tuple)
# Get Account Balance Asset Free --> spot + margin + futures
def account_get_balance_asset_free(self, p_symbol):
# Prepare
_inputs = f"{self.wallet}|{p_symbol}"
_response_tuple = None
_asset_balance_response = None
_assets_balance_response = None
_bal_decimal = None
try:
if self.wallet == 'spot':
_asset_balance_response = self.client.get_asset_balance(asset=p_symbol)
if _asset_balance_response:
if _asset_balance_response.get('free'):
_bal_decimal = Decimal(_asset_balance_response.get('free'))
_response_tuple = ('OK', _bal_decimal)
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','account_get_balance_asset_free',_inputs,'_asset_balance_response.get(free) is None')}")
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','account_get_balance_asset_free',_inputs,'_asset_balance_response is None')}")
elif self.wallet == 'margin':
_account_info = None
_what_find = None
_what_finds = "userAssets"
_account_info = self.client.get_margin_account()
if _what_finds in _account_info:
for _what_find in _account_info[_what_finds]: # For every Balances
if _what_find.get('asset') == p_symbol.upper():
_bal_decimal = Decimal(_what_find.get('free'))
_response_tuple = ('OK', _bal_decimal)
break
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','account_get_balance_asset_free',_inputs,p_symbol+' not found')}")
continue
elif self.wallet == 'futures':
_assets_balance_response = self.account_get_balance_total()
if _assets_balance_response[0] == 'OK':
for _asset_balance_response in _assets_balance_response[1]:
if _asset_balance_response.get('asset') == p_symbol.upper():
if _asset_balance_response.get('free'):
_bal_decimal = Decimal(_asset_balance_response.get('free'))
_response_tuple = ('OK', _bal_decimal)
break
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','account_get_balance_asset_free',_inputs,'_asset_balance_response.get(free) is None')}")
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','account_get_balance_asset_free',_inputs, p_symbol.upper()+' not found')}")
else:
_response_tuple = ('NOK', f"{ utility.my_log('Error','account_get_balance_asset_free',_inputs,_assets_balance_response[1])}")
except BinanceAPIException as e:
_error = str(e).split(":")[1]
_response_tuple = ('NOK', _error)
except Exception:
_response_tuple = ('NOK', f"{ utility.my_log('Exception','account_get_balance_asset_free',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# Calculate Account exact Quantity to BUY --> spot + margin
def account_get_quantity_to_buy(self, p_what_fee, p_type, p_size, p_how2get_qta2buy, p_price = None):
# Prepare
_inputs = f"{self.wallet}|{p_what_fee}|{p_type}|{p_size}|{p_how2get_qta2buy}|{p_price}|{self.symbol_first}|{self.symbol_second}"
_response_tuple = None
_symbol_bal_second_free = None
_symbol_bal_second_tot_estimated = None
_symbol_lot_size = None
_symbol_step_size_value = None
_symbol_min_qty_value = None
_symbol_min_notional = None
_symbol_min_notional_value = None
_symbol_price = None
_symbol_price_value = None
_symbol_fee = None
_symbol_fee_value = None
_symbol_fee_perc = None
# Prepare Quantity Vars
quantity_pre_size_applied = None
quantity_post_size_applied = None
quantity_pre_stepSize_applied = None
quantity_post_stepSize_applied = None
quantity_processed_final = None
# By default rounding setting in python is ROUND_HALF_EVEN
getcontext().rounding = ROUND_DOWN
""" Get Owned Second Asset Balance Free """
_symbol_bal_second_free = self.account_get_balance_asset_free(self.symbol_second)
if _symbol_bal_second_free[0] != 'OK':
_response_tuple = ('NOK', _symbol_bal_second_free[1])
return(_response_tuple)
""" Get Owned Second Asset Balance """
if p_how2get_qta2buy == 'total':
# Symbol Bal Second TOT Estimated Asset Balance
_symbol_bal_second_tot_estimated = self.account_get_balance_total()
if _symbol_bal_second_tot_estimated[0] == 'OK':
pass
# DA RIVEVEDERE PERCHÈ CON SELF.SYMBOL_SECOND = USDT NON FUNZIONEREBBE
#quantity_pre_size_applied = _symbol_bal_second_tot_estimated[1][0].get('totals').get(f"tot_{self.symbol_second.lower()}")
else:
_response_tuple = ('NOK', _symbol_bal_second_tot_estimated[1])
return(_response_tuple)
elif p_how2get_qta2buy == 'only_available':
# Symbol Bal Second AVAILABLE Asset Balance
quantity_pre_size_applied = _symbol_bal_second_free[1]
""" Build bal to use & size """
# I break down the formula quantity_post_size_applied = round(Decimal(quantity_pre_size_applied) / Decimal(100) * Decimal(p_size), 5)
# into elementary steps
# Default Value
_p_size_str = None
_p_size_decimal = None
_quantity_pre_size_applied_decimal = None
_100_int = 100
_100_str = None
_100_decimal = None
_division = None
_multiplication = None
_inputs_temp = None
# Prepare p_size ( str -> decimal )
_p_size_str = str(p_size)
try:
_p_size_decimal = Decimal(_p_size_str)
except Exception:
_inputs_temp = f"||{type(p_size)},{p_size}|{type(_p_size_str)},{_p_size_str}|{type(_p_size_decimal)},{_p_size_decimal}"
_response_tuple = ('NOK', f"{ utility.my_log('Exception','account_get_quantity_to_buy',_inputs+_inputs_temp,traceback.format_exc(2))}")
return(_response_tuple)
# Prepare 100 ( str -> decimal )
_100_str = str(_100_int)
try:
_100_decimal = Decimal(_100_str)
except Exception:
_inputs_temp = f"||{type(_100_int)},{_100_int}|{type(_100_str)},{_100_str}|{type(_100_decimal)},{_100_decimal}"
_response_tuple = ('NOK', f"{ utility.my_log('Exception','account_get_quantity_to_buy',_inputs+_inputs_temp,traceback.format_exc(2))}")
return(_response_tuple)
# Prepare quantity_pre_size_applied
try:
_quantity_pre_size_applied_decimal = Decimal(quantity_pre_size_applied)
except Exception:
_inputs_temp = f"||{type(quantity_pre_size_applied)},{quantity_pre_size_applied}|{type(_quantity_pre_size_applied_decimal)},{_quantity_pre_size_applied_decimal}"
_response_tuple = ('NOK', f"{ utility.my_log('Exception','account_get_quantity_to_buy',_inputs+_inputs_temp,traceback.format_exc(2))}")
return(_response_tuple)
# Operate Division
try:
_division = _quantity_pre_size_applied_decimal / _100_decimal
except Exception:
_inputs_temp = f"||{type(_100_decimal)},{_100_decimal}|{type(_quantity_pre_size_applied_decimal)},{_quantity_pre_size_applied_decimal}|{type(_division)},{_division}"
_response_tuple = ('NOK', f"{ utility.my_log('Exception','account_get_quantity_to_buy',_inputs+_inputs_temp,traceback.format_exc(2))}")
return(_response_tuple)
# Operate Multiplication
try:
_multiplication = _division * _p_size_decimal
except Exception:
_inputs_temp = f"||{type(_p_size_decimal)},{_p_size_decimal}|{type(_division)},{_division}|{type(_multiplication)},{_multiplication}"
_response_tuple = ('NOK', f"{ utility.my_log('Exception','account_get_quantity_to_buy',_inputs,traceback.format_exc(2))}")
return(_response_tuple)
# Operate Round
try:
quantity_post_size_applied = round(_multiplication, 5)
except Exception:
_inputs_temp = f"||{type(_multiplication)},{_multiplication}|{type(quantity_post_size_applied)},{quantity_post_size_applied}"
_response_tuple = ('NOK', f"{ utility.my_log('Exception','account_get_quantity_to_buy',_inputs+_inputs_temp,traceback.format_exc(2))}")
return(_response_tuple)