-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbinance_swap.py
1247 lines (1146 loc) · 52.7 KB
/
binance_swap.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 json
from decimal import Decimal
import ccxt.async_support
from ccxt import ArgumentsRequired, BadRequest
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import DDoSProtection
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import InvalidNonce
from ccxt_ext.ccxt_ext import CCXTExtension
from ccxt_ext.errors import ChangeMarginTypeError, ChangePositionError
from swap_api import SwapApi
class BinanceSwap(SwapApi, CCXTExtension, ccxt.async_support.binance):
# ------------------------------------------------------------------------------------------------------------------
def describe(self):
return self.deep_extend(super().describe(), {
'id': 'binance',
'name': 'Binance',
'countries': ['JP', 'MT'], # Japan, Malta
'rateLimit': 500,
'certified': True,
'has': {
'clientOrderIdSupport': True,
'singlePositionSideSupport': True,
'dualPositionSideSupport': True,
'isolatedMarginTypeSupport': True,
'crossedMarginTypeSupport': True,
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/29604020-d5483cdc-87ee-11e7-94c7-d1a8d9169293.jpg',
'test': {
'fapiPublic': 'https://testnet.binancefuture.com/fapi/v1',
'fapiPrivate': 'https://testnet.binancefuture.com/fapi/v1',
},
'api': {
'web': 'https://www.binance.com',
'wapi': 'https://api.binance.com/wapi/v3',
'sapi': 'https://api.binance.com/sapi/v1',
'fapiPublic': 'https://fapi.binance.com/fapi/v1',
'fapiPrivate': 'https://fapi.binance.com/fapi/v1',
'fapiPrivatev2': 'https://fapi.binance.com/fapi/v2',
'public': 'https://api.binance.com/api/v3',
'private': 'https://api.binance.com/api/v3',
'v3': 'https://api.binance.com/api/v3',
'v1': 'https://api.binance.com/api/v1',
},
'www': 'https://www.binance.com',
'referral': 'https://www.binance.com/?ref=10205187',
'doc': [
'https://binance-docs.github.io/apidocs/spot/en',
],
'api_management': 'https://www.binance.com/en/usercenter/settings/api-management',
'fees': 'https://www.binance.com/en/fee/schedule',
},
'api': {
'web': {
'get': [
'exchange/public/product',
'assetWithdraw/getAllAsset.html',
],
},
# the API structure below will need 3-layer apidefs
'fapiPublic': {
'get': [
'ping',
'time',
'exchangeInfo',
'depth',
'trades',
'historicalTrades',
'aggTrades',
'klines',
'fundingRate',
'premiumIndex',
'ticker/24hr',
'ticker/price',
'ticker/bookTicker',
'allForceOrders',
'openInterest',
'leverageBracket',
],
},
'fapiPrivate': {
'get': [
'allOrders',
'openOrder',
'openOrders',
'order',
'account',
'balance',
'positionSide/dual',
'positionMargin/history',
'positionRisk',
'userTrades',
'income',
],
'post': [
'batchOrders',
'positionSide/dual',
'positionMargin',
'marginType',
'order',
'leverage',
'listenKey',
],
'put': [
'listenKey',
],
'delete': [
'batchOrders',
'order',
'allOpenOrders',
'listenKey',
],
},
'fapiPrivatev2': {
'get': [
'positionRisk',
'account',
'balance',
]
},
'public': {
'get': [
'ping',
'time',
'depth',
'trades',
'aggTrades',
'historicalTrades',
'klines',
'ticker/24hr',
'ticker/price',
'ticker/bookTicker',
'exchangeInfo',
],
'put': ['userDataStream'],
'post': ['userDataStream'],
'delete': ['userDataStream'],
},
'private': {
'get': [
'allOrderList', # oco
'openOrderList', # oco
'orderList', # oco
'order',
'openOrders',
'allOrders',
'account',
'myTrades',
],
'post': [
'order/oco',
'order',
'order/test',
],
'delete': [
'orderList', # oco
'order',
],
},
},
'fees': {
'trading': {
'tierBased': False,
'percentage': True,
'taker': 0.001,
'maker': 0.001,
},
},
'commonCurrencies': {
'BCC': 'BCC', # kept for backward-compatibility https://github.com/ccxt/ccxt/issues/4848
'YOYO': 'YOYOW',
},
# exchange-specific options
'options': {
'fetchTradesMethod': 'publicGetAggTrades', # publicGetTrades, publicGetHistoricalTrades
'fetchTickersMethod': 'publicGetTicker24hr',
'defaultTimeInForce': 'GTC', # 'GTC' = Good To Cancel(default), 'IOC' = Immediate Or Cancel
'defaultLimitOrderType': 'limit', # or 'limit_maker'
'defaultType': 'spot', # 'spot', 'future'
'hasAlreadyAuthenticatedSuccessfully': False,
'warnOnFetchOpenOrdersWithoutSymbol': True,
'recvWindow': 5 * 1000, # 5 sec, binance default
'timeDifference': 0, # the difference between system clock and Binance clock
'adjustForTimeDifference': False, # controls the adjustment logic upon instantiation
'parseOrderToPrecision': False, # force amounts and costs in parseOrder to precision
'newOrderRespType': {
'market': 'FULL', # 'ACK' for order id, 'RESULT' for full order or 'FULL' for order with fills
'limit': 'RESULT', # we change it from 'ACK' by default to 'RESULT'
},
},
'exceptions': {
'API key does not exist': AuthenticationError,
'Order would trigger immediately.': InvalidOrder,
'Account has insufficient balance for requested action.': InsufficientFunds,
'Rest API trading is not enabled.': ExchangeNotAvailable,
"You don't have permission.": PermissionDenied, # {"msg":"You don't have permission.","success":false}
'Market is closed.': ExchangeNotAvailable, # {"code":-1013,"msg":"Market is closed."}
'-1000': ExchangeNotAvailable,
# {"code":-1000,"msg":"An unknown error occured while processing the request."}
'-1013': InvalidOrder, # createOrder -> 'invalid quantity'/'invalid price'/MIN_NOTIONAL
'-1021': InvalidNonce, # 'your time is ahead of server'
'-1022': AuthenticationError, # {"code":-1022,"msg":"Signature for self request is not valid."}
'-1100': InvalidOrder, # createOrder(symbol, 1, asdf) -> 'Illegal characters found in parameter 'price'
'-1104': ExchangeError, # Not all sent parameters were read, read 8 parameters but was sent 9
'-1128': ExchangeError, # {"code":-1128,"msg":"Combination of optional parameters invalid."}
'-2010': ExchangeError,
# generic error code for createOrder -> 'Account has insufficient balance for requested action.', {"code":-2010,"msg":"Rest API trading is not enabled."}, etc...
'-2011': OrderNotFound, # cancelOrder(1, 'BTC/USDT') -> 'UNKNOWN_ORDER'
'-2013': OrderNotFound, # fetchOrder(1, 'BTC/USDT') -> 'Order does not exist'
'-2014': AuthenticationError, # {"code":-2014, "msg": "API-key format invalid."}
'-2015': AuthenticationError, # "Invalid API-key, IP, or permissions for action."
'-2019': InsufficientFunds, # {"code":-2019,"msg":"Margin is insufficient."}
'-4047': ChangeMarginTypeError,
# {"code":-4047,"msg":"Margin type cannot be changed if there exists open orders."}
'-4050': InsufficientFunds, # {"code":-4050,"msg":"Cross balance insufficient."}
'-4067': ChangePositionError,
# {"code":-4067,"msg":"Position side cannot be changed if there exists position."}
'-4068': ChangePositionError,
# {"code":-4068,"msg":"Position side cannot be changed if there exists position."}
'-4061': ChangePositionError,
# {"code":-4061,"msg":"Order's position side does not match user's setting."}
},
'ignore_exceptions': {
'-4059': ExchangeError, # {"code":-4059,"msg":"No need to change position side."}
'-4046': ExchangeError, # {"code":-4046,"msg":"No need to change margin type."}
},
'fee_tiers': [
{
'level': 0,
'maker': Decimal('0.00020'),
'taker': Decimal('0.00040'),
},
{
'level': 1,
'maker': Decimal('0.00016'),
'taker': Decimal('0.00040'),
},
{
'level': 2,
'maker': Decimal('0.00014'),
'taker': Decimal('0.00035'),
},
{
'level': 3,
'maker': Decimal('0.00012'),
'taker': Decimal('0.00032'),
},
{
'level': 4,
'maker': Decimal('0.00010'),
'taker': Decimal('0.00030'),
},
{
'level': 5,
'maker': Decimal('0.00008'),
'taker': Decimal('0.00027'),
},
{
'level': 6,
'maker': Decimal('0.00006'),
'taker': Decimal('0.00025'),
},
{
'level': 7,
'maker': Decimal('0.00004'),
'taker': Decimal('0.00022'),
},
{
'level': 8,
'maker': Decimal('0.00002'),
'taker': Decimal('0.00020'),
},
{
'level': 9,
'maker': Decimal('0.00000'),
'taker': Decimal('0.00017'),
},
]
})
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
url += '/' + path
if api == 'wapi':
url += '.html'
userDataStream = (path == 'userDataStream') or (path == 'listenKey')
if path == 'historicalTrades':
if self.apiKey:
headers = {
'X-MBX-APIKEY': self.apiKey,
}
else:
raise AuthenticationError(self.id + ' historicalTrades endpoint requires `apiKey` credential')
elif userDataStream:
if self.apiKey:
# v1 special case for userDataStream
body = self.urlencode(params)
headers = {
'X-MBX-APIKEY': self.apiKey,
'Content-Type': 'application/x-www-form-urlencoded',
}
else:
raise AuthenticationError(self.id + ' userDataStream endpoint requires `apiKey` credential')
if (api == 'private') or (api == 'sapi') or (api == 'wapi' and path != 'systemStatus') or (
api == 'fapiPrivate') or (api == 'fapiPrivatev2'):
self.check_required_credentials()
query = None
if (api == 'sapi') and (path == 'asset/dust'):
query = self.urlencode_with_array_repeat(self.extend({
'timestamp': self.nonce(),
'recvWindow': self.options['recvWindow'],
}, params))
else:
query = self.urlencode(self.extend({
'timestamp': self.nonce(),
'recvWindow': self.options['recvWindow'],
}, params))
signature = self.hmac(self.encode(query), self.encode(self.secret))
query += '&' + 'signature=' + signature
headers = {
'X-MBX-APIKEY': self.apiKey,
}
if (method == 'GET') or (method == 'DELETE') or (api == 'wapi'):
url += '?' + query
else:
body = query
headers['Content-Type'] = 'application/x-www-form-urlencoded'
else:
# userDataStream endpoints are public, but POST, PUT, DELETE
# therefore they don't accept URL query arguments
# https://github.com/ccxt/ccxt/issues/5224
if not userDataStream:
if params:
url += '?' + self.urlencode(params)
return {'url': url, 'method': method, 'body': body, 'headers': headers}
async def fetch_markets(self, params=None):
response = await self.fapiPublicGetExchangeInfo()
if self.options['adjustForTimeDifference']:
await self.load_time_difference()
markets = response['symbols']
result = []
for i in range(0, len(markets)):
market = markets[i]
id = market['symbol']
baseId = market['baseAsset']
quoteId = market['quoteAsset']
base = self.common_currency_code(baseId)
quote = self.common_currency_code(quoteId)
symbol = base + '/' + quote
filters = self.index_by(market['filters'], 'filterType')
precision = {
# 'base': market['baseAssetPrecision'],
# 'quote': market['quotePrecision'],
'amount': market['quantityPrecision'],
'price': market['pricePrecision'],
}
active = (market['status'] == 'TRADING')
entry = {
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'info': market,
'active': active,
'precision': precision,
'limits': {
'amount': {
'min': None,
'max': None,
},
'price': {
'min': None,
'max': None,
},
'cost': {
'min': None,
'max': None,
},
},
# 维持保证金比例
'maintMarginPercent': self.safe_decimal(market, 'maintMarginPercent'),
# 所需保证金比例
'requiredMarginPercent': self.safe_decimal(market, 'requiredMarginPercent'),
}
# 价格限制
if 'PRICE_FILTER' in filters:
filter = filters['PRICE_FILTER']
entry['limits']['price'] = {
'min': self.safe_decimal(filter, 'minPrice'),
'max': self.safe_decimal(filter, 'maxPrice'),
# 步长
'stepSize': self.safe_decimal(filter, 'tickSize'),
}
# 数量限制
if 'LOT_SIZE' in filters:
filter = filters['LOT_SIZE']
entry['limits']['amount'] = {
'min': self.safe_decimal(filter, 'minQty'),
'max': self.safe_decimal(filter, 'maxQty'),
# 步长
'stepSize': self.safe_decimal(filter, 'stepSize'),
}
# 市价订单数量限制
if 'MARKET_LOT_SIZE' in filters:
# 字段同数量限制
pass
# 价格比限制
if 'PERCENT_PRICE' in filters:
# multiplierUp: 价格上限百分比
# multiplierDown: 价格下限百分比
pass
# 最多挂单数限制
if 'MAX_NUM_ORDERS' in filters:
# limit
pass
result.append(entry)
return result
async def fetch_balance(self, params=None):
response = await self.fapiPrivatev2GetAccount()
#
# spot
#
# {
# makerCommission: 10,
# takerCommission: 10,
# buyerCommission: 0,
# sellerCommission: 0,
# canTrade: True,
# canWithdraw: True,
# canDeposit: True,
# updateTime: 1575357359602,
# accountType: "MARGIN",
# balances: [
# {asset: "BTC", free: "0.00219821", locked: "0.00000000" },
# ]
# }
#
# futures(fapi)
#
# {
# "feeTier": 0, // 手续费等级
# "canTrade": true, // 是否可以交易
# "canDeposit": true, // 是否可以入金
# "canWithdraw": true, // 是否可以出金
# "updateTime": 0,
# "totalInitialMargin": "0.00000000", // 但前所需起始保证金总额(存在逐仓请忽略)
# "totalMaintMargin": "0.00000000", // 维持保证金总额
# "totalWalletBalance": "23.72469206", // 账户总余额
# "totalUnrealizedProfit": "0.00000000", // 持仓未实现盈亏总额
# "totalMarginBalance": "23.72469206", // 保证金总余额
# "totalPositionInitialMargin": "0.00000000", // 持仓所需起始保证金(基于最新标记价格)
# "totalOpenOrderInitialMargin": "0.00000000", // 当前挂单所需起始保证金(基于最新标记价格)
# "totalCrossWalletBalance": "23.72469206", // 全仓账户余额
# "totalCrossUnPnl": "0.00000000", // 全仓持仓未实现盈亏总额
# "availableBalance": "23.72469206", // 可用余额
# "maxWithdrawAmount": "23.72469206" // 最大可转出余额
# "assets": [
# {
# "asset": "USDT", //资产
# "walletBalance": "23.72469206", //余额
# "unrealizedProfit": "0.00000000", // 未实现盈亏
# "marginBalance": "23.72469206", // 保证金余额
# "maintMargin": "0.00000000", // 维持保证金
# "initialMargin": "0.00000000", // 当前所需起始保证金
# "positionInitialMargin": "0.00000000", // 持仓所需起始保证金(基于最新标记价格)
# "openOrderInitialMargin": "0.00000000", // 当前挂单所需起始保证金(基于最新标记价格)
# "crossWalletBalance": "23.72469206", //全仓账户余额
# "crossUnPnl": "0.00000000" // 全仓持仓未实现盈亏
# "availableBalance": "23.72469206", // 可用余额
# "maxWithdrawAmount": "23.72469206" // 最大可转出余额
# }
# ],
# "positions": [ // 头寸,将返回所有市场symbol。
# //根据用户持仓模式展示持仓方向,即双向模式下只返回BOTH持仓情况,单向模式下只返回 LONG 和 SHORT 持仓情况
# {
# "symbol": "BTCUSDT", // 交易对
# "initialMargin": "0", // 当前所需起始保证金(基于最新标记价格)
# "maintMargin": "0", //维持保证金
# "unrealizedProfit": "0.00000000", // 持仓未实现盈亏
# "positionInitialMargin": "0", // 持仓所需起始保证金(基于最新标记价格)
# "openOrderInitialMargin": "0", // 当前挂单所需起始保证金(基于最新标记价格)
# "leverage": "100", // 杠杆倍率
# "isolated": true, // 是否是逐仓模式
# "entryPrice": "0.00000", // 持仓成本价
# "maxNotional": "250000", // 当前杠杆下用户可用的最大名义价值
# "positionSide": "BOTH" // 持仓方向。
# }
# ]
# }
#
result = {'info': response, 'currencies': {}}
balances = self.safe_value(response, 'assets', [])
for balance in balances:
currencyId = self.safe_string(balance, 'asset')
code = self.safe_currency_code(currencyId)
account = self.account()
account['free'] = self.safe_decimal(balance, 'availableBalance')
account['total'] = self.safe_decimal(balance, 'walletBalance')
account['used'] = account['total'] - account['free']
result['currencies'][code] = account
result['totalInitialMargin'] = self.safe_decimal(response, 'totalInitialMargin')
result['totalMaintMargin'] = self.safe_decimal(response, 'totalMaintMargin')
result['totalWalletBalance'] = self.safe_decimal(response, 'totalWalletBalance')
result['totalUnrealizedProfit'] = self.safe_decimal(response, 'totalUnrealizedProfit')
result['totalMarginBalance'] = self.safe_decimal(response, 'totalMarginBalance')
result['totalPositionInitialMargin'] = self.safe_decimal(response, 'totalPositionInitialMargin')
result['totalOpenOrderInitialMargin'] = self.safe_decimal(response, 'totalOpenOrderInitialMargin')
result['totalCrossWalletBalance'] = self.safe_decimal(response, 'totalCrossWalletBalance')
result['totalCrossUnPnl'] = self.safe_decimal(response, 'totalCrossUnPnl')
result['availableBalance'] = self.safe_decimal(response, 'availableBalance')
result['maxWithdrawAmount'] = self.safe_decimal(response, 'maxWithdrawAmount')
return result
async def fetch_order_book(self, symbol, limit=None, params=None):
await self.load_markets()
market = self.market(symbol)
request = {'symbol': market['id']}
if limit is not None:
# default 100, max 5000
request['limit'] = min(int(limit), 5000)
response = await self.fapiPublicGetDepth(self.extend(request, params))
orderbook = self.parse_order_book(response)
orderbook['nonce'] = self.safe_integer(response, 'lastUpdateId')
return orderbook
async def create_order(self, symbol, type, side, amount=None, price=None, clientOrderId=None, positionSide=None, reduceOnly=False, params=None):
await self.load_markets()
market = self.market(symbol)
amount = amount and self.amount_to_precision(symbol, amount)
price = price and self.price_to_precision(symbol, price)
uppercaseType = type.upper()
request = {
'symbol': market['id'],
'type': uppercaseType,
'side': side.upper(),
}
newClientOrderId = clientOrderId
request['newClientOrderId'] = newClientOrderId
if uppercaseType == 'MARKET':
quoteOrderQty = self.safe_decimal(params, 'quoteOrderQty')
if quoteOrderQty is not None:
request['quoteOrderQty'] = quoteOrderQty
params = self.omit(params, 'quoteOrderQty')
else:
request['quantity'] = amount
else:
request['quantity'] = amount
timeInForceIsRequired = False
priceIsRequired = False
stopPriceIsRequired = False
if uppercaseType == 'LIMIT':
priceIsRequired = True
timeInForceIsRequired = True
elif (uppercaseType == 'STOP_LOSS') or (uppercaseType == 'TAKE_PROFIT'):
stopPriceIsRequired = True
priceIsRequired = True
elif (uppercaseType == 'STOP_LOSS_LIMIT') or (uppercaseType == 'TAKE_PROFIT_LIMIT'):
stopPriceIsRequired = True
priceIsRequired = True
timeInForceIsRequired = True
elif uppercaseType == 'LIMIT_MAKER':
priceIsRequired = True
elif uppercaseType == 'STOP':
stopPriceIsRequired = True
priceIsRequired = True
if priceIsRequired:
if price is None:
raise InvalidOrder(
self.id + ' createSwapOrder method requires a price argument for a ' + type + ' order')
request['price'] = price
if timeInForceIsRequired:
request['timeInForce'] = self.options[
'defaultTimeInForce'] # 'GTC' = Good To Cancel(default), 'IOC' = Immediate Or Cancel
if stopPriceIsRequired:
stopPrice = self.safe_decimal(params, 'stopPrice')
if stopPrice is None:
raise InvalidOrder(
self.id + ' createSwapOrder method requires a stopPrice extra param for a ' + type + ' order')
else:
params = self.omit(params, 'stopPrice')
request['stopPrice'] = stopPrice
if positionSide:
request['positionSide'] = positionSide.upper()
if reduceOnly is not None:
request['reduceOnly'] = reduceOnly
response = await self.fapiPrivatePostOrder(self.extend(request, params))
return self.parse_swap_order(response, market)
async def cancel_order(self, id, symbol, clientOrderId=None, params=None):
if symbol is None:
raise ArgumentsRequired(self.id + ' cancelOrder requires a symbol argument')
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
# 'orderId': int(id),
# 'origClientOrderId': id,
}
origClientOrderId = clientOrderId
if origClientOrderId is not None:
request['origClientOrderId'] = origClientOrderId
else:
request['orderId'] = int(id)
response = await self.fapiPrivateDeleteOrder(self.extend(request, params))
return {
'info': response
}
async def fetch_open_orders(self, symbol=None, since=None, limit=None, fromId=None, direct='next', params=None):
if symbol is None:
raise ArgumentsRequired(self.id + ' fetch_open_orders requires a symbol argument')
await self.load_markets()
market = self.market(symbol)
if direct is not None and direct != 'next':
raise ArgumentsRequired('in binance "direct" can only be next')
request = {}
if symbol is not None:
request['symbol'] = market['id']
if fromId is not None:
request['orderId'] = fromId
response = await self.fapiPrivateGetOpenOrders(self.extend(request, params))
return self.parse_orders(response, market, since, limit)
async def fetch_closed_orders(self, symbol, since=None, limit=None, fromId=None, direct='next', params=None):
orders = await self.fetch_orders(symbol, since, limit, fromId, direct, params)
return self.filter_by_array(orders, 'status', values={'closed', 'canceled', 'canceling'}, indexed=False)
async def fetch_order(self, id=None, symbol=None, clientOrderId=None, params=None):
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchOrder requires a symbol argument')
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
origClientOrderId = clientOrderId
if origClientOrderId is not None:
request['origClientOrderId'] = origClientOrderId
else:
request['orderId'] = int(id)
response = await self.fapiPrivateGetOrder(self.extend(request, params))
return self.parse_swap_order(response, market)
async def fetch_orders(self, symbol, since=None, limit=None, fromId=None, direct='next', params=None):
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchOrders requires a symbol argument')
if direct is not None and direct != 'next':
raise ArgumentsRequired('in binance "direct" can only be next')
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if since is not None:
request['startTime'] = since
if limit is not None:
# 默认值 500; 最大值 1000
request['limit'] = min(int(limit), 1000)
if fromId is not None:
request['orderId'] = fromId
response = await self.fapiPrivateGetAllOrders(self.extend(request, params))
return self.parse_swap_orders(response, market, since, limit)
async def fetch_my_trades(self, symbol, since=None, limit=None, fromId=None, direct='next', params=None):
if symbol is None:
raise ArgumentsRequired(self.id + ' fetchMyTrades requires a symbol argument')
if direct is not None and direct != 'next':
raise ArgumentsRequired('in binance "direct" can only be next')
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if since is not None:
request['startTime'] = since
if limit is not None:
request['limit'] = limit
if fromId is not None:
try:
params['fromId'] = int(fromId)
except (TypeError, ValueError):
raise BadRequest(self.id + f' fetchMyTrades invalid fromId: {fromId}')
response = await self.fapiPrivateGetUserTrades(self.extend(request, params))
return self.parse_swap_trades(response, market)
async def change_leverage(self, symbol, leverage, positionSide=None, params=None):
if symbol is None:
raise ArgumentsRequired(self.id + ' swapLeverage requires a symbol argument')
try:
leverage = int(leverage)
except (TypeError, ValueError):
raise BadRequest(f'swapLeverage invalid leverage: {leverage}')
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
# 目标杠杆倍数:1 到 125 整数
'leverage': leverage,
}
response = await self.fapiPrivatePostLeverage(self.extend(request, params))
return {
'info': response,
}
async def change_margin_type(self, symbol, marginType, positionSide=None, params=None):
if symbol is None:
raise ArgumentsRequired(self.id + ' swapMarginType requires a symbol argument')
margin_type = marginType.upper()
if margin_type not in {'ISOLATED', 'CROSSED'}:
raise BadRequest(f'swapMarginType invalid type: {margin_type}')
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
'marginType': margin_type,
}
response = await self.fapiPrivatePostMarginType(self.extend(request, params))
return {
'info': response,
}
async def change_isolated_margin(self, symbol, positionSide, direction, amount, params=None):
if symbol is None:
raise ArgumentsRequired(self.id + ' swapPositionMargin requires a symbol argument')
direction = direction.upper()
if direction not in {'ASC', 'DESC'}:
raise BadRequest(f'swapPositionMargin invalid type: {direction}')
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
'amount': Decimal(amount),
'type': 1 if 'ASC' == direction.upper() else 2,
}
if positionSide:
request['positionSide'] = positionSide.upper()
response = await self.fapiPrivatePostPositionMargin(self.extend(request, params))
return {
'info': response
}
async def change_position_side(self, symbol, positionSide, params=None):
request = {'dualSidePosition': 'true' if positionSide == 'dual' else 'false'}
response = await self.fapiPrivatePostPositionSideDual(self.extend(request, params))
return {
'info': response,
}
async def fetch_trading_fee_rates(self, symbol=None, params=None):
response = await self.fapiPrivateGetAccount(params)
fee_tier = response.get('feeTier')
fee_tier = self.fee_tiers[int(fee_tier)]
return [{
'symbol': None,
'maker': fee_tier['maker'],
'taker': fee_tier['taker'],
'info': response
}]
async def fetch_position_side(self, symbol=None, params=None):
response = await self.fapiPrivateGetPositionSideDual(params)
return {
'info': response,
'positionSide': 'dual' if response.get('dualSidePosition') else 'single'
}
async def fetch_funding_records(self, symbol=None, since=None, limit=None, fromId=None, direct='next', params=None):
request = {}
if symbol is not None:
await self.load_markets()
market = self.market(symbol)
request['symbol'] = market['id']
request['incomeType'] = 'FUNDING_FEE'
if since is not None:
request['startTime'] = since
if limit is not None:
request['limit'] = limit
response = await self.fapiPrivateGetIncome(self.extend(request, params))
return self.parse_funding_fees(response)
async def fetch_positions(self, symbol=None, params=None):
await self.load_markets()
response = await self.fapiPrivatev2GetPositionRisk(params)
return self.parse_swap_positions(response, symbol)
def parse_swap_order_status(self, status):
statuses = {
'NEW': 'open',
'PARTIALLY_FILLED': 'open',
'FILLED': 'closed',
'CANCELED': 'canceled',
'PENDING_CANCEL': 'canceling', # currently unused
'REJECTED': 'rejected',
'EXPIRED': 'canceled',
}
return self.safe_string(statuses, status, status)
async def fetch_incomes(self, symbol=None, since=None, limit=None, fromId=None, direct='next', params=None):
request = {}
await self.load_markets()
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
if 'incomeType' in params:
income_type = params.pop('incomeType').upper()
if income_type not in {'TRANSFER', 'WELCOME_BONUS', 'REALIZED_PNL',
'FUNDING_FEE', 'COMMISSION', 'INSURANCE_CLEAR'}:
raise BadRequest(f'fetchSwapIncome invalid incomeType: {income_type}')
request['incomeType'] = income_type
if since is not None:
request['startTime'] = since
if limit is not None:
request['limit'] = limit
response = await self.fapiPrivateGetIncome(self.extend(request, params))
return self.parse_swap_incomes(response)
def parse_funding_fee(self, result):
return {
'id': None,
'fundingFee': self.safe_decimal(result, 'income'),
'position': None,
'positionValue': None,
'fundingRate': None,
'timestamp': self.safe_integer(result, 'time'),
'info': {}
}
def parse_swap_order(self, order, market=None):
#
# spot
#
# {
# "symbol": "LTCBTC",
# "orderId": 1,
# "clientOrderId": "myOrder1",
# "price": "0.1",
# "origQty": "1.0",
# "executedQty": "0.0",
# "cummulativeQuoteQty": "0.0",
# "status": "NEW",
# "timeInForce": "GTC",
# "type": "LIMIT",
# "side": "BUY",
# "stopPrice": "0.0",
# "icebergQty": "0.0",
# "time": 1499827319559,
# "updateTime": 1499827319559,
# "isWorking": True
# }
#
# futures
#
# {
# "symbol": "BTCUSDT",
# "orderId": 1,
# "clientOrderId": "myOrder1",
# "price": "0.1",
# "origQty": "1.0",
# "executedQty": "1.0",
# "cumQuote": "10.0",
# "status": "NEW",
# "timeInForce": "GTC",
# "type": "LIMIT",
# "side": "BUY",
# "stopPrice": "0.0",
# "updateTime": 1499827319559
# }
#
status = self.parse_swap_order_status(self.safe_string(order, 'status'))
symbol = None
marketId = self.safe_string(order, 'symbol')
if marketId in self.markets_by_id:
market = self.markets_by_id[marketId]
if market is not None:
symbol = market['symbol']
timestamp = None
if 'time' in order:
timestamp = self.safe_integer(order, 'time')
elif 'transactTime' in order:
timestamp = self.safe_integer(order, 'transactTime')
price = self.safe_decimal(order, 'price')
amount = self.safe_decimal(order, 'origQty')
filled = self.safe_decimal(order, 'executedQty')
remaining = None
# - Spot/Margin market: cummulativeQuoteQty
# - Futures market: cumQuote.
# Note self is not the actual cost, since Binance futures uses leverage to calculate margins.
cost = self.safe_decimal_2(order, 'cummulativeQuoteQty', 'cumQuote')
if filled is not None:
if amount is not None:
remaining = amount - filled
if self.options['parseOrderToPrecision']:
remaining = Decimal(self.amount_to_precision(symbol, remaining))
remaining = max(remaining, 0.0)
if price is not None:
if cost is None:
cost = price * filled
id = self.safe_string(order, 'orderId')
type = self.safe_string(order, 'type').lower()
if type == 'market':
if price == 0.0:
if (cost is not None) and (filled is not None):
if (cost > 0) and (filled > 0):
price = cost / filled
if self.options['parseOrderToPrecision']:
price = Decimal(self.price_to_precision(symbol, price))
elif type == 'limit_maker':
type = 'limit'
side = self.safe_string(order, 'side').lower()
fee = None
trades = None
fills = self.safe_value(order, 'fills')
if fills is not None:
trades = self.parse_trades(fills, market)
numTrades = len(trades)
if numTrades > 0:
cost = trades[0]['cost']
fee = {
'cost': trades[0]['fee']['cost'],
'currency': trades[0]['fee']['currency'],
}
for i in range(1, len(trades)):
cost = self.sum(cost, trades[i]['cost'])
fee['cost'] = self.sum(fee['cost'], trades[i]['fee']['cost'])
average = None
if cost is not None: