Repository navigation
Expand file tree
/
Copy pathexchange_execution.py
More file actions
1622 lines (1366 loc) · 60 KB
/
Copy pathexchange_execution.py
File metadata and controls
1622 lines (1366 loc) · 60 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
# exchange_execution.py
from enum import Enum
import os
import asyncio
import json
import math
import time
import logging
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from decimal import Decimal, ROUND_DOWN
from typing import Dict, Any, List, Optional, Tuple, Union
from dataclasses import dataclass, field, asdict
import ccxt
import aiohttp
from urllib.parse import urljoin
from models import (
TradingSignal,
OrderResult,
EntryZone,
TakeProfitLevel
)
# Constants
class OrderSide:
BUY = 'buy'
SELL = 'sell'
class OrderType:
MARKET = 'MARKET'
LIMIT = 'LIMIT'
STOP = 'STOP'
STOP_MARKET = 'STOP_MARKET'
TAKE_PROFIT = 'TAKE_PROFIT'
TAKE_PROFIT_MARKET = 'TAKE_PROFIT_MARKET'
class OrderStatus:
PENDING = 'PENDING'
OPEN = 'OPEN'
CLOSED = 'CLOSED'
CANCELED = 'CANCELED'
EXPIRED = 'EXPIRED'
REJECTED = 'REJECTED'
class PositionSide(str, Enum):
"""Position side enum"""
LONG = 'long'
SHORT = 'short'
class MarginType(str, Enum):
"""Margin type enum"""
CROSS = 'cross'
ISOLATED = 'isolated'
@dataclass
class ExchangeCredentials:
"""Exchange credentials configuration"""
api_key: str
api_secret: str
passphrase: Optional[str] = None
test_api_key: Optional[str] = None
test_api_secret: Optional[str] = None
test_passphrase: Optional[str] = None
testnet: bool = False
# 或者如果你希望保持完全一致的话,可以这样定义:
@dataclass
class OrderParams:
"""Order parameters (Legacy class for backwards compatibility)"""
symbol: str
side: str
order_type: str
amount: float
price: Optional[float] = None
stop_price: Optional[float] = None
reduce_only: bool = False
leverage: Optional[int] = None
margin_mode: str = MarginType.CROSS
extra_params: Dict[str, Any] = field(default_factory=dict)
def validate(self) -> bool:
"""Validate order parameters"""
try:
if not all([self.symbol, self.side, self.order_type, self.amount > 0]):
return False
if self.order_type == OrderType.LIMIT and not self.price:
return False
if self.order_type in [OrderType.STOP, OrderType.TAKE_PROFIT] and not self.stop_price:
return False
return True
except Exception:
return False
@dataclass
class OrderInfo:
"""Order information"""
id: str
symbol: str
side: str
type: str
price: Optional[float]
amount: float
filled: float = 0
remaining: float = 0
status: str = OrderStatus.PENDING
fee: Dict[str, Any] = field(default_factory=dict)
timestamp: datetime = field(default_factory=datetime.now)
@staticmethod
def from_exchange_order(order: Dict[str, Any]) -> Optional['OrderInfo']:
"""Create OrderInfo from exchange order data"""
try:
return OrderInfo(
id=order['id'],
symbol=order['symbol'],
side=order['side'],
type=order['type'],
price=float(order['price']) if order.get('price') else None,
amount=float(order['amount']),
filled=float(order.get('filled', 0)),
remaining=float(order.get('remaining', order['amount'])),
status=order['status'],
fee=order.get('fee', {}),
timestamp=datetime.fromtimestamp(order['timestamp']/1000)
)
except Exception as e:
logging.error(f"Error creating OrderInfo: {e}")
return None
# 首先修复数据模型
@dataclass
class AccountBalance:
"""Account balance information"""
total_equity: float = 0.0 # 总权益
used_margin: float = 0.0 # 已用保证金
free_margin: float = 0.0 # 可用保证金
margin_ratio: float = 0.0 # 保证金率
unrealized_pnl: float = 0.0 # 未实现盈亏
realized_pnl: float = 0.0 # 已实现盈亏
timestamp: datetime = field(default_factory=datetime.now)
@property
def total(self) -> float:
return self.total_equity
@property
def used(self) -> float:
return self.used_margin
@property
def free(self) -> float:
return self.free_margin
@staticmethod
def from_exchange_balance(balance: Dict[str, Any]) -> 'AccountBalance':
"""Create AccountBalance from exchange balance data"""
try:
total = float(balance.get('total', {}).get('USDT', 0) or 0)
used = float(balance.get('used', {}).get('USDT', 0) or 0)
free = float(balance.get('free', {}).get('USDT', 0) or 0)
return AccountBalance(
total_equity=total,
used_margin=used,
free_margin=free,
margin_ratio=(used / total * 100) if total > 0 else 0,
unrealized_pnl=float(balance.get('unrealizedPnl', 0) or 0),
realized_pnl=float(balance.get('realizedPnl', 0) or 0)
)
except Exception as e:
logging.error(f"Error creating AccountBalance: {e}")
return AccountBalance()
@dataclass
class PositionInfo:
"""Position information"""
# 基础信息
symbol: str
side: PositionSide
size: float
entry_price: float
margin_mode: MarginType
leverage: int
# 价格相关
liquidation_price: Optional[float] = None
mark_price: Optional[float] = 0
break_even_price: Optional[float] = None
# 保证金相关
initial_margin: float = 0
maintenance_margin: float = 0
position_initial_margin: float = 0 # 持仓保证金
open_order_initial_margin: float = 0 # 委托单保证金
isolated_margin: float = 0 # 逐仓保证金
# 盈亏相关
unrealized_pnl: float = 0
realized_pnl: float = 0
pnl_percentage: float = 0
# 其他
notional: float = 0 # 名义价值
collateral: float = 0 # 可用保证金
timestamp: datetime = field(default_factory=datetime.now)
def get(self, key: str, default: Any = None) -> Any:
"""Support dict-like get method for compatibility"""
return getattr(self, key, default)
@staticmethod
def from_exchange_position(pos: Dict[str, Any]) -> Optional['PositionInfo']:
"""Create PositionInfo from exchange position data"""
try:
logging.info(f"ExchangeInfo -- {pos}")
# 处理空仓位情况
position_amt = float(pos.get('contracts', 0) or pos.get('positionAmt', 0) or 0)
if position_amt == 0:
return None
# 判断多空方向
side = PositionSide.LONG if (
pos.get('side') == 'long'
) else PositionSide.SHORT
# 判断杠杆模式
margin_mode = MarginType.ISOLATED if pos.get('marginMode') == 'isolated' else MarginType.CROSS
return PositionInfo(
# 基础信息
symbol=pos['symbol'],
side=side,
size=abs(position_amt),
entry_price=float(pos.get('entryPrice', 0) or 0),
margin_mode=margin_mode,
leverage=int(float(pos.get('leverage', 1) or 1)),
# 价格相关
liquidation_price=float(pos.get('liquidationPrice', 0) or 0),
mark_price=float(pos.get('markPrice', 0) or 0),
break_even_price=float(pos.get('breakEvenPrice', 0) or 0),
# 保证金相关
initial_margin=float(pos.get('initialMargin', 0) or 0),
maintenance_margin=float(pos.get('maintenanceMargin', 0) or 0),
position_initial_margin=float(pos.get('positionInitialMargin', 0) or 0),
open_order_initial_margin=float(pos.get('openOrderInitialMargin', 0) or 0),
isolated_margin=float(pos.get('isolatedMargin', 0) or 0),
# 盈亏相关
unrealized_pnl=float(pos.get('unrealizedPnl', 0) or pos.get('unRealizedProfit', 0) or 0),
realized_pnl=float(pos.get('realizedPnl', 0) or 0),
pnl_percentage=float(pos.get('percentage', 0) or 0),
# 其他
notional=float(pos.get('notional', 0) or 0),
collateral=float(pos.get('collateral', 0) or 0)
)
except Exception as e:
logging.error(f"Error creating PositionInfo: {e}")
return None
def is_long(self) -> bool:
"""Check if position is long"""
return self.side == PositionSide.LONG
def is_short(self) -> bool:
"""Check if position is short"""
return self.side == PositionSide.SHORT
def is_isolated(self) -> bool:
"""Check if position is isolated margin"""
return self.margin_mode == MarginType.ISOLATED
def is_cross(self) -> bool:
"""Check if position is cross margin"""
return self.margin_mode == MarginType.CROSS
@dataclass
class MarketInfo:
"""Market information"""
symbol: str
base: str
quote: str
price_precision: int
amount_precision: int
min_amount: float
min_cost: float
market_type: str
contract_size: float = 1.0
last_price: Optional[float] = None
mark_price: Optional[float] = None
index_price: Optional[float] = None
timestamp: datetime = field(default_factory=datetime.now)
@staticmethod
def from_exchange_market(market: Dict[str, Any], ticker: Optional[Dict[str, Any]] = None) -> Optional['MarketInfo']:
"""Create MarketInfo from exchange market data"""
try:
def safe_float(value: Any, default: float = 0.0) -> float:
if value is None:
return default
try:
return float(value)
except (TypeError, ValueError):
return default
precision = market.get('precision', {})
limits = market.get('limits', {})
return MarketInfo(
symbol=market['symbol'],
base=market.get('base', ''),
quote=market.get('quote', ''),
price_precision=int(precision.get('price', 8)),
amount_precision=int(precision.get('amount', 8)),
min_amount=safe_float(limits.get('amount', {}).get('min')),
min_cost=safe_float(limits.get('cost', {}).get('min')),
market_type=market.get('type', 'spot'),
contract_size=safe_float(market.get('contractSize'), 1.0),
last_price=safe_float(ticker.get('last')) if ticker else None,
mark_price=safe_float(ticker.get('mark')) if ticker else None,
index_price=safe_float(ticker.get('index')) if ticker else None
)
except Exception as e:
logging.error(f"Error creating MarketInfo: {e}")
return None
class ExchangeException(Exception):
"""Base exchange exception"""
pass
class OrderException(ExchangeException):
"""Order related exception"""
pass
class PositionException(ExchangeException):
"""Position related exception"""
pass
class MarketException(ExchangeException):
"""Market data related exception"""
pass
class NetworkException(ExchangeException):
"""Network related exception"""
pass
class ExchangeClient(ABC):
"""Base exchange client implementation"""
def __init__(self, credentials: ExchangeCredentials):
self.credentials = credentials
self._exchange = None
self._last_request_time = 0
self.min_request_interval = 0.1
self._session: Optional[aiohttp.ClientSession] = None
# Cache
self._market_cache: Dict[str, MarketInfo] = {}
self._market_cache_time: Dict[str, float] = {}
self._balance_cache: Optional[AccountBalance] = None
self._balance_cache_time: float = 0
self._position_cache: Dict[str, PositionInfo] = {}
self._position_cache_time: Dict[str, float] = {}
self.CACHE_DURATION = 5 # seconds
async def initialize(self) -> bool:
"""Initialize exchange client"""
try:
# Setup exchange
if not await self._setup_exchange():
return False
# Load markets
await self._load_markets()
# Initialize session
if not self._session:
self._session = aiohttp.ClientSession()
return True
except Exception as e:
logging.error(f"Error initializing exchange client: {e}")
return False
async def cleanup(self):
"""Cleanup resources"""
try:
if self._session:
await self._session.close()
self._session = None
self._exchange = None
except Exception as e:
logging.error(f"Error cleaning up exchange client: {e}")
def _rate_limit(self):
"""Apply rate limiting"""
current_time = time.time()
time_since_last = current_time - self._last_request_time
if time_since_last < self.min_request_interval:
time.sleep(self.min_request_interval - time_since_last)
self._last_request_time = time.time()
@abstractmethod
async def _setup_exchange(self) -> bool:
"""Setup exchange connection"""
pass
async def _load_markets(self) -> None:
"""Load market data"""
try:
if not self._exchange:
raise ValueError("Exchange not initialized")
self._rate_limit()
markets = await asyncio.to_thread(self._exchange.load_markets)
# Cache market info
for symbol, market in markets.items():
market_info = MarketInfo.from_exchange_market(market)
if market_info:
self._market_cache[symbol] = market_info
self._market_cache_time[symbol] = time.time()
logging.info(f"Loaded {len(self._market_cache)} markets")
except Exception as e:
logging.error(f"Error loading markets: {e}")
raise
@staticmethod
def _safe_float(value: Any, default: float = 0.0) -> float:
"""Safely convert value to float"""
if value is None:
return default
try:
return float(value)
except (TypeError, ValueError):
return default
async def fetch_positions(self, symbol: Optional[str] = None) -> List[PositionInfo]:
"""Fetch positions"""
try:
self._rate_limit()
positions = await asyncio.to_thread(
self._exchange.fetchPositions,
[symbol] if symbol else None
)
result = []
for pos in positions:
position_info = PositionInfo.from_exchange_position(pos)
if position_info:
result.append(position_info)
return result
except Exception as e:
logging.error(f"Error fetching positions: {e}")
return []
async def fetch_balance(self) -> AccountBalance:
"""Fetch balance"""
try:
self._rate_limit()
balance = await asyncio.to_thread(self._exchange.fetchBalance)
return AccountBalance.from_exchange_balance(balance)
except Exception as e:
logging.error(f"Error fetching balance: {e}")
return AccountBalance()
async def get_market_info(self, symbol: str) -> Optional[MarketInfo]:
"""Get market information"""
try:
now = time.time()
if symbol in self._market_cache:
if now - self._market_cache_time.get(symbol, 0) < self.CACHE_DURATION:
return self._market_cache[symbol]
self._rate_limit()
market = await asyncio.to_thread(self._exchange.market, symbol)
ticker = await asyncio.to_thread(self._exchange.fetchTicker, symbol)
market_info = MarketInfo.from_exchange_market(market, ticker)
if market_info:
self._market_cache[symbol] = market_info
self._market_cache_time[symbol] = now
return market_info
except Exception as e:
logging.error(f"Error getting market info: {e}")
return None
async def get_balance(self) -> AccountBalance:
"""Get account balance"""
try:
# Check cache
now = time.time()
if self._balance_cache and now - self._balance_cache_time < self.CACHE_DURATION:
return self._balance_cache
# Fetch from exchange
self._rate_limit()
balance = await asyncio.to_thread(self._exchange.fetchBalance)
balance_info = AccountBalance.from_exchange_balance(balance)
self._balance_cache = balance_info
self._balance_cache_time = now
return balance_info
except Exception as e:
logging.error(f"Error getting balance: {e}")
return AccountBalance()
async def get_positions(self, symbol: Optional[str] = None) -> List[PositionInfo]:
"""Get positions"""
try:
# Check cache
now = time.time()
cache_key = symbol or 'all'
if cache_key in self._position_cache:
if now - self._position_cache_time.get(cache_key, 0) < self.CACHE_DURATION:
return [self._position_cache[cache_key]]
# Fetch from exchange
self._rate_limit()
positions = await asyncio.to_thread(
self._exchange.fetchPositions,
[symbol] if symbol else None
)
result = []
for pos in positions:
if float(pos.get('contracts', 0)) != 0: # Only include non-zero positions
position_info = PositionInfo.from_exchange_position(pos)
if position_info:
result.append(position_info)
self._position_cache[position_info.symbol] = position_info
self._position_cache_time[position_info.symbol] = now
if not symbol: # Cache all positions
self._position_cache['all'] = result
self._position_cache_time['all'] = now
return result
except Exception as e:
logging.error(f"Error getting positions: {e}")
return []
async def cancel_order(self, order_id: str, symbol: str) -> bool:
"""Cancel order"""
try:
self._rate_limit()
result = await asyncio.to_thread(
self._exchange.cancelOrder,
order_id,
symbol
)
return bool(result)
except Exception as e:
logging.error(f"Error canceling order: {e}")
return False
async def get_order(self, order_id: str, symbol: str) -> Optional[OrderInfo]:
"""Get order information"""
try:
self._rate_limit()
order = await asyncio.to_thread(
self._exchange.fetchOrder,
order_id,
symbol
)
return OrderInfo.from_exchange_order(order) if order else None
except Exception as e:
logging.error(f"Error getting order: {e}")
return None
async def get_funding_rate(self, symbol: str) -> Optional[float]:
"""Get funding rate"""
try:
self._rate_limit()
funding = await asyncio.to_thread(
self._exchange.fetchFundingRate,
symbol
)
return float(funding['fundingRate']) if funding else None
except Exception as e:
logging.error(f"Error getting funding rate: {e}")
return None
async def get_mark_price_history(self, symbol: str, timeframe: str = '1m',
limit: int = 100) -> List[Dict[str, Any]]:
"""Get mark price history"""
try:
self._rate_limit()
ohlcv = await asyncio.to_thread(
self._exchange.fetchOHLCV,
symbol,
timeframe,
limit=limit,
params={'price': 'mark'}
)
return [
{
'timestamp': datetime.fromtimestamp(candle[0]/1000),
'open': float(candle[1]),
'high': float(candle[2]),
'low': float(candle[3]),
'close': float(candle[4]),
'volume': float(candle[5])
}
for candle in ohlcv
]
except Exception as e:
logging.error(f"Error getting mark price history: {e}")
return []
async def get_market_leverage_info(self, symbol: str) -> Dict[str, Any]:
"""Get market leverage settings"""
try:
# Get market leverage info from exchange
leverage_info = await asyncio.to_thread(
self._exchange.fetchMarketLeverageTiers, # 注意这里是fetchMarketLeverageTiers
symbol # 不需要放在列表里
)
if leverage_info and isinstance(leverage_info, list):
# 通常第一个tier是最大杠杆
max_leverage = int(leverage_info[0].get('maxLeverage', 1))
return {
'max_leverage': max_leverage,
'tiers': leverage_info
}
return {'max_leverage': 1, 'tiers': []}
except Exception as e:
logging.error(f"Error getting leverage info: {e}")
return {'max_leverage': 1, 'tiers': []}
async def set_leverage(self, symbol: str, leverage: int, margin_mode: str) -> bool:
"""Set leverage with validation"""
try:
# Get max allowed leverage
leverage_info = await self.get_market_leverage_info(symbol)
max_leverage = leverage_info['max_leverage']
# Adjust leverage if it exceeds maximum
actual_leverage = min(leverage, max_leverage)
# Set margin mode first
await asyncio.to_thread(
self._exchange.setMarginMode,
margin_mode,
symbol
)
# Then set leverage
await asyncio.to_thread(
self._exchange.setLeverage,
actual_leverage,
symbol
)
logging.info(f"Set {margin_mode} leverage for {symbol}: requested={leverage}, actual={actual_leverage}")
return actual_leverage
except Exception as e:
logging.error(f"Error setting leverage: {e}")
raise # 这种关键操作最好抛出异常而不是返回False
async def convert_amount_to_contracts(
self,
symbol: str,
usdt_amount: float,
price: float,
leverage: int
) -> Tuple[float, Dict[str, Any]]:
"""Convert USDT amount to contracts quantity with leverage"""
try:
market_info = await self.get_market_info(symbol)
if not market_info:
raise ValueError(f"Cannot get market info for {symbol}")
# Get max allowed leverage and adjust if needed
leverage_info = await self.get_market_leverage_info(symbol)
actual_leverage = min(leverage, leverage_info['max_leverage'])
# Calculate quantity with leverage
# 实际可买币数 = (USDT金额 * 杠杆) / 价格
notional_value = usdt_amount * actual_leverage # 名义价值
quantity = notional_value / price # 可买币数
# 应用精度要求
formatted_quantity = self._format_amount(symbol, quantity)
# 实际使用的保证金
actual_value = (formatted_quantity * price) / actual_leverage
logging.info(f"""
Amount Conversion Details:
USDT Amount: {usdt_amount}
Price: {price}
Leverage: {actual_leverage}x (max: {leverage_info['max_leverage']}x)
Raw Quantity: {quantity} (币数量)
Formatted Quantity: {formatted_quantity} (根据精度调整后的币数量)
Actual Margin: {actual_value} USDT (实际使用保证金)
Notional Value: {formatted_quantity * price} USDT (名义价值)
Min Amount: {market_info.min_amount if market_info else 'Unknown'}
Amount Precision: {market_info.amount_precision if market_info else 'Unknown'}
""")
return formatted_quantity, {
'raw_quantity': quantity,
'formatted_quantity': formatted_quantity,
'initial_margin': actual_value, # 实际使用的保证金
'notional_value': formatted_quantity * price, # 名义价值
'price': price,
'leverage': actual_leverage
}
except Exception as e:
logging.error(f"Error converting amount to contracts: {e}")
raise
async def create_order(self, order: OrderParams) -> OrderResult:
"""Create order with proper price and leverage handling"""
try:
if not order.validate():
raise OrderException("Invalid order parameters")
# Get market info and current price
market_info = await self.get_market_info(order.symbol)
if not market_info or not market_info.last_price:
raise ValueError(f"Cannot get market info for {order.symbol}")
# 确定使用价格
use_price = order.price if (order.order_type == OrderType.LIMIT and order.price) else market_info.last_price
# 设置杠杆和保证金模式
leverage = order.leverage or 50 # 默认50倍杠杆
actual_leverage = await self.set_leverage(order.symbol, leverage, order.margin_mode)
# 转换USDT金额到币数量
quantity, conversion_info = await self.convert_amount_to_contracts(
order.symbol,
order.amount, # USDT amount
use_price,
actual_leverage # 使用实际设置的杠杆
)
# 创建订单参数
params = {
'symbol': order.symbol,
'type': order.order_type.lower(),
'side': order.side.lower(),
'amount': quantity, # 币的数量(已包含杠杆)
}
if order.order_type == OrderType.LIMIT:
if not order.price:
raise OrderException("Price is required for limit orders")
params['price'] = self._format_price(order.symbol, order.price)
if order.stop_price:
params['stopPrice'] = self._format_price(order.symbol, order.stop_price)
if order.reduce_only:
params['reduceOnly'] = True
params.update(order.extra_params)
logging.info(f"""
Creating order:
Symbol: {order.symbol}
USDT Amount Intended: {order.amount}
Leverage: {conversion_info['leverage']}x
Coin Quantity: {quantity}
Type: {params['type']}
Side: {params['side']}
Price: {params.get('price')}
Stop Price: {params.get('stopPrice')}
Margin Mode: {order.margin_mode}
Initial Margin: {conversion_info['initial_margin']} USDT
Notional Value: {conversion_info['notional_value']} USDT
""")
# Execute order
result = await asyncio.to_thread(
self._exchange.createOrder,
**params
)
return OrderResult(
success=True,
order_id=result['id'],
executed_price=float(result.get('price', 0) or use_price),
executed_amount=quantity,
extra_info={
'raw_response': result,
'conversion_info': conversion_info
}
)
except Exception as e:
logging.error(f"Error creating order: {e}")
raise # 关键操作直接抛出异常
def _format_price(self, symbol: str, price: float) -> float:
"""Format price according to symbol precision"""
try:
#TODO - market price
# market_info = self._market_cache.get(symbol)
# if market_info:
# precision = market_info.price_precision
# logging.info(f"format_price----price_precision---{market_info.price_precision}--{float(format(price, f'.{precision}f'))}---original--price{price}")
# return float(format(price, f'.{precision}f'))
logging.info(f"format_priceoriginal--price{price}")
return price
except Exception as e:
logging.error(f"Error formatting price: {e}")
return price
def _format_amount(self, symbol: str, amount: float) -> float:
"""Format amount according to symbol precision"""
try:
market_info = self._market_cache.get(symbol)
if market_info:
precision = market_info.amount_precision
return float(format(amount, f'.{precision}f'))
return amount
except Exception as e:
logging.error(f"Error formatting amount: {e}")
return amount
class BinanceClient(ExchangeClient):
"""Binance exchange client implementation"""
def __init__(self, credentials: ExchangeCredentials):
super().__init__(credentials)
self.min_request_interval = 0.05
self.exchange_name = 'BINANCE'
async def _setup_exchange(self) -> bool:
"""Setup Binance exchange connection"""
try:
logging.info(f"Setting up Binance with testnet={self.credentials.testnet}")
config = {
'apiKey': self.credentials.api_key,
'secret': self.credentials.api_secret,
'enableRateLimit': True,
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True,
'recvWindow': 60000,
'warnOnFetchOHLCVLimitArgument': False,
'createMarketBuyOrderRequiresPrice': False
}
}
if self.credentials.testnet:
config['urls'] = {
'api': {
'public': 'https://testnet.binancefuture.com/fapi/v1',
'private': 'https://testnet.binancefuture.com/fapi/v1',
}
}
config['options']['defaultType'] = 'future'
config['options']['testnet'] = True
self._exchange = ccxt.binance(config)
# Test connection
logging.info("Testing Binance connection...")
await asyncio.to_thread(self._exchange.fetch_balance)
logging.info("Binance connection test successful")
# Load markets
logging.info("Loading Binance markets...")
await self._load_markets()
logging.info("Binance markets loaded successfully")
return True
except Exception as e:
logging.error(f"Error setting up Binance exchange: {e}")
import traceback
logging.error(f"Traceback:\n{traceback.format_exc()}")
return False
async def get_leverage_brackets(self, symbol: str) -> List[Dict[str, Any]]:
"""Get leverage brackets"""
try:
self._rate_limit()
response = await asyncio.to_thread(
self._exchange.fapiPrivateGetLeverageBracket,
{'symbol': symbol}
)
if response and isinstance(response, list):
return [
{
'bracket': bracket['bracket'],
'initialLeverage': bracket['initialLeverage'],
'notionalCap': bracket['notionalCap'],
'notionalFloor': bracket['notionalFloor'],
'maintMarginRatio': bracket['maintMarginRatio']
}
for bracket in response[0]['brackets']
]
return []
except Exception as e:
logging.error(f"Error getting leverage brackets: {e}")
return []
async def transfer_margin(self, symbol: str, amount: float, type: str) -> bool:
"""Transfer margin"""
try:
self._rate_limit()
await asyncio.to_thread(
self._exchange.fapiPrivatePostPositionMargin,
{
'symbol': symbol,
'amount': amount,
'type': type # 1: Add, 2: Reduce
}
)
return True
except Exception as e:
logging.error(f"Error transferring margin: {e}")
return False
class OKXClient(ExchangeClient):
"""OKX exchange client implementation"""
def __init__(self, credentials: ExchangeCredentials):
super().__init__(credentials)
self.min_request_interval = 0.02
self.exchange_name = 'OKX'
async def _setup_exchange(self) -> bool:
"""Setup OKX exchange connection"""
try:
logging.info(f"Setting up OKX with testnet={self.credentials.testnet}")
config = {
'apiKey': self.credentials.api_key,
'secret': self.credentials.api_secret,
'password': self.credentials.passphrase,
'enableRateLimit': True,
'options': {
'defaultType': 'swap',
'adjustForTimeDifference': True
}
}
if self.credentials.testnet:
config['hostname'] = 'okx.com' # Use main domain for testnet
config['options']['testnet'] = True
self._exchange = ccxt.okx(config)
# Test connection
logging.info("Testing OKX connection...")
await asyncio.to_thread(self._exchange.fetch_balance)
logging.info("OKX connection test successful")
# Load markets
logging.info("Loading OKX markets...")
await self._load_markets()
logging.info("OKX markets loaded successfully")
return True
except Exception as e:
logging.error(f"Error setting up OKX exchange: {e}")
import traceback
logging.error(f"Traceback:\n{traceback.format_exc()}")
return False