-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinance_api.py
More file actions
1585 lines (1373 loc) · 63.5 KB
/
binance_api.py
File metadata and controls
1585 lines (1373 loc) · 63.5 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
gate交易所API封装
提供与gate交易所交互的功能,包括获取价格、资金费率、下单、查询仓位等
"""
import time
import json
import hmac
import hashlib
import base64
import asyncio
import uuid
from typing import Dict, List, Optional, Any, Tuple, Union
from decimal import Decimal
import math
import traceback
import urllib.parse
import httpx
import websockets
import logging
import nacl.signing # 添加PyNaCl库依赖
import hmac
import hashlib
from Crypto.Hash import SHA256, HMAC
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from funding_arbitrage_bot.exchanges.base_exchange import BaseExchange
from funding_arbitrage_bot.utils import helpers
class BinanceAPI(BaseExchange):
"""binance交易所API封装类"""
def __init__(
self,
api_key: str,
api_secret: str,
base_url: str = "https://fapi.binance.com",
ws_url: str = "wss://fstream.binance.com/stream",
logger: Optional[logging.Logger] = None,
config: Optional[Dict] = None
):
"""
初始化gate API
Args:
api_key: API密钥
api_secret: API密钥对应的密钥
base_url: REST API基础URL
ws_url: WebSocket API URL
logger: 日志记录器,如果为None则使用默认日志记录器
config: 配置信息,包含交易对精度等设置
"""
self.logger = logger or logging.getLogger(__name__)
self.api_key = api_key.strip()
# 保存原始的API密钥
self.api_secret = api_secret.strip()
# 尝试解码
try:
self.api_secret_bytes = base64.b64decode(self.api_secret)
self.logger.info("成功解码API密钥")
# 如果密钥长度大于32字节,仅取前32字节
if len(self.api_secret_bytes) > 32:
self.api_secret_bytes = self.api_secret_bytes[:32]
self.logger.info(f"API密钥长度为{len(self.api_secret_bytes)}字节,截取前32字节")
except Exception as e:
self.logger.warning(f"无法解码API密钥,可能导致签名问题: {e}")
self.api_secret_bytes = self.api_secret.encode()
self.base_url = base_url
self.ws_url = ws_url
# 保存配置信息
self.config = config or {}
# 价格和资金费率缓存
self.prices = {}
self.funding_rates = {}
# 24小时交易量缓存
self.volumes = {}
# 24小时成交数缓存
self.trade_counts = {}
# 新的数据结构,格式为 {"BTC": {"symbol": "BTCUSDT", "funding_rate": "0.111", "funding_rate_timestamp": "xxxx", "price": 1, "price_timestamp": "xxxx"}}
self.coin_data = {}
# HTTP客户端
self.http_client = httpx.AsyncClient(timeout=10.0)
# WebSocket连接
self.ws = None
self.ws_connected = False
self.ws_task = None
# 默认请求超时时间
self.default_window = 5000 # 5秒
# 价格日志输出控制
self.last_price_log = {}
self.price_log_interval = 300 # 每5分钟记录一次价格
self.price_coins = []
self.depth_data = {}
self.ws_api_key = self.config.get('exchanges', {}).get('binance', {}).get('ed25519_api_key', '')
PRIVATE_KEY_PATH = self.config.get('exchanges', {}).get('binance', {}).get('ed25519_api_secret_path', '')
with open(PRIVATE_KEY_PATH, 'rb') as f:
self.ws_private_key = load_pem_private_key(data=f.read(), password=None)
self.ws_trade = None
self.ws_trade_connected = False
self.ws_trade_task = None
self.ws_trade_pending_message = {}
self.ws_trade_pending_futures = {} # 新增:id -> Future
def create_ed25519_sign(self, request: dict):
# Create signature payload from params
params = request['params']
payload = '&'.join([f'{k}={v}' for k, v in sorted(params.items())])
signature = base64.b64encode(self.ws_private_key.sign(payload.encode('ASCII')))
return signature
async def close(self):
"""关闭API连接"""
if self.http_client:
await self.http_client.aclose()
if self.ws_task:
self.ws_task.cancel()
try:
await self.ws_task
except asyncio.CancelledError:
pass
def gen_sign(self, origin_data: dict):
channel = origin_data.get('channel')
event = origin_data.get('event')
current_time = origin_data.get('current_time')
message = 'channel=%s&event=%s&time=%d' % (channel, event, current_time)
h = hmac.new(self.api_secret.encode("utf8"), message.encode("utf8"), hashlib.sha512)
return h.hexdigest()
def gen_sign_rest(self, params: dict) -> str:
"""
使用 HMAC-SHA256 算法生成币安API签名
Args:
params (dict): 请求参数
Returns:
str: 十六进制格式的签名
"""
# 确保所有参数值都是字符串
params = {k: str(v) for k, v in params.items()}
# 按字母顺序排序并生成查询字符串(不进行URL编码)
query_string = '&'.join([f"{k}={v}" for k, v in sorted(params.items())])
try:
# 创建 HMAC 对象
hmac_obj = HMAC.new(
key=self.api_secret.encode('utf-8'),
msg=query_string.encode('utf-8'),
digestmod=SHA256
)
# 计算签名并转换为十六进制字符串
signature = hmac_obj.hexdigest()
return signature
except Exception as e:
raise RuntimeError(f"Failed to calculate hmac-sha256: {str(e)}")
async def _make_signed_request(
self,
instruction: str,
method: str,
endpoint: str,
params: Optional[Dict] = None,
data: Optional[Dict] = None
) -> Dict:
"""
发送带签名的API请求
todo sign参数问题暂时废弃
Args:
instruction: API指令名称
method: HTTP方法(GET、POST等)
endpoint: API端点(不包含基础URL)
params: URL参数
data: 请求体数据
Returns:
API响应数据
"""
# 准备请求参数
headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}
# if method == 'GET':
# return await self.http_client.get(url=f'{self.base_url}{endpoint}', headers=headers)
pass
async def get_price(self, symbol: str) -> dict:
base_symbol = symbol
if base_symbol in self.coin_data and self.coin_data[base_symbol]["price"] is not None:
return {
"price": self.coin_data[base_symbol]["price"],
"price_timestamp": self.coin_data[base_symbol]["price_timestamp"]
}
else:
return {
"price": None,
"price_timestamp": None
}
async def get_funding_rate(self, symbol: str) -> dict:
# print(self.coin_data)
# 从coin_data中获取资金费率
if symbol in self.coin_data and self.coin_data[symbol]["funding_rate"] is not None:
return {
"funding_rate": self.coin_data[symbol]["funding_rate"],
"funding_rate_timestamp": self.coin_data[symbol]["funding_rate_timestamp"]
}
else:
return {
"funding_rate": None,
"funding_rate_timestamp": None
}
async def place_order_rest(self,
symbol: str,
side: str,
order_type: str = "MARKET",
size: float = None,
price: float = None,
tif: str = "gtc",
is_close=False):
try:
place_order_url = f'{self.base_url}/fapi/v1/order'
bn_symbol = helpers.get_binance_symbol(symbol)
# 处理价格格式化 (对LIMIT订单)
formatted_price = ""
trading_pair_config = None
for pair in self.config.get("trading_pairs", []):
if pair.get("symbol") == symbol:
trading_pair_config = pair
break
if order_type == "LIMIT" and price:
# 从配置中获取价格精度和tick_size
price_precision = 2 # 默认精度
tick_size = 0.01 # 默认tick_size
if trading_pair_config:
price_precision = int(trading_pair_config.get("price_precision", 2))
tick_size = float(trading_pair_config.get("tick_size", 0.01))
# 确保价格是浮点数
price = float(price)
# 调整价格为tick_size的倍数
price = round(price / tick_size) * tick_size
# 控制小数位数,确保不超过配置的精度
price = round(price, price_precision)
# 格式化价格,确保精度符合要求
formatted_price = "{:.{}f}".format(price, price_precision)
# 去除尾部多余的0
formatted_price = formatted_price.rstrip('0').rstrip(
'.') if '.' in formatted_price else formatted_price
self.logger.info(
f"价格处理: 原始价格={price}, 格式化后={formatted_price}, 精度={price_precision}, tick_size={tick_size}")
print(
f"Binance 开仓:价格处理: 原始价格={price}, 格式化后={formatted_price}, 精度={price_precision}, tick_size={tick_size}")
# 构造请求参数
params = {
"symbol": bn_symbol,
"side": side,
"type": order_type,
"quantity": str(size),
"timestamp": str(int(time.time() * 1000)),
"timeInForce": tif.upper()
}
# 添加限价单特有参数
if order_type == "LIMIT":
params.update({
"price": str(formatted_price)
})
# 生成签名
signature = self.gen_sign_rest(params)
# 构造完整的查询字符串,包括签名
# 对每个参数值进行URL编码
encoded_params = {k: urllib.parse.quote(str(v)) for k, v in params.items()}
query_string = '&'.join([f"{k}={v}" for k, v in sorted(encoded_params.items())])
query_string = f"{query_string}&signature={signature}"
# 构造完整URL
url = f"{place_order_url}?{query_string}"
# 设置请求头
headers = {'X-MBX-APIKEY': self.api_key}
self.logger.debug(f"Binance下单URL: {url}")
print(f"Binance下单URL: {url}")
order_res = await self.http_client.post(url, headers=headers)
self.logger.info(f"Binance下单结果: {order_res.text}")
print(f"Binance下单结果: {order_res.text}")
if order_res.status_code == 200:
data = order_res.json()
if "orderId" in data:
return {
"success": True,
"order_id": data['orderId'],
"error": None,
"symbol": symbol,
"side": side,
"size": data['origQty'],
"price": data.get('price'),
"type": order_type,
"raw_response": data
}
return {
"success": False,
"error": order_res.text,
"symbol": symbol,
"side": side,
"type": order_type,
"raw_response": order_res.text
}
except Exception as e:
self.logger.error(f"Binance下单异常: {e}")
return {
"success": False,
"error": str(e),
"symbol": symbol,
"side": side,
"type": order_type,
"raw_response": str(e)
}
async def place_order(
self,
symbol: str,
side: str,
order_type: str = "MARKET",
size: float = None,
price: float = None,
tif: str = "gtc",
is_close=False
) -> Dict:
"""
币安下单接口
"""
if self.ws_trade and self.ws_trade_connected:
bn_symbol = helpers.get_binance_symbol(symbol)
# 处理价格格式化 (对LIMIT订单)
formatted_price = ""
trading_pair_config = None
for pair in self.config.get("trading_pairs", []):
if pair.get("symbol") == symbol:
trading_pair_config = pair
break
if order_type == "LIMIT" and price:
# 从配置中获取价格精度和tick_size
price_precision = 2 # 默认精度
tick_size = 0.01 # 默认tick_size
if trading_pair_config:
price_precision = int(trading_pair_config.get("price_precision", 2))
tick_size = float(trading_pair_config.get("tick_size", 0.01))
# 确保价格是浮点数
price = float(price)
# 调整价格为tick_size的倍数
price = round(price / tick_size) * tick_size
# 控制小数位数,确保不超过配置的精度
price = round(price, price_precision)
# 格式化价格,确保精度符合要求
formatted_price = "{:.{}f}".format(price, price_precision)
# 去除尾部多余的0
formatted_price = formatted_price.rstrip('0').rstrip(
'.') if '.' in formatted_price else formatted_price
self.logger.info(
f"价格处理: 原始价格={price}, 格式化后={formatted_price}, 精度={price_precision}, tick_size={tick_size}")
print(
f"Binance 开仓:价格处理: 原始价格={price}, 格式化后={formatted_price}, 精度={price_precision}, tick_size={tick_size}")
params = {
"apiKey": self.ws_api_key,
"symbol": bn_symbol,
"side": side,
"type": order_type,
"quantity": str(size)
}
if order_type == "LIMIT":
params.update({
"price": str(formatted_price),
"timeInForce": tif.upper()
})
order_uuid = str(uuid.uuid4())
request = {
'id': order_uuid,
'method': 'order.place',
'params': params
}
timestamp = int(time.time() * 1000) # 以毫秒为单位的 UNIX 时间戳
request['params']['timestamp'] = timestamp
signature = self.create_ed25519_sign(request)
request['params']['signature'] = signature.decode('ASCII')
print(f'binance trade_json = {request}')
self.logger.info(f'binance trade_json = {request}')
# 新增:下单前注册Future
loop = asyncio.get_event_loop()
fut = loop.create_future()
self.ws_trade_pending_futures[order_uuid] = fut
await self.ws_trade.send(json.dumps(request))
try:
# 等待响应,超时可自定义
response_json = await asyncio.wait_for(fut, timeout=10)
except asyncio.TimeoutError:
self.ws_trade_pending_futures.pop(order_uuid, None)
return {
"success": False,
"error": "WebSocket下单超时",
"symbol": symbol,
"side": side,
"type": order_type,
"raw_response": None
}
print(f'binance ws下单结果: {response_json}')
self.logger.info(f'binance ws下单结果: {response_json}')
data = response_json['result']
if "orderId" in data:
return {
"success": True,
"order_id": data['orderId'],
"error": None,
"symbol": symbol,
"side": side,
"size": data['origQty'],
"price": data.get('price'),
"type": order_type,
"raw_response": data
}
else:
return {
"success": False,
"error": data,
"symbol": symbol,
"side": side,
"type": order_type,
"raw_response": response_json
}
else:
return await self.place_order_rest(symbol, side, order_type, size, price, tif, is_close)
async def get_order_status(self, order_id: str, symbol: str = None) -> Dict:
"""
获取订单状态
Args:
symbol: 交易对,如 "BTC"
order_id: 订单ID
Returns:
订单状态信息
"""
try:
url = f'{self.base_url}/fapi/v1/order'
params = {
'symbol': helpers.get_binance_symbol(symbol),
'orderId': order_id,
'timestamp': str(int(time.time() * 1000))
}
headers = {'X-MBX-APIKEY': self.api_key}
# 生成签名
signature = self.gen_sign_rest(params)
# 构造完整的查询字符串,包括签名
encoded_params = {k: urllib.parse.quote(str(v)) for k, v in params.items()}
query_string = '&'.join([f"{k}={v}" for k, v in sorted(encoded_params.items())])
query_string = f"{query_string}&signature={signature}"
url = f"{url}?{query_string}"
response = await self.http_client.get(url, headers=headers)
print(f'binance get_order_status response: {response.text}')
self.logger.info(f'binance get_order_status response: {response.text}')
res_json = response.json()
status_res = {
'success': False, # 请求状态
'total_size': '', # 订单总size
'price': '', # 订单价格
'left_size': '', # 订单剩余size
'status': 'unknown', # 订单状态 open/finished (转换)
'finish_status': None, # 订单结束状态(取消: cancelled, 完成:filled)
'raw_response': response.json()
}
if response.status_code == 200:
if 'orderId' in res_json:
status_res['success'] = True
total_size = res_json['origQty']
status_res['total_size'] = total_size
# execute_qty = res_json['executedQty']
execute_qty = res_json.get('executedQty', 0)
status_res['left_size'] = float(total_size) - float(execute_qty)
status_res['price'] = res_json['price']
if res_json['status'] == 'FILLED':
status_res['status'] = 'finished'
elif res_json['status'] == 'NEW':
status_res['status'] = 'open'
if float(total_size) - float(execute_qty) == 0:
status_res['finish_status'] = 'filled'
return status_res
except Exception as e:
print(e)
self.logger.error(e)
return {
'success': False, # 请求状态
'total_size': '', # 订单总size
'price': '', # 订单价格
'left_size': '', # 订单剩余size
'status': 'unknown', # 订单状态 open/finished (转换)
'finish_status': None, # 订单结束状态(取消: cancelled, 完成:filled)
'raw_response': e,
'error': e
}
async def get_position(self, symbol: str) -> Optional[Dict]:
"""
获取当前持仓
Args:
symbol: 交易对,如 "BTCUSDT"
Returns:
持仓信息,如果无持仓则返回None
"""
try:
# 构造请求参数
params = {
'symbol': helpers.get_binance_symbol(symbol),
'timestamp': str(int(time.time() * 1000))
}
# 生成签名
signature = self.gen_sign_rest(params)
# 构造完整的查询字符串,包括签名
encoded_params = {k: urllib.parse.quote(str(v)) for k, v in params.items()}
query_string = '&'.join([f"{k}={v}" for k, v in sorted(encoded_params.items())])
query_string = f"{query_string}&signature={signature}"
# 构造完整URL
url = f"{self.base_url}/fapi/v3/positionRisk?{query_string}"
# 设置请求头
headers = {'X-MBX-APIKEY': self.api_key}
self.logger.debug(f"Binance请求持仓URL: {url}")
response = await self.http_client.get(url, headers=headers)
self.logger.debug(f"Binance请求持仓响应: {response.text}")
# 检查响应状态
if response.status_code == 200:
data = response.json()
# 解析持仓数据
if isinstance(data, list):
for position in data:
position_symbol = position.get("symbol", "")
if not position_symbol or position_symbol != helpers.get_binance_symbol(symbol):
continue
position_amt = float(position.get("positionAmt", "0"))
# 跳过零持仓
if position_amt == 0:
self.logger.debug(f"跳过零持仓: {position_symbol}")
continue
# 确定持仓方向
side = "BUY" if position_amt > 0 else "SELL"
abs_size = abs(position_amt)
return {
"symbol": position_symbol,
"side": side,
"size": abs_size,
"entry_price": float(position.get("entryPrice", 0)),
"mark_price": float(position.get("markPrice", 0)),
"unrealized_pnl": float(position.get("unRealizedProfit", 0))
}
self.logger.warning(f"未找到{symbol}的持仓信息")
return None
except Exception as e:
self.logger.error(f"获取{symbol}持仓信息失败: {e}")
self.logger.debug(f"异常详情: {traceback.format_exc()}")
return None
async def close_position_rest(self, symbol: str, size: Optional[float] = None, order_type="LIMIT", price=""):
"""
平仓操作
"""
try:
bn_symbol = helpers.get_binance_symbol(symbol)
current_position = await self.get_position(symbol)
print(f'Binance平仓, 当前持仓:{symbol}, {current_position}')
if not current_position:
return {
"success": False,
"error": "No position found",
"symbol": symbol
}
trading_pair_config = None
for pair in self.config.get("trading_pairs", []):
if pair.get("symbol") == symbol:
trading_pair_config = pair
break
cur_side = current_position['side']
side = "BUY" if cur_side == "SELL" else "SELL"
# 构造请求参数
params = {
"symbol": bn_symbol,
"side": side,
"type": order_type,
"quantity": current_position.get('size'),
"reduceOnly": "true",
"timestamp": str(int(time.time() * 1000))
}
if order_type == "LIMIT":
formatted_price = price
if order_type == "LIMIT" and price:
# 从配置中获取价格精度和tick_size
price_precision = 2 # 默认精度
tick_size = 0.01 # 默认tick_size
if trading_pair_config:
price_precision = int(trading_pair_config.get("price_precision", 2))
tick_size = float(trading_pair_config.get("tick_size", 0.01))
# 确保价格是浮点数
price = float(price)
# 调整价格为tick_size的倍数
price = round(price / tick_size) * tick_size
# 控制小数位数,确保不超过配置的精度
price = round(price, price_precision)
# 格式化价格,确保精度符合要求
formatted_price = "{:.{}f}".format(price, price_precision)
# 去除尾部多余的0
formatted_price = formatted_price.rstrip('0').rstrip(
'.') if '.' in formatted_price else formatted_price
self.logger.info(
f"价格处理: 原始价格={price}, 格式化后={formatted_price}, 精度={price_precision}, tick_size={tick_size}")
print(
f"Binance 平仓:价格处理: 原始价格={price}, 格式化后={formatted_price}, 精度={price_precision}, tick_size={tick_size}")
params.update({
"timeInForce": "GTC",
"price": str(formatted_price)
})
# 生成签名
signature = self.gen_sign_rest(params)
# 构造完整的查询字符串,包括签名
encoded_params = {k: urllib.parse.quote(str(v)) for k, v in params.items()}
query_string = '&'.join([f"{k}={v}" for k, v in sorted(encoded_params.items())])
query_string = f"{query_string}&signature={signature}"
# 构造完整URL
url = f"{self.base_url}/fapi/v1/order?{query_string}"
# 设置请求头
headers = {'X-MBX-APIKEY': self.api_key}
self.logger.debug(f"Binance平仓URL: {url}")
print(f"Binance平仓param: {params}")
print(f"Binance平仓URL: {url}")
response = await self.http_client.post(url, headers=headers)
self.logger.debug(f"Binance平仓响应: {response.text}")
print(f"Binance平仓响应: {response.text}")
if response.status_code == 200:
data = response.json()
if "orderId" in data:
return {
"success": True,
"order_id": data['orderId'],
"error": None,
"symbol": symbol,
"side": side,
"size": data['origQty'],
"price": data.get('price'),
"type": order_type,
"raw_response": data
}
return {
"success": False,
"error": response.text,
"symbol": symbol,
"side": side,
"type": order_type,
"raw_response": response.text
}
except Exception as e:
self.logger.error(f"Binance平仓异常: {e}")
print(f"Binance平仓异常: {e}")
return {
"success": False,
"error": str(e),
"symbol": symbol,
"type": order_type,
"raw_response": str(e)
}
async def close_position(self, symbol: str, size: Optional[float] = None, order_type="LIMIT", price="",
side: str = None) -> Dict:
if self.ws_trade and self.ws_trade_connected:
"""
平仓操作
side :持仓方向 (是当前的持仓方向 long 为BUY, short 为 SELL)
"""
bn_symbol = helpers.get_binance_symbol(symbol)
print(f'Binance平仓, 当前持仓:{symbol}: {size}, 持仓方向: {side}')
self.logger.info(f'Binance平仓, 当前持仓:{symbol}: {size}, 持仓方向: {side}')
trading_pair_config = None
for pair in self.config.get("trading_pairs", []):
if pair.get("symbol") == symbol:
trading_pair_config = pair
break
cur_side = side
side = "BUY" if cur_side == "SELL" else "SELL"
# 构造请求参数
params = {
"apiKey": self.ws_api_key,
"symbol": bn_symbol,
"side": side,
"quantity": size,
"type": order_type,
"reduceOnly": "true",
}
if order_type == "LIMIT":
formatted_price = price
if order_type == "LIMIT" and price:
# 从配置中获取价格精度和tick_size
price_precision = 2 # 默认精度
tick_size = 0.01 # 默认tick_size
if trading_pair_config:
price_precision = int(trading_pair_config.get("price_precision", 2))
tick_size = float(trading_pair_config.get("tick_size", 0.01))
# 确保价格是浮点数
price = float(price)
# 调整价格为tick_size的倍数
price = round(price / tick_size) * tick_size
# 控制小数位数,确保不超过配置的精度
price = round(price, price_precision)
# 格式化价格,确保精度符合要求
formatted_price = "{:.{}f}".format(price, price_precision)
# 去除尾部多余的0
formatted_price = formatted_price.rstrip('0').rstrip(
'.') if '.' in formatted_price else formatted_price
self.logger.info(
f"价格处理: 原始价格={price}, 格式化后={formatted_price}, 精度={price_precision}, tick_size={tick_size}")
print(
f"Binance 平仓:价格处理: 原始价格={price}, 格式化后={formatted_price}, 精度={price_precision}, tick_size={tick_size}")
params.update({
"timeInForce": "GTC",
"price": str(formatted_price)
})
order_uuid = str(uuid.uuid4())
request = {
'id': order_uuid,
'method': 'order.place',
'params': params
}
# === 新增:加上timestamp和signature ===
timestamp = int(time.time() * 1000) # 以毫秒为单位的 UNIX 时间戳
request['params']['timestamp'] = timestamp
signature = self.create_ed25519_sign(request)
request['params']['signature'] = signature.decode('ASCII')
print(f'binance trade_json = {request}')
self.logger.info(f'binance trade_json = {request}')
# === 新增:Future机制 ===
loop = asyncio.get_event_loop()
fut = loop.create_future()
self.ws_trade_pending_futures[order_uuid] = fut
await self.ws_trade.send(json.dumps(request))
try:
response_json = await asyncio.wait_for(fut, timeout=10)
except asyncio.TimeoutError:
self.ws_trade_pending_futures.pop(order_uuid, None)
return {
"success": False,
"error": "WebSocket平仓超时",
"symbol": symbol,
"side": side,
"type": order_type,
"raw_response": None
}
print(f'binance ws下单结果: {response_json}')
self.logger.info(f'binance ws下单结果: {response_json}')
data = response_json['result']
if "orderId" in data:
return {
"success": True,
"order_id": data['orderId'],
"error": None,
"symbol": symbol,
"side": side,
"size": data['origQty'],
"price": data.get('price'),
"type": order_type,
"raw_response": data
}
else:
return {
"success": False,
"error": data,
"symbol": symbol,
"side": side,
"type": order_type,
"raw_response": response_json
}
else:
return await self.close_position_rest(symbol, size, order_type, price)
async def start_ws_price_stream(self):
"""
启动WebSocket价格数据流
"""
if self.ws_task:
return
self.ws_task = asyncio.create_task(self._ws_price_listener())
self.ws_trade_task = asyncio.create_task(self._ws_trade_task())
async def _ws_price_listener(self):
"""
WebSocket价格数据监听器
"""
while True:
try:
async with websockets.connect(self.ws_url) as ws:
self.ws = ws
self.ws_connected = True
self.logger.info("Binance WebSocket已连接")
# 获取永续合约交易对列表
symbols = await self._get_perp_symbols()
# 构建订阅参数
subscribe_params = []
for symbol in symbols:
# 订阅标记价格流
# subscribe_params.append(f"{symbol}@markPrice")
# subscribe_params.append(f"{symbol}@ticker")
# print(s)
subscribe_params.append(f"{symbol}@depth5@100ms")
subscribe_msg = {
"method": "SUBSCRIBE",
"params": subscribe_params,
"id": 1
}
# 发送订阅请求
await ws.send(json.dumps(subscribe_msg))
self.logger.info(f"已向Binance发送订阅请求,共 {len(symbols)} 个交易对")
for symbol in symbols:
# 订阅标记价格流
subscribe_params.append(f"{symbol}@markPrice")
# subscribe_params.append(f"{symbol}@ticker")
subscribe_msg = {
"method": "SUBSCRIBE",
"params": subscribe_params,
"id": 1
}
await ws.send(json.dumps(subscribe_msg))
# 接收和处理消息
while True:
message = await ws.recv()
data_json = json.loads(message)
# 处理确认消息
if "result" in data_json and data_json.get("result") == "success":
self.logger.info("Binance订阅成功")
continue
# 处理标记价格更新
if "stream" in data_json and "@markPrice" in data_json["stream"]:
stream_data = data_json.get("data", {})
symbol = stream_data.get("s", "")
base_symbol = symbol.split("USDT")[0] if "USDT" in symbol else symbol
current_time = time.time()
if symbol and "p" in stream_data:
try:
mark_price = float(stream_data["p"])
self.prices[symbol] = mark_price
if base_symbol not in self.coin_data:
self.coin_data[base_symbol] = {
"symbol": symbol,
"funding_rate": None,
"funding_rate_timestamp": None,
"price": None,
"price_timestamp": None
}
except (ValueError, TypeError) as e:
self.logger.error(
f"无法将Binance标记价格转换为浮点数: {stream_data['p']}, 错误: {e}")
# 处理资金费率数据
if 'r' in stream_data:
try:
funding_rate = float(stream_data['r'])
self.funding_rates[symbol] = funding_rate
if base_symbol in self.coin_data:
self.coin_data[base_symbol]["funding_rate"] = funding_rate
self.coin_data[base_symbol]["funding_rate_timestamp"] = current_time
if hasattr(self, "data_manager") and self.data_manager:
self.data_manager.update_funding_rate(base_symbol, 'binance', funding_rate,
current_time)
else:
self.coin_data[base_symbol] = {
"symbol": symbol,
"funding_rate": funding_rate,
"funding_rate_timestamp": current_time,
"price": None,
"price_timestamp": None
}
except (ValueError, TypeError) as e:
self.logger.error(
f"无法将Binance资金费率转换为浮点数: {stream_data['r']}, 错误: {e}")
now = time.time()
if now - self.last_price_log.get(base_symbol, 0) > self.price_log_interval:
self.logger.debug(
f"Binance价格更新: {base_symbol} = {stream_data.get('p', 'N/A')}, 资金费率 = {stream_data.get('r', 'N/A')}")
self.last_price_log[base_symbol] = now
if "stream" in data_json and "@depth" in data_json["stream"]:
stream_data = data_json.get("data", {})
symbol = stream_data.get("s", "")
base_symbol = symbol.split("USDT")[0] if "USDT" in symbol else symbol
bids = stream_data.get("b", [])
asks = stream_data.get("a", [])
if len(asks) > 0:
ask1_price = asks[0][0]
ask1_size = asks[0][1]
else:
ask1_price = None