Repository navigation
Expand file tree
/
Copy pathlive_binance_quant.py
More file actions
1692 lines (1517 loc) · 66.7 KB
/
Copy pathlive_binance_quant.py
File metadata and controls
1692 lines (1517 loc) · 66.7 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
"""
Binance USD-M Futures 实盘/模拟盘交易脚本(永续合约)。
基于混合费率执行策略,每 5 分钟获取信号并自动下单。
混合费率执行策略:
- 开仓: POST_ONLY (Maker) -- 挂限价单,享Maker低费率
- 止盈: POST_ONLY (Maker) -- 自动挂止盈限价单,价格到达即成交
- 止损: IOC (Taker) -- 必须保证成交,付Taker费率
- 超时: POST_ONLY (Maker) -- 挂限价单平仓
Usage:
# 模拟盘 / Testnet(推荐先用这个测试)
export BINANCE_API_KEY="your_api_key"
export BINANCE_API_SECRET="your_api_secret"
uv run python live_binance_quant.py --symbol BTCUSDT --interval 5m --demo --capital 100
# 实盘交易(真钱!确认策略稳定后再用)
export BINANCE_API_KEY="your_api_key"
export BINANCE_API_SECRET="your_api_secret"
uv run python live_binance_quant.py --symbol BTCUSDT --interval 5m --live --capital 500 --leverage 2
注意:
- 默认需要 --demo 或 --live 明确指定
- 切换到实盘前,务必先用 Demo/Testnet 跑至少 1-2 天验证信号和下单逻辑
- 本脚本交易 Binance USD-M 永续合约,支持做多/做空双向
"""
import os
import sys
import time
import json
import math
import argparse
import functools
from datetime import datetime, timedelta
from decimal import Decimal
from dotenv import load_dotenv
load_dotenv()
import pandas as pd
import torch
import ccxt
from train_quant import (
TrendStrategy,
ScalpStrategy,
HybridMeanRevMomentumStrategy,
AdaptiveHybridStrategy,
RegimeStrategy,
)
LOG_DIR = "logs"
os.makedirs(LOG_DIR, exist_ok=True)
STATE_FILE = os.path.join(LOG_DIR, "live_binance_state.json")
LOG_FILE = os.path.join(LOG_DIR, "live_binance_log.txt")
LOCK_FILE = os.path.join(LOG_DIR, "live_binance_quant.lock")
INTERVAL_SECONDS_MAP = {
"1m": 60,
"5m": 300,
"15m": 900,
"1h": 3600,
"4h": 14400,
"1d": 86400,
}
CCXT_INTERVAL_MAP = {
"1m": "1m",
"5m": "5m",
"15m": "15m",
"1h": "1h",
"4h": "4h",
"1d": "1d",
}
try:
import msvcrt
def acquire_lock():
fd = os.open(LOCK_FILE, os.O_CREAT | os.O_RDWR)
try:
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
except (OSError, IOError):
print("错误: 已有另一个 live_binance_quant 实例在运行,请先停止后再启动")
sys.exit(1)
return fd
except ImportError:
import fcntl
def acquire_lock():
fd = os.open(LOCK_FILE, os.O_CREAT | os.O_RDWR)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (OSError, IOError):
print("错误: 已有另一个 live_binance_quant 实例在运行,请先停止后再启动")
sys.exit(1)
return fd
def load_state():
if os.path.exists(STATE_FILE):
with open(STATE_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return None
def save_state(state):
with open(STATE_FILE, "w", encoding="utf-8") as f:
json.dump(state, f, ensure_ascii=False, indent=2)
def log_message(msg):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{timestamp}] {msg}"
print(line)
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(line + "\n")
def retry_on_exception(max_retries=3, delay=1.0, exceptions=(Exception,)):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except exceptions as e:
if attempt == max_retries - 1:
raise
log_message(
f"{func.__name__} 失败 (尝试 {attempt + 1}/{max_retries}): {e},{delay}s 后重试..."
)
time.sleep(delay)
return None
return wrapper
return decorator
def align_next_wake_time(interval_seconds, offset_seconds=10):
now = datetime.now()
epoch = datetime(1970, 1, 1)
now_ts = (now - epoch).total_seconds()
next_boundary = math.ceil(now_ts / interval_seconds) * interval_seconds
next_wake_ts = next_boundary + offset_seconds
return epoch + timedelta(seconds=next_wake_ts)
def normalize_symbol(symbol: str) -> str:
"""把用户输入统一为 ccxt unified symbol。
支持格式:
- BTCUSDT -> BTC/USDT:USDT
- BTC/USDT:USDT -> BTC/USDT:USDT
- BTC-USDT-SWAP -> BTC/USDT:USDT
"""
s = symbol.strip().upper()
if "/" in s and ":" in s:
return s
if "-" in s:
# BTC-USDT-SWAP -> BTC/USDT:USDT
parts = s.split("-")
if len(parts) >= 2:
base = parts[0]
quote = parts[1]
return f"{base}/{quote}:{quote}"
# BTCUSDT -> BTC/USDT:USDT
if s.endswith("USDT"):
base = s[:-4]
return f"{base}/USDT:USDT"
if s.endswith("USD"):
base = s[:-3]
return f"{base}/USD:USD"
# 无法识别时原样返回,依赖 ccxt 自行处理
return s
# ---------------------------------------------------------------------------
# Binance API 初始化
# ---------------------------------------------------------------------------
def get_binance_credentials():
"""从环境变量读取 API 凭证"""
key = os.environ.get("BINANCE_API_KEY", "")
secret = os.environ.get("BINANCE_API_SECRET", "")
return key, secret
@retry_on_exception(max_retries=3, delay=1.0)
def init_binance_api(demo=False):
"""初始化 ccxt Binance USD-M Futures API"""
key, secret = get_binance_credentials()
if not all([key, secret]):
log_message("错误: 未设置 BINANCE_API_KEY / BINANCE_API_SECRET 环境变量")
sys.exit(1)
config = {
"apiKey": key,
"secret": secret,
"enableRateLimit": True,
"options": {
"defaultType": "swap",
},
}
proxy = os.environ.get("BINANCE_HTTP_PROXY") or os.environ.get("HTTP_PROXY")
if proxy:
config["proxies"] = {
"http": proxy,
"https": proxy,
}
log_message(f"使用 HTTP 代理: {proxy}")
exchange = ccxt.binanceusdm(config)
if demo:
exchange.set_sandbox_mode(True)
log_message("已启用 Binance Testnet 模拟盘模式")
exchange.load_markets()
log_message("Binance API 连接成功")
return exchange
# ---------------------------------------------------------------------------
# Binance API 封装
# ---------------------------------------------------------------------------
@retry_on_exception(max_retries=3, delay=1.0)
def get_balance(exchange, asset="USDT"):
"""查询指定币种余额,返回 (available, equity)"""
balance = exchange.fetch_balance()
free = float(balance.get(asset, {}).get("free", 0.0))
total = float(balance.get(asset, {}).get("total", 0.0))
# futures wallet fallback
if free == 0 and total == 0 and "info" in balance:
assets = balance["info"].get("assets", [])
for item in assets:
if item.get("asset") == asset:
free = float(item.get("availableBalance", 0.0))
total = float(item.get("walletBalance", 0.0))
break
return free, total
@retry_on_exception(max_retries=3, delay=1.0)
def get_position(exchange, symbol):
"""获取永续合约持仓(正=多, 负=空, 0=无)"""
positions = exchange.fetch_positions([symbol])
for pos in positions:
if pos.get("symbol") == symbol:
contracts = float(pos.get("contracts", 0.0) or 0.0)
side = pos.get("side")
if side == "short":
contracts = -abs(contracts)
return contracts
return 0.0
@retry_on_exception(max_retries=3, delay=1.0)
def set_leverage(exchange, symbol, lever):
"""设置合约杠杆"""
try:
exchange.set_leverage(int(lever), symbol)
log_message(f"杠杆设置成功: {symbol} {lever}x")
return True
except Exception as e:
# 已设置相同杠杆时会报错,忽略
if "leverage" in str(e).lower():
log_message(f"杠杆设置: {symbol} {lever}x (可能已相同)")
return True
log_message(f"杠杆设置失败: {e}")
return False
def _precision_to_step(precision):
"""把 ccxt precision 转为最小步长。"""
if precision is None:
return 0.001
p = float(precision)
if 0 < p < 1:
return p
if p >= 1:
return 10 ** (-int(p))
return 0.001
@retry_on_exception(max_retries=3, delay=1.0)
def get_instrument_info(exchange, symbol):
"""获取交易对信息 (tickSize, stepSize, minQty, contractSize)"""
market = exchange.market(symbol)
precision = market.get("precision", {})
limits = market.get("limits", {})
tick_size = _precision_to_step(precision.get("price"))
step_size = _precision_to_step(precision.get("amount"))
min_amount_limit = limits.get("amount", {}).get("min")
min_cost_limit = limits.get("cost", {}).get("min")
return {
"tickSz": float(tick_size),
"lotSz": float(step_size),
"minSz": float(min_amount_limit) if min_amount_limit else float(step_size),
"minCost": float(min_cost_limit) if min_cost_limit else 5.0,
"ctVal": float(market.get("contractSize", 1.0) or 1.0),
}
@retry_on_exception(max_retries=3, delay=1.0)
def fetch_candles(exchange, symbol, bar="5m", limit=500):
"""获取 Binance K 线数据"""
ccxt_interval = CCXT_INTERVAL_MAP.get(bar, bar)
ohlcv = exchange.fetch_ohlcv(symbol, timeframe=ccxt_interval, limit=limit)
if not ohlcv:
log_message("获取K线失败: 返回为空")
return None
records = []
for c in ohlcv:
records.append(
{
"timestamp": int(c[0]),
"open": float(c[1]),
"high": float(c[2]),
"low": float(c[3]),
"close": float(c[4]),
"volume": float(c[5]),
"datetime": pd.to_datetime(int(c[0]), unit="ms"),
}
)
df = pd.DataFrame(records)
return df
@retry_on_exception(max_retries=3, delay=1.0)
def get_orderbook(exchange, symbol, depth=5):
"""获取订单簿,返回 (best_bid, best_ask) 浮点数"""
book = exchange.fetch_order_book(symbol, limit=depth)
bids = book.get("bids", [])
asks = book.get("asks", [])
best_bid = float(bids[0][0]) if bids else None
best_ask = float(asks[0][0]) if asks else None
return best_bid, best_ask
@retry_on_exception(max_retries=3, delay=1.0)
def get_order_status(exchange, symbol, order_id):
"""获取订单状态,返回 (state, fill_sz, avg_px)
ccxt status -> 内部状态映射:
open -> live
closed -> filled
canceled -> canceled
(部分成交 ccxt 通常报 open + filled amount)
"""
order = exchange.fetch_order(order_id, symbol)
ccxt_status = order.get("status")
filled = float(order.get("filled", 0.0) or 0.0)
avg_price = float(order.get("average", 0.0) or 0.0)
state_map = {
"open": "live",
"closed": "filled",
"canceled": "canceled",
"cancelled": "canceled",
"expired": "canceled",
"rejected": "canceled",
}
state = state_map.get(ccxt_status, ccxt_status)
# 部分成交也按 live 处理(后续重试会检查 filled)
if filled > 0 and state == "live":
state = "partially_filled"
return state, filled, avg_price
@retry_on_exception(max_retries=3, delay=1.0)
def get_open_orders(exchange, symbol):
"""获取当前挂单列表"""
return exchange.fetch_open_orders(symbol)
def cancel_all_orders(exchange, symbol):
"""取消指定交易对的所有挂单"""
try:
orders = get_open_orders(exchange, symbol)
for order in orders:
order_id = order.get("id")
if order_id:
try:
exchange.cancel_order(order_id, symbol)
except Exception as e:
log_message(f"取消订单失败: {order_id}, {e}")
if orders:
log_message(f"已取消 {len(orders)} 个挂单: {symbol}")
return True
except Exception as e:
log_message(f"取消所有挂单失败: {e}")
return False
@retry_on_exception(max_retries=3, delay=1.0)
def place_market_order(exchange, symbol, side, pos_side, sz):
"""
下市价单 (Taker)。
side: buy / sell
pos_side: long / short (仅用于日志)
sz: 数量(币数)
"""
order = exchange.create_market_buy_order(symbol, sz) if side == "buy" else exchange.create_market_sell_order(symbol, sz)
order_id = order.get("id")
log_message(f"市价单成功 [{side.upper()} {pos_side}] 订单ID: {order_id}")
return order_id
@retry_on_exception(max_retries=3, delay=1.0)
def place_limit_order(exchange, symbol, side, pos_side, sz, px, post_only=True, time_in_force=None):
"""下限价单 (Maker 或 IOC)"""
params = {}
if post_only:
params["postOnly"] = True
if time_in_force:
params["timeInForce"] = time_in_force
order_type = "limit"
order = exchange.create_order(symbol, order_type, side, sz, px, params)
order_id = order.get("id")
tif = "POST_ONLY" if post_only else (time_in_force or "LIMIT")
log_message(
f"限价单成功 [{side.upper()} {pos_side}] 订单ID: {order_id} 价格={px} 数量={sz} TIF={tif}"
)
return order_id
# ---------------------------------------------------------------------------
# 信号生成
# ---------------------------------------------------------------------------
def predict_signal(strategy, df, enable_short=False):
"""生成交易信号"""
import inspect
sig = inspect.signature(strategy.generate_signals)
if "enable_short" in sig.parameters:
signals = strategy.generate_signals(df, enable_short=enable_short)
else:
signals = strategy.generate_signals(df)
signal_id = int(signals[-1])
close = df["close"].values
window = strategy.window
rolling_mean = pd.Series(close).rolling(window=window, min_periods=window).mean()
rolling_std = pd.Series(close).rolling(window=window, min_periods=window).std()
upper = rolling_mean + strategy.std_dev * rolling_std
lower = rolling_mean - strategy.std_dev * rolling_std
bb_info = {
"price": close[-1],
"upper": upper.iloc[-1],
"mid": rolling_mean.iloc[-1],
"lower": lower.iloc[-1],
}
return signal_id, bb_info
# ---------------------------------------------------------------------------
# 价格/数量精度处理
# ---------------------------------------------------------------------------
def round_to_tick(price, tick_size):
"""将价格对齐到 tick_size,避免浮点精度问题"""
ticks = round(float(price) / float(tick_size))
return float(Decimal(ticks) * Decimal(str(tick_size)))
def round_to_size(size, lot_size):
"""将数量对齐到 lot_size"""
units = int(Decimal(str(size)) / Decimal(str(lot_size)))
return float(units * Decimal(str(lot_size)))
def compute_order_price(side, best_bid, best_ask, tick_size):
"""计算 POST_ONLY 限价单价格(挂在 best bid/ask 提高成交率),对齐到 tick_size"""
if side == "buy":
price = best_bid
else:
price = best_ask
return round_to_tick(price, tick_size) if price else None
def compute_ioc_price(side, best_bid, best_ask, tick_size):
"""计算 IOC 单价格(穿越盘口确保成交),对齐到 tick_size"""
if side == "buy":
price = best_ask + float(tick_size) * 2 if best_ask else None
else:
price = best_bid - float(tick_size) * 2 if best_bid else None
if price is not None:
price = round_to_tick(price, tick_size)
return price
# ---------------------------------------------------------------------------
# 交易执行
# ---------------------------------------------------------------------------
def execute_trade(
signal_id,
exchange,
symbol,
tick_sz,
lot_sz,
capital_per_trade,
state,
current_price,
best_bid,
best_ask,
force_ioc=False,
):
"""
根据信号执行交易(支持多空双向)
signal_id: 0=平仓, 1=持有, 2=做多, 3=做空
force_ioc: True=强制用市价单(兜底模式), False=先尝试Maker挂单
"""
position = state.get("position", 0)
strategy_size = state.get("strategy_size", 0.0)
trades = state.get("trades", [])
MIN_ORDER_USDT = 5.0
log_message(f"[交易] signal={signal_id} position={position} target计算中...")
# 先取消所有现有挂单
cancel_all_orders(exchange, symbol)
# 同步实际持仓到 state
actual_pos = get_position(exchange, symbol)
if abs(actual_pos) < lot_sz * 0.5:
if position != 0:
log_message(f"[持仓同步] 实际持仓为0,重置状态 (原state: {position})")
state["position"] = 0
state["strategy_size"] = 0.0
state["entry_bar"] = 0
position = 0
strategy_size = 0.0
else:
actual_dir = 1 if actual_pos > 0 else -1
if position != actual_dir:
log_message(f"[持仓同步] 修正持仓方向: state={position} -> actual={actual_dir}")
state["position"] = actual_dir
state["strategy_size"] = abs(actual_pos)
position = actual_dir
strategy_size = abs(actual_pos)
# 解析目标仓位
target_pos = position
if signal_id == 2:
target_pos = 1
elif signal_id == 3:
target_pos = -1
elif signal_id == 0:
target_pos = 0
log_message(f"[交易] target_pos={target_pos} position={position}")
if target_pos == position:
log_message("[交易] 无需换仓,跳过")
state["last_signal"] = signal_id
return state
# --- 平掉当前仓位 ---
# 判断盈亏以决定订单类型: 盈利->Maker(限价), 亏损->Taker(市价)
entry_price = state.get("entry_price", 0)
if position == 1 and entry_price > 0:
pnl_pct = (current_price - entry_price) / entry_price
elif position == -1 and entry_price > 0:
pnl_pct = (entry_price - current_price) / entry_price
else:
pnl_pct = 0
close_as_maker = pnl_pct > 0
close_type_str = "Maker(TP)" if close_as_maker else "Taker(SL)"
if position == 1 and target_pos <= 0:
# 平多仓(卖出平多)
if strategy_size > 0:
actual_position = get_position(exchange, symbol)
sell_size = (
min(strategy_size, abs(actual_position)) if actual_position > 0 else strategy_size
)
if sell_size > 0:
sell_size = round_to_size(sell_size, lot_sz)
if sell_size > 0:
if close_as_maker:
order_price = compute_order_price("sell", best_bid, best_ask, tick_sz)
if order_price:
order_id = place_limit_order(
exchange, symbol, "sell", "long", sell_size, order_price, post_only=True
)
else:
order_id = None
else:
order_id = place_market_order(
exchange, symbol, "sell", "long", sell_size
)
order_price = current_price
if order_id:
trades.append(
{
"time": datetime.now().isoformat(),
"type": f"CLOSE_LONG_{close_type_str}",
"symbol": symbol,
"orderId": order_id,
"size": sell_size,
"price": order_price,
}
)
log_message(
f"[平多{close_type_str}] pnl={pnl_pct * 100:+.2f}% 下单卖出 size={sell_size:.8f} price={order_price}"
)
else:
log_message(f"[平多失败] {close_type_str}单未成交")
state["position"] = 0
state["strategy_size"] = 0.0
state["entry_bar"] = 0
elif position == -1 and target_pos >= 0:
# 平空仓(买入平空)
if strategy_size > 0:
actual_position = get_position(exchange, symbol)
close_size = (
min(strategy_size, abs(actual_position)) if actual_position < 0 else strategy_size
)
if close_size > 0:
close_size = round_to_size(close_size, lot_sz)
if close_size > 0:
if close_as_maker:
order_price = compute_order_price("buy", best_bid, best_ask, tick_sz)
if order_price:
order_id = place_limit_order(
exchange, symbol, "buy", "short", close_size, order_price, post_only=True
)
else:
order_id = None
else:
order_id = place_market_order(
exchange, symbol, "buy", "short", close_size
)
order_price = current_price
if order_id:
trades.append(
{
"time": datetime.now().isoformat(),
"type": f"CLOSE_SHORT_{close_type_str}",
"symbol": symbol,
"orderId": order_id,
"size": close_size,
"price": order_price,
}
)
log_message(
f"[平空{close_type_str}] pnl={pnl_pct * 100:+.2f}% 下单买入 size={close_size:.8f} price={order_price}"
)
else:
log_message(f"[平空失败] {close_type_str}单未成交")
state["position"] = 0
state["strategy_size"] = 0.0
state["entry_bar"] = 0
# --- 开新仓 ---
log_message(
f"[交易] 检查开仓: target_pos={target_pos} state_position={state.get('position', 0)} force_ioc={force_ioc}"
)
if target_pos == 1 and state.get("position", 0) == 0:
if current_price <= 0:
log_message("[跳过开多] 价格无效")
else:
raw_size = Decimal(str(capital_per_trade)) / Decimal(str(current_price))
n_units = int(raw_size / Decimal(str(lot_sz)))
order_size = float(n_units * Decimal(str(lot_sz)))
if order_size > 0:
notional = order_size * current_price
if notional < MIN_ORDER_USDT:
log_message(f"[跳过开多] 名义价值 {notional:.2f} < 最小下单 {MIN_ORDER_USDT} USDT")
elif force_ioc:
order_id = place_market_order(
exchange, symbol, "buy", "long", order_size
)
if order_id:
trades.append(
{
"time": datetime.now().isoformat(),
"type": "BUY_OPEN_IOC_FALLBACK",
"symbol": symbol,
"orderId": order_id,
"size": order_size,
"price": current_price,
}
)
state["position"] = 1
state["strategy_size"] = order_size
state["entry_price"] = current_price
state["entry_bar"] = state.get("bar_count", 0)
log_message(
f"[开多市价兜底] size={order_size:.8f} price={current_price:.2f}"
)
else:
log_message("[开多市价失败] 兜底单也未成交")
else:
order_price = compute_order_price("buy", best_bid, best_ask, tick_sz)
if order_price:
order_id = place_limit_order(
exchange, symbol, "buy", "long", order_size, order_price, post_only=True
)
if order_id:
trades.append(
{
"time": datetime.now().isoformat(),
"type": "BUY_OPEN_MAKER",
"symbol": symbol,
"orderId": order_id,
"size": order_size,
"price": order_price,
}
)
state["pending_open"] = True
state["pending_order_id"] = order_id
state["pending_open_signal"] = 2
state["pending_open_price"] = current_price
state["pending_open_size"] = order_size
log_message(
f"[开多Maker] 挂单买入 size={order_size:.8f} price={order_price:.2f} notional={notional:.2f}"
)
else:
log_message("[开多失败] 限价单被拒绝")
else:
log_message("[开多失败] 无有效盘口价格")
elif target_pos == -1 and state.get("position", 0) == 0:
if current_price <= 0:
log_message("[跳过开空] 价格无效")
else:
raw_size = Decimal(str(capital_per_trade)) / Decimal(str(current_price))
n_units = int(raw_size / Decimal(str(lot_sz)))
order_size = float(n_units * Decimal(str(lot_sz)))
if order_size > 0:
notional = order_size * current_price
if notional < MIN_ORDER_USDT:
log_message(f"[跳过开空] 名义价值 {notional:.2f} < 最小下单 {MIN_ORDER_USDT} USDT")
elif force_ioc:
order_id = place_market_order(
exchange, symbol, "sell", "short", order_size
)
if order_id:
trades.append(
{
"time": datetime.now().isoformat(),
"type": "SELL_SHORT_IOC_FALLBACK",
"symbol": symbol,
"orderId": order_id,
"size": order_size,
"price": current_price,
}
)
state["position"] = -1
state["strategy_size"] = order_size
state["entry_price"] = current_price
state["entry_bar"] = state.get("bar_count", 0)
log_message(
f"[开空市价兜底] size={order_size:.8f} price={current_price:.2f}"
)
else:
log_message("[开空市价失败] 兜底单也未成交")
else:
order_price = compute_order_price("sell", best_bid, best_ask, tick_sz)
if order_price:
order_id = place_limit_order(
exchange, symbol, "sell", "short", order_size, order_price, post_only=True
)
if order_id:
trades.append(
{
"time": datetime.now().isoformat(),
"type": "SELL_SHORT_MAKER",
"symbol": symbol,
"orderId": order_id,
"size": order_size,
"price": order_price,
}
)
state["pending_open"] = True
state["pending_order_id"] = order_id
state["pending_open_signal"] = 3
state["pending_open_price"] = current_price
state["pending_open_size"] = order_size
log_message(
f"[开空Maker] 挂单卖出 size={order_size:.8f} price={order_price:.2f} notional={notional:.2f}"
)
else:
log_message("[开空失败] 限价单被拒绝")
else:
log_message("[开空失败] 无有效盘口价格")
state["trades"] = trades
state["last_signal"] = signal_id
state["last_update"] = datetime.now().isoformat()
# 平仓后清理 TP 状态
if state.get("position", 0) == 0:
state["tp_order_id"] = None
state["tp_price"] = 0.0
state["tp_side"] = None
return state
def manage_tp_order(exchange, symbol, tick_sz, lot_sz, strategy, state):
"""
管理止盈限价单 (Maker)。
当持仓存在且无 TP 单时,自动挂止盈限价单。
"""
pos = state.get("position", 0)
entry_price = state.get("entry_price", 0)
size = state.get("strategy_size", 0)
tp_order_id = state.get("tp_order_id")
if pos == 0 or entry_price == 0 or size == 0:
if tp_order_id:
try:
exchange.cancel_order(tp_order_id, symbol)
except Exception:
pass
state["tp_order_id"] = None
state["tp_price"] = 0.0
state["tp_side"] = None
return state
# 计算止盈价格和方向
tp_pct = getattr(strategy, "take_profit_pct", 0.02)
if pos == 1:
tp_price = round_to_tick(entry_price * (1 + tp_pct), tick_sz)
tp_side = "sell"
tp_pos_side = "long"
else:
tp_price = round_to_tick(entry_price * (1 - tp_pct), tick_sz)
tp_side = "buy"
tp_pos_side = "short"
# 已有正确的 TP 单则跳过
if tp_order_id and state.get("tp_price") == tp_price and state.get("tp_side") == tp_side:
return state
# 取消旧 TP 单
if tp_order_id:
try:
exchange.cancel_order(tp_order_id, symbol)
except Exception:
pass
state["tp_order_id"] = None
# 对齐 size
order_size = round_to_size(size, lot_sz)
if order_size <= 0:
return state
# 挂止盈限价单 (Maker)
order_id = place_limit_order(
exchange, symbol, tp_side, tp_pos_side, order_size, tp_price, post_only=True
)
if order_id:
state["tp_order_id"] = order_id
state["tp_price"] = tp_price
state["tp_side"] = tp_side
log_message(
f"[TP挂单] {tp_side.upper()} {tp_pos_side} size={order_size:.8f} @ {tp_price:.2f} (入场={entry_price:.2f}, TP={tp_pct * 100:.1f}%)"
)
return state
def cancel_tp_order(exchange, symbol, state):
"""取消止盈限价单"""
tp_order_id = state.get("tp_order_id")
if tp_order_id:
try:
exchange.cancel_order(tp_order_id, symbol)
except Exception:
pass
state["tp_order_id"] = None
state["tp_price"] = 0.0
state["tp_side"] = None
return state
def check_stop_loss(state, current_price, stop_loss_pct=0.03, max_hold_bars=48):
"""检查止损和时间退出条件(支持多空双向)"""
pos = state.get("position", 0)
if pos == 0:
return False, ""
entry_price = state.get("entry_price", 0)
entry_bar = state.get("entry_bar", 0)
current_bar = state.get("bar_count", 0)
if pos == 1:
# 多头止损:价格下跌超过阈值
if entry_price > 0 and (entry_price - current_price) / entry_price >= stop_loss_pct:
return (
True,
f"多头止损: 跌幅 {(entry_price - current_price) / entry_price * 100:.2f}% >= {stop_loss_pct * 100:.0f}%",
)
elif pos == -1:
# 空头止损:价格上涨超过阈值
if entry_price > 0 and (current_price - entry_price) / entry_price >= stop_loss_pct:
return (
True,
f"空头止损: 涨幅 {(current_price - entry_price) / entry_price * 100:.2f}% >= {stop_loss_pct * 100:.0f}%",
)
if current_bar - entry_bar >= max_hold_bars:
pos_name = "多头" if pos == 1 else "空头"
return True, f"{pos_name}时间退出: 持仓 {current_bar - entry_bar} 根K线 >= {max_hold_bars}"
return False, ""
def force_close(
exchange,
symbol,
state,
current_price,
best_bid,
best_ask,
tick_sz,
lot_sz,
reason,
use_maker=False,
):
"""
强制平仓。
use_maker=False: 市价单 (Taker) -- 止损场景,必须保证成交
use_maker=True: 限价单 (Maker) -- 超时场景,可挂单等成交
"""
pos = state.get("position", 0)
strategy_size = state.get("strategy_size", 0.0)
if pos == 0 or strategy_size <= 0:
return state
# 取消 TP 单和所有挂单
cancel_tp_order(exchange, symbol, state)
cancel_all_orders(exchange, symbol)
actual_position = get_position(exchange, symbol)
close_size = (
min(strategy_size, abs(actual_position)) if abs(actual_position) > 0 else strategy_size
)
if close_size > 0:
close_size = round_to_size(close_size, lot_sz)
if close_size <= 0:
state["position"] = 0
state["strategy_size"] = 0.0
state["entry_bar"] = 0
return state
# 确定平仓方向
if pos == 1:
side = "sell"
pos_side = "long"
elif pos == -1:
side = "buy"
pos_side = "short"
else:
return state
# 根据场景选择订单类型
if use_maker:
order_price = compute_order_price(side, best_bid, best_ask, tick_sz)
if order_price:
order_id = place_limit_order(
exchange, symbol, side, pos_side, close_size, order_price, post_only=True
)
else:
order_id = None
fee_label = "Maker"
else:
order_id = place_market_order(exchange, symbol, side, pos_side, close_size)
order_price = current_price
fee_label = "Taker"
if order_id:
trades = state.get("trades", [])
pos_name = "多头" if pos == 1 else "空头"
trades.append(
{
"time": datetime.now().isoformat(),