-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainProgramme.py
More file actions
2199 lines (2018 loc) · 97.2 KB
/
Copy pathMainProgramme.py
File metadata and controls
2199 lines (2018 loc) · 97.2 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
"""
SOLUSDT aggressive short-term trading bot v8.3.
Trades only the Binance margin account. Position sizing is based on margin
account equity and does not transfer funds across accounts.
"""
import os, sys, json, time, logging, traceback
from datetime import datetime, timedelta
from typing import Optional, Tuple
from urllib.parse import urlparse
from urllib import request, error
import ccxt
import numpy as np
from calculator import SlippageTracker, net_pnl_after_fee
from config import RuntimeConfig, build_runtime_config
from storage import Storage
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("trading_bot.log", encoding="utf-8"),
logging.StreamHandler(sys.stdout),
],
)
logger = logging.getLogger("SOLUSDT")
SYMBOL = "SOL/USDT"
TIMEFRAME = "5m"
KLINE_POLL_SECONDS = 50
EMA_FAST, EMA_MID, EMA_SLOW = 5, 13, 30
RSI_PERIOD = 7
MACD_FAST, MACD_SLOW, MACD_SIG = 8, 17, 9
BB_PERIOD, BB_STD = 14, 2.0
ATR_PERIOD, VOL_MA = 7, 10
STOP_LOSS_PCT = 0.010
TAKE_PROFIT_PCT = 0.015
TRAILING_ACTIVATE = 0.012
TRAILING_DIST = 0.0045
BREAK_EVEN_ACTIVATE = 0.010
BREAK_EVEN_BUFFER = 0.0012
PROFIT_RETRACE_KEEP = 0.42
MIN_PROFIT_EXIT = 0.0035
TIME_STOP_MIN = None
ATR_STOP_MULT = None
MAX_DAILY_LOSS_PCT = 0.15
MAX_DAILY_TRADES = 999 # Unlimited daily trades.
MAX_CONSEC_LOSS = 5
PAUSE_MINUTES = 30
POST_TRADE_COOLDOWN_MIN = 0
LOSS_COOLDOWN_MIN = 0
MIN_EMA_SEP_PCT = 0.0000
MIN_ATR_PCT = 0.00045
MAX_LONG_RSI = 55
MIN_SHORT_RSI = 45
VOL_CONFIRM_MULT = 1.5
BB_LONG_TOUCH = 1.003
BB_SHORT_TOUCH = 0.997
MIN_BB_WIDTH_PCT = 0.006
FAKE_BREAKOUT_LOOKBACK = 3
FAKE_BREAKOUT_STRICT_MULT = 1.25
RSI_DIVERGENCE_LOOKBACK = 18
RSI_DIVERGENCE_MIN_GAP = 3.0
BASE_CAP_USE = 0.48
MAX_AI_CAP_USE = 0.70
MIN_AI_CAP_USE = 0.10
HARD_MAX_LOSS_PCT = 0.010
FORCE_EXIT_NEGATIVE_HOLD_MIN = 120
ATR_TAKE_PROFIT_MULT = 1.5
ATR_STOP_LOSS_MULT = 1.0
MIN_TAKE_PROFIT_PCT = 0.015
MIN_DYNAMIC_STOP_LOSS_PCT = 0.006
AI_REVIEW_AFTER_MIN = 30
AI_REVIEW_INTERVAL_MIN = 30
AI_MAX_RETRIES = 2
AI_RETRY_BASE_DELAY = 0.6
AI_TIMEOUT_WARN_SECONDS = 6.0
DUST_POSITION_SOL = 0.005
DUST_POSITION_USDT = 3.0
FEE_RATE = 0.001
MTF_15M = "15m"
MTF_1H = "1h"
MTF_EMA_FAST = 50
MTF_EMA_SLOW = 200
META_KEYS = {"info", "free", "used", "total", "timestamp", "datetime",
"debt", "borrowed", "interest", "net", "currency", "free_margin",
"used_margin", "equity", "unrealized_pnl", "margin_ratio", "position"}
def get_cfg(equity: float) -> dict:
return {"leverage": 5, "cap_use": BASE_CAP_USE, "max_cap_use": MAX_AI_CAP_USE, "label": "v8.3-sqlite"}
class DeepSeekRiskAdvisor:
def __init__(self, api_key: str = "", model: str = "deepseek-chat",
enabled: bool = True, timeout: int = 8,
runtime: RuntimeConfig = None, storage: Storage = None):
self.api_key = (api_key or "").strip()
self.model = model or "deepseek-chat"
self.enabled = bool(enabled and self.api_key)
self.timeout = int(timeout or 8)
self.runtime = runtime or build_runtime_config({})
self.features = self.runtime.features
self.db = storage
self._last_response_ms = 0
self._cache = {}
self._stats_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ai_stats.json")
self._stats = self._load_stats()
self.system_prompt = (
"You are a strict crypto trading risk manager for SOLUSDT 5m margin scalping. "
"Return compact JSON only. For entry you may approve, skip, reduce cap_use, or raise cap_use "
"up to 0.70. For exit you may hold, close, or close and immediately reverse to the opposite side "
"when evidence is strong. If holding you must set next_take_profit_pct and next_stop_loss_pct. "
"If reversing, return action reverse_long or reverse_short plus cap_use 0.10-0.70. "
"The bot enforces hard exits: never rely on AI hold beyond -1.0% loss or after 120 minutes negative. "
"Reflect on recent trade results before approving. Prefer skip when signal quality is weak. "
"Keep reasons short in Chinese."
)
def _load_stats(self) -> dict:
try:
if os.path.exists(self._stats_file):
with open(self._stats_file, encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
data.setdefault("recent", [])
data.setdefault("approve_wins", 0)
data.setdefault("approve_losses", 0)
data.setdefault("approve_pnl", 0.0)
data.setdefault("approve_consec_losses", 0)
return data
except (OSError, json.JSONDecodeError) as e:
logger.warning(f"AI stats load failed: {e}")
return {"recent": [], "approve_wins": 0, "approve_losses": 0,
"approve_pnl": 0.0, "approve_consec_losses": 0}
def _save_stats(self):
try:
with open(self._stats_file, "w", encoding="utf-8") as f:
json.dump(self._stats, f, ensure_ascii=False)
except OSError as e:
logger.warning(f"AI stats save failed: {e}")
def recent_results(self) -> list:
return list(self._stats.get("recent", []))[-3:]
def effective_max_cap_use(self, cfg: dict) -> float:
max_cap = float(cfg.get("max_cap_use", MAX_AI_CAP_USE))
if self.features.ai_quality_stats and int(self._stats.get("approve_consec_losses", 0) or 0) >= 5:
max_cap = min(max_cap, BASE_CAP_USE)
return max(MIN_AI_CAP_USE, min(MAX_AI_CAP_USE, max_cap))
def record_trade_result(self, ai_entry: dict, pnl: float):
if not self.features.ai_quality_stats:
return
if not isinstance(ai_entry, dict) or ai_entry.get("action") != "approve":
return
pnl = float(pnl or 0)
won = pnl > 0
if won:
self._stats["approve_wins"] = int(self._stats.get("approve_wins", 0) or 0) + 1
self._stats["approve_consec_losses"] = 0
else:
self._stats["approve_losses"] = int(self._stats.get("approve_losses", 0) or 0) + 1
self._stats["approve_consec_losses"] = int(self._stats.get("approve_consec_losses", 0) or 0) + 1
self._stats["approve_pnl"] = float(self._stats.get("approve_pnl", 0.0) or 0.0) + pnl
recent = list(self._stats.get("recent", []))
recent.append({
"time": datetime.now().strftime("%m/%d %H:%M:%S"),
"pnl": round(pnl, 4),
"win": won,
"reason": str(ai_entry.get("reason", ""))[:80],
})
self._stats["recent"] = recent[-20:]
self._save_stats()
if int(self._stats.get("approve_consec_losses", 0) or 0) >= 5:
logger.warning("AI approve quality degraded: 5 consecutive losing approved trades; cap_use max limited to base")
@staticmethod
def _clean_float(value, digits: int = 4):
try:
if value is None or np.isnan(value):
return None
return round(float(value), digits)
except Exception:
return None
def _signature(self, prefix: str, signal_side: str, cp: float, ind: dict, risk: "RiskManager", reason: str = "") -> str:
rsi_now = self._clean_float(StrategyEngine.last(ind["rsi"]), 1)
atr_now = self._clean_float(StrategyEngine.last(ind["atr"]) / cp * 100 if cp > 0 else None, 3)
bucket = int(time.time() // 600)
return f"{prefix}:{bucket}:{signal_side}:{round(cp, 2)}:{rsi_now}:{atr_now}:{risk.daily_trades}:{risk.consec_losses}:{reason[:30]}"
def _payload(self, signal_side: str, signal_reason: str, cp: float, klines: dict,
ind: dict, equity: float, margin_level: float, cfg: dict,
risk: "RiskManager", context: dict = None) -> dict:
candles = []
for i in range(max(0, len(klines["close"]) - 12), len(klines["close"])):
candles.append([
int(klines["timestamp"][i] // 1000),
round(float(klines["open"][i]), 3),
round(float(klines["high"][i]), 3),
round(float(klines["low"][i]), 3),
round(float(klines["close"][i]), 3),
round(float(klines["volume"][i]), 1),
])
bbu = StrategyEngine.last(ind["bb_u"])
bbl = StrategyEngine.last(ind["bb_l"])
bbm = StrategyEngine.last(ind["bb_m"])
atr_v = StrategyEngine.last(ind["atr"])
vol_ma = StrategyEngine.last(ind["vol_ma"])
payload = {
"symbol": "SOLUSDT",
"timeframe": "5m",
"candidate": signal_side,
"signal_reason": signal_reason,
"price": round(float(cp), 4),
"account": {
"equity_usdt": round(float(equity), 3),
"margin_level_pct": round(float(margin_level), 1),
"leverage": cfg.get("leverage"),
"base_cap_use": cfg.get("cap_use"),
"max_cap_use": cfg.get("max_cap_use", MAX_AI_CAP_USE),
"daily_trades": risk.daily_trades,
"daily_pnl_usdt": round(float(risk.daily_pnl), 3),
"consecutive_losses": risk.consec_losses,
},
"indicators": {
"rsi": self._clean_float(StrategyEngine.last(ind["rsi"]), 1),
"rsi_prev": self._clean_float(StrategyEngine.prev(ind["rsi"]), 1),
"ema5": self._clean_float(StrategyEngine.last(ind["ema_f"]), 4),
"ema13": self._clean_float(StrategyEngine.last(ind["ema_m"]), 4),
"bb_upper": self._clean_float(bbu, 4),
"bb_lower": self._clean_float(bbl, 4),
"bb_width_pct": self._clean_float((bbu - bbl) / bbm * 100 if bbm and not np.isnan(bbm) else None, 3),
"volume": self._clean_float(klines["volume"][-1], 1),
"volume_ma": self._clean_float(vol_ma, 1),
"atr_pct": self._clean_float(atr_v / cp * 100 if cp > 0 else None, 3),
"macd_hist": self._clean_float(StrategyEngine.last(ind["hist"]), 5),
},
"recent_ai_results": self.recent_results(),
"recent_12_candles": candles,
"mtf": self._extract_mtf_payload(context),
}
if context:
payload["context"] = context
return payload
@staticmethod
def _extract_mtf_payload(context: dict = None) -> dict:
if not isinstance(context, dict):
return {"consensus": "unknown"}
if "consensus" in context:
return context
mtf = context.get("mtf")
if isinstance(mtf, dict):
return mtf
return {"consensus": "unknown"}
def _request_json(self, user_payload: dict, max_tokens: int = 180) -> dict:
body = {
"model": self.model,
"temperature": 0.1,
"max_tokens": max_tokens,
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": self.system_prompt},
{"role": "user", "content": json.dumps(user_payload, ensure_ascii=False, separators=(",", ":"))},
],
}
req = request.Request(
"https://api.deepseek.com/chat/completions",
data=json.dumps(body).encode("utf-8"),
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
},
method="POST",
)
attempts = AI_MAX_RETRIES + 1 if self.features.ai_retries else 1
last_err = None
for attempt in range(attempts):
started = time.time()
try:
with request.urlopen(req, timeout=self.timeout) as resp:
data = json.loads(resp.read().decode("utf-8"))
elapsed = time.time() - started
if elapsed >= AI_TIMEOUT_WARN_SECONDS:
logger.warning(f"DeepSeek slow response: {elapsed:.2f}s attempt={attempt + 1}")
else:
logger.info(f"DeepSeek response: {elapsed:.2f}s attempt={attempt + 1}")
self._last_response_ms = int(elapsed * 1000)
content = data["choices"][0]["message"]["content"]
return json.loads(content)
except (error.URLError, TimeoutError, json.JSONDecodeError, KeyError, ValueError) as e:
last_err = e
if attempt + 1 >= attempts:
break
delay = AI_RETRY_BASE_DELAY * (2 ** attempt)
logger.warning(f"DeepSeek request failed attempt={attempt + 1}: {e}; retry in {delay:.1f}s")
time.sleep(delay)
raise last_err or RuntimeError("DeepSeek request failed")
def _save_ai_decision(self, call_type: str, side: str, price: float,
payload: dict, result: dict):
if not self.db or not self.db.enabled:
return
try:
self.db.save_ai_decision(
call_type=call_type,
side=side,
price=price,
action=str(result.get("action", "")),
cap_use=result.get("cap_use"),
response_ms=int(self._last_response_ms or 0),
reason=str(result.get("reason", "")),
payload=payload,
result=result,
)
except Exception as e:
logger.warning(f"SQLite AI decision write skipped: {e}")
def _latest_cached(self, prefix: str, side: str):
wanted = f"{prefix}:"
marker = f":{side}:"
for key, value in reversed(list(self._cache.items())):
if str(key).startswith(wanted) and marker in str(key):
return value
return None
def advise(self, signal_side: str, signal_reason: str, cp: float, klines: dict,
ind: dict, equity: float, margin_level: float, cfg: dict,
risk: "RiskManager", context: dict = None) -> Tuple[bool, dict]:
if not self.enabled:
return True, {"action": "approve", "cap_use": cfg.get("cap_use"), "reason": "DeepSeek disabled"}
sig = self._signature("entry", signal_side, cp, ind, risk, signal_reason)
if sig in self._cache:
return self._cache[sig]
user_payload = self._payload(signal_side, signal_reason, cp, klines, ind, equity, margin_level, cfg, risk, context)
user_payload["task"] = "entry_decision"
user_payload["return_schema"] = {"action": "approve|skip", "cap_use": "0.10-0.70", "reason": "short Chinese reason"}
try:
decision = self._request_json(user_payload, max_tokens=160)
action = str(decision.get("action", "skip")).lower()
cap = float(decision.get("cap_use", cfg.get("cap_use")) or cfg.get("cap_use"))
cap = max(MIN_AI_CAP_USE, min(self.effective_max_cap_use(cfg), cap))
allowed = action == "approve" and cap >= MIN_AI_CAP_USE
result = (allowed, {
"action": "approve" if allowed else "skip",
"cap_use": cap,
"reason": str(decision.get("reason", ""))[:120],
})
logger.info(f"DeepSeek entry risk: {result[1]['action']} cap={cap:.2f} reason={result[1]['reason']}")
except (error.URLError, TimeoutError, json.JSONDecodeError, KeyError, ValueError) as e:
cached = self._latest_cached("entry", signal_side) if self.features.ai_cache_fallback else None
if cached:
allowed, ai = cached
result = (allowed, {**ai, "reason": f"AI失败,用缓存判断: {ai.get('reason', '')}"[:120], "source": "cache_fallback"})
logger.warning(f"DeepSeek entry failed; using cached decision: {e}")
else:
result = (True, {"action": "approve", "cap_use": cfg.get("cap_use"), "reason": f"DeepSeek entry failed; local fallback approve: {e}"})
logger.warning(f"DeepSeek entry risk failed; local fallback approve: {e}")
self._cache[sig] = result
self._save_ai_decision("entry", signal_side, cp, user_payload, result[1])
if len(self._cache) > 64:
self._cache.pop(next(iter(self._cache)))
return result
def advise_exit(self, pos: dict, exit_reason: str, cp: float, klines: dict, ind: dict,
equity: float, margin_level: float, risk: "RiskManager",
context: dict = None) -> dict:
if not self.enabled:
return {"action": "close", "reason": "DeepSeek disabled"}
side = str(pos.get("side", ""))
entry = float(pos.get("entry_price", 0) or 0)
amount = float(pos.get("amount", 0) or 0)
if entry <= 0 or amount <= 0:
return {"action": "close", "reason": "position invalid"}
pnl_pct = (cp - entry) / entry if side == "long" else (entry - cp) / entry
entry_time = pos.get("entry_time")
if isinstance(entry_time, datetime):
hold_min = max(0.0, (datetime.now() - entry_time).total_seconds() / 60)
else:
hold_min = 0.0
max_gain = ((float(pos.get("highest", entry) or entry) - entry) / entry if side == "long"
else (entry - float(pos.get("lowest", entry) or entry)) / entry)
cfg = get_cfg(equity)
payload = self._payload(side, exit_reason, cp, klines, ind, equity, margin_level, cfg, risk, context)
payload["task"] = "exit_decision"
payload["position"] = {
"side": side,
"entry_price": round(entry, 4),
"amount_sol": round(amount, 6),
"pnl_pct": round(pnl_pct * 100, 3),
"hold_minutes": round(hold_min, 1),
"max_gain_pct": round(max_gain * 100, 3),
"exit_trigger": exit_reason,
"current_plan": pos.get("ai_exit_plan") or {},
}
payload["return_schema"] = {
"action": "close|hold|reverse_long|reverse_short",
"reason": "short Chinese reason",
"next_take_profit_pct": "positive decimal, e.g. 0.012",
"next_stop_loss_pct": "positive decimal, e.g. 0.026",
"cap_use": "optional for reverse, 0.10-0.70",
}
sig = self._signature("exit", side, cp, ind, risk, exit_reason)
if sig in self._cache:
return self._cache[sig][1]
try:
decision = self._request_json(payload, max_tokens=180)
action = str(decision.get("action", "close")).lower()
next_tp = float(decision.get("next_take_profit_pct", TAKE_PROFIT_PCT) or TAKE_PROFIT_PCT)
next_sl = float(decision.get("next_stop_loss_pct", STOP_LOSS_PCT) or STOP_LOSS_PCT)
next_tp = max(MIN_TAKE_PROFIT_PCT, min(0.035, next_tp))
next_sl = max(MIN_DYNAMIC_STOP_LOSS_PCT, min(HARD_MAX_LOSS_PCT, next_sl))
reverse_side = None
if action in {"reverse_long", "reverse_short"}:
reverse_side = "long" if action.endswith("long") else "short"
if reverse_side == side:
reverse_side = None
action = "close"
reverse_cap = float(decision.get("cap_use", cfg.get("cap_use")) or cfg.get("cap_use"))
reverse_cap = max(MIN_AI_CAP_USE, min(self.effective_max_cap_use(cfg), reverse_cap))
result = {
"action": "hold" if action == "hold" else ("reverse" if reverse_side else "close"),
"reason": str(decision.get("reason", ""))[:160],
"next_take_profit_pct": next_tp,
"next_stop_loss_pct": next_sl,
"pnl_pct": round(pnl_pct * 100, 3),
"reverse_side": reverse_side,
"cap_use": reverse_cap,
}
logger.info(
f"DeepSeek出场: {result['action']} reverse={reverse_side or '-'} "
f"tp={next_tp*100:.2f}% sl={next_sl*100:.2f}% reason={result['reason']}"
)
except (error.URLError, TimeoutError, json.JSONDecodeError, KeyError, ValueError) as e:
cached = self._latest_cached("exit", side) if self.features.ai_cache_fallback else None
if cached:
result = {**cached[1], "reason": f"AI出场失败,用缓存判断: {cached[1].get('reason', '')}"[:160], "source": "cache_fallback"}
logger.warning(f"DeepSeek出场失败,使用缓存判断: {e}")
else:
result = {"action": "close", "reason": f"DeepSeek出场失败默认平仓: {e}"}
logger.warning(f"DeepSeek出场失败,默认平仓: {e}")
self._cache[sig] = (result.get("action") == "hold", result)
self._save_ai_decision("exit", side, cp, payload, result)
if len(self._cache) > 64:
self._cache.pop(next(iter(self._cache)))
return result
# ============================================================
# Technical indicators.
# ============================================================
def ema(data: np.ndarray, period: int) -> np.ndarray:
result = np.full_like(data, np.nan, dtype=np.float64)
if len(data) < period:
return result
m = 2.0 / (period + 1)
result[period - 1] = np.mean(data[:period])
for i in range(period, len(data)):
result[i] = (data[i] - result[i - 1]) * m + result[i - 1]
return result
def rsi(close: np.ndarray, period: int = 7) -> np.ndarray:
result = np.full_like(close, np.nan, dtype=np.float64)
if len(close) < period + 1:
return result
delta = np.diff(close)
gain, loss = np.where(delta > 0, delta, 0.0), np.where(delta < 0, -delta, 0.0)
ag, al = np.mean(gain[:period]), np.mean(loss[:period])
result[period] = 100.0 if al == 0 else 100.0 - (100.0 / (1.0 + ag / al))
for i in range(period + 1, len(close)):
ag = (ag * (period - 1) + gain[i - 1]) / period
al = (al * (period - 1) + loss[i - 1]) / period
result[i] = 100.0 if al == 0 else 100.0 - (100.0 / (1.0 + ag / al))
return result
def macd(close: np.ndarray, fast: int = 8, slow: int = 17, signal: int = 9):
ef, es = ema(close, fast), ema(close, slow)
ml = ef - es
sl = ema(ml, signal)
return ml, sl, ml - sl
def bb(close: np.ndarray, period: int = 14, std: float = 2.0):
mid = sma(close, period)
up = np.full_like(close, np.nan, dtype=np.float64)
lo = np.full_like(close, np.nan, dtype=np.float64)
for i in range(period - 1, len(close)):
s = np.std(close[i - period + 1:i + 1])
up[i] = mid[i] + std * s
lo[i] = mid[i] - std * s
return mid, up, lo
def sma(data: np.ndarray, period: int) -> np.ndarray:
r = np.full_like(data, np.nan, dtype=np.float64)
if len(data) < period:
return r
for i in range(period - 1, len(data)):
r[i] = np.mean(data[i - period + 1:i + 1])
return r
def atr(high: np.ndarray, low: np.ndarray, close: np.ndarray, period: int = 7) -> np.ndarray:
r = np.full_like(close, np.nan, dtype=np.float64)
if len(close) < period + 1:
return r
tr = np.maximum(high[1:] - low[1:],
np.maximum(np.abs(high[1:] - close[:-1]), np.abs(low[1:] - close[:-1])))
r[period] = np.mean(tr[:period])
for i in range(period + 1, len(close)):
r[i] = (r[i - 1] * (period - 1) + tr[i - 1]) / period
return r
# ============================================================
# Binance API wrapper. Trading uses the margin account only.
# ============================================================
class BinanceAPI:
def __init__(self, api_key: str, secret: str, proxy: str = "", cf_worker: str = ""):
base = {
"apiKey": api_key, "secret": secret,
"enableRateLimit": True, "timeout": 60000,
}
if proxy and not cf_worker:
base["proxies"] = {"http": proxy, "https": proxy}
logger.info(f"Using proxy: {proxy}")
self.spot = ccxt.binance({**base, "options": {"defaultType": "spot"}})
self.margin = ccxt.binance({**base, "options": {"defaultType": "margin"}})
self.futures = ccxt.binance({**base, "options": {"defaultType": "future"}})
if cf_worker:
self._use_cf_worker(cf_worker)
# Load markets with retries because the proxy or CF relay can be unstable.
for name, ex in [("spot", self.spot), ("margin", self.margin), ("futures", self.futures)]:
for attempt in range(5):
try:
ex.load_markets()
break
except Exception as e:
if attempt < 4:
wait = (attempt + 1) * 5
logger.warning(f"{name} load failed (attempt {attempt + 1}/5): {e}; retry in {wait}s")
time.sleep(wait)
else:
raise
self.market = self.spot.market(SYMBOL)
logger.info("API ready | margin trading mode")
# ---- Balance reads ----
def _use_cf_worker(self, cf_worker: str):
cf_worker = cf_worker.rstrip("/")
for ex in [self.spot, self.margin, self.futures]:
for key, old in list(ex.urls.get("api", {}).items()):
parsed = urlparse(old)
ex.urls["api"][key] = cf_worker + parsed.path
logger.info(f"Using CF Worker relay: {cf_worker}")
def _is_asset(self, key: str, info) -> bool:
if key in META_KEYS:
return False
if not isinstance(info, dict):
return False
return "free" in info or "total" in info
def get_margin_usdt(self) -> float:
"""Available USDT in margin account."""
try:
b = self.margin.fetch_balance()
info = b.get("USDT")
if isinstance(info, dict):
free = float(info.get("free", 0) or 0)
total = float(info.get("total", 0) or 0)
used = float(info.get("used", 0) or 0)
logger.info(f"[DEBUG] margin USDT: free={free:.4f} total={total:.4f} used={used:.4f}")
result = free if free > 0 else total
if result > 0:
return result
except Exception:
pass
return self.get_margin_total_usdt()
def get_margin_total_usdt(self) -> float:
"""Total USDT in margin account, including used margin."""
try:
b = self.margin.fetch_balance()
info = b.get("USDT")
if isinstance(info, dict):
return float(info.get("total", 0) or 0)
except Exception:
pass
return 0.0
def get_margin_sol(self) -> float:
try:
b = self.margin.fetch_balance()
info = b.get("SOL")
if isinstance(info, dict):
return float(info.get("total", 0) or 0)
except Exception:
pass
return 0.0
def get_margin_asset_total(self, asset: str) -> float:
try:
b = self.margin.fetch_balance()
info = b.get(asset)
if isinstance(info, dict):
return float(info.get("total", 0) or 0)
except Exception:
pass
return 0.0
def get_margin_asset_borrowed(self, asset: str) -> float:
try:
b = self.margin.fetch_balance()
info = b.get(asset)
if isinstance(info, dict):
return float(info.get("debt", info.get("borrowed", 0)) or 0)
except Exception:
pass
return 0.0
def get_margin_sol_borrowed(self) -> float:
try:
b = self.margin.fetch_balance()
info = b.get("SOL")
if isinstance(info, dict):
return float(info.get("debt", info.get("borrowed", 0)) or 0)
except Exception:
pass
return 0.0
def get_margin_equity(self) -> float:
"""Margin account net equity in USDT."""
try:
b = self.margin.fetch_balance()
total = 0.0
for asset, info in b.items():
if not self._is_asset(asset, info):
continue
asset_total = float(info.get("total", 0) or 0)
borrowed = float(info.get("debt", info.get("borrowed", 0)) or 0)
net = asset_total - borrowed
if abs(net) < 0.0001:
continue
if asset == "USDT":
total += net
else:
try:
t = self.spot.fetch_ticker(f"{asset}/USDT")
total += net * float(t["last"])
except Exception:
pass
return total
except Exception:
return 0.0
def get_margin_level(self) -> float:
"""Margin level percentage. Higher is safer."""
try:
b = self.margin.fetch_balance()
total_asset = 0.0
total_debt = 0.0
for asset, info in b.items():
if not self._is_asset(asset, info):
continue
asset_total = float(info.get("total", 0) or 0)
borrowed = float(info.get("debt", info.get("borrowed", 0)) or 0)
if asset == "USDT":
total_asset += asset_total
total_debt += borrowed
else:
try:
t = self.spot.fetch_ticker(f"{asset}/USDT")
price = float(t["last"])
total_asset += asset_total * price
total_debt += borrowed * price
except Exception:
pass
if total_debt <= 0:
return 999.0
return (total_asset / total_debt) * 100.0
except Exception:
return 0.0
def get_all_snapshot(self) -> dict:
"""Balance snapshot for display only."""
snap = {"funding": 0.0, "spot": 0.0, "margin": 0.0, "futures": 0.0}
# Margin account.
try:
snap["margin"] = self.get_margin_total_usdt()
except Exception:
pass
# Spot account.
try:
b = self.spot.fetch_balance()
snap["spot"] = float((b.get("USDT") or {}).get("total", 0) or 0)
except Exception:
pass
# Funding account.
try:
resp = self.spot.sapiGetAssetGetFundingAsset()
for item in resp:
if item.get("asset") == "USDT":
snap["funding"] = float(item.get("free", 0) or 0)
except Exception:
pass
# Futures account.
try:
b = self.futures.fetch_balance()
info = b.get("USDT")
if isinstance(info, dict):
snap["futures"] = float(info.get("total", info.get("free", 0)) or 0)
except Exception:
pass
return snap
# ---- Trading ----
def fetch_klines(self, limit: int = 100, timeframe: str = TIMEFRAME) -> dict:
ohlcv = self.spot.fetch_ohlcv(SYMBOL, timeframe=timeframe, limit=limit)
return {
"close": np.array([c[4] for c in ohlcv], dtype=np.float64),
"open": np.array([c[1] for c in ohlcv], dtype=np.float64),
"high": np.array([c[2] for c in ohlcv], dtype=np.float64),
"low": np.array([c[3] for c in ohlcv], dtype=np.float64),
"volume": np.array([c[5] for c in ohlcv], dtype=np.float64),
"timestamp": [c[0] for c in ohlcv],
}
def fetch_klines_multi(self, limit: int = 100) -> dict:
result = {}
for tf in [TIMEFRAME, MTF_15M, MTF_1H]:
try:
result[tf] = self.fetch_klines(limit=limit, timeframe=tf)
except Exception as e:
logger.warning(f"MTF fetch {tf} failed: {e}")
result[tf] = None
return result
def fetch_ticker(self):
return self.spot.fetch_ticker(SYMBOL)
@staticmethod
def extract_fill_price(order: dict, fallback: float) -> float:
"""Extract average fill price from Binance order response."""
cum_qty = float(order.get("cummulativeQuoteQty", 0) or 0)
exe_qty = float(order.get("executedQty", 0) or 0)
if exe_qty > 0 and cum_qty > 0:
return cum_qty / exe_qty
# Native Binance fills array.
fills = order.get("fills", [])
if fills and isinstance(fills, list) and len(fills) > 0:
prices = [float(f.get("price", 0) or 0) for f in fills]
if prices and sum(prices) > 0:
return sum(prices) / len(prices)
# Standard ccxt fields.
for key in ["average", "price"]:
v = order.get(key)
if v is not None and float(v) > 0:
return float(v)
return fallback
def round_amount(self, amount: float) -> float:
step = float(self.market.get("precision", {}).get("amount") or 0.001)
if step <= 0:
step = 0.001
decimals = max(0, int(round(-np.log10(step)))) if step < 1 else 0
floored = np.floor(max(0.0, float(amount)) / step) * step
return max(0, round(float(floored), decimals))
def _margin_order(self, side: str, amount: float, effect_types: list = None,
allow_balance_fallback: bool = True,
allow_ccxt_fallback: bool = True) -> dict:
"""Place a native margin order, trying multiple sideEffectType values."""
qty = self.round_amount(amount)
base = {"symbol": "SOLUSDT", "side": side, "type": "MARKET", "quantity": str(qty)}
if qty <= 0:
raise ValueError(f"invalid order amount: {amount}")
# Buy/sell use different side effect fallback sequences.
if effect_types is None:
if side == "BUY":
effect_types = ["NO_SIDE_EFFECT", "MARGIN_BUY"]
else:
effect_types = ["AUTO_REPAY", "AUTO_BORROW_REPAY", "NO_SIDE_EFFECT"]
last_err = None
for effect in effect_types:
params = {**base, "sideEffectType": effect}
for method_name in ["sapiPostMarginOrder", "sapi_post_margin_order"]:
fn = getattr(self.margin, method_name, None)
if not fn:
continue
try:
o = fn(params)
logger.info(f"order succeeded ({method_name} sideEffect={effect}): {qty} SOL")
return o
except Exception as e:
last_err = e
err_str = str(e)[:120]
logger.warning(f" {effect} failed: {err_str}")
if "insufficient" not in str(e).lower():
break
# Fallback to actual account balance when close quantity is slightly off.
if allow_balance_fallback and side == "SELL":
actual_sol = self.get_margin_sol()
if 0 < actual_sol < qty:
actual_qty = self.round_amount(actual_sol)
if actual_qty <= 0 or actual_qty >= qty:
raise last_err or ValueError(f"actual SOL balance is insufficient: {actual_sol}")
logger.warning(f"position qty {qty} differs from actual SOL {actual_sol}; using {actual_qty}")
return self._margin_order(side, actual_qty, effect_types, allow_balance_fallback=False,
allow_ccxt_fallback=allow_ccxt_fallback)
elif allow_balance_fallback and side == "BUY":
actual_usdt = self.get_margin_usdt()
if actual_usdt > 0:
ticker = self.fetch_ticker()
alt_qty = self.round_amount(actual_usdt * 0.99 / ticker["last"])
if 0 < alt_qty < qty:
logger.warning(f"try reduced buy amount: {alt_qty}")
return self._margin_order(side, alt_qty, effect_types, allow_balance_fallback=False,
allow_ccxt_fallback=allow_ccxt_fallback)
if not allow_ccxt_fallback:
raise last_err or RuntimeError(f"order failed: {side} {qty}")
# fallback2: ccxt create_order
logger.warning(f"all sideEffectType attempts failed; fallback to ccxt. last_err: {str(last_err)[:200] if last_err else 'none'}")
o = self.margin.create_order(SYMBOL, "market", side.lower(), qty)
fill = o.get("average", o.get("price"))
logger.info(f"ccxt order filled: {qty} SOL @ {fill}")
return o
def margin_order_ioc(self, side: str, amount: float, limit_price: float) -> dict:
qty = self.round_amount(amount)
if qty <= 0:
raise ValueError(f"invalid IOC order amount: {amount}")
side_l = str(side).lower()
if side_l not in {"buy", "sell"}:
raise ValueError(f"invalid IOC side: {side}")
limit_price = float(limit_price or 0)
if limit_price <= 0:
raise ValueError(f"invalid IOC limit price: {limit_price}")
effects = ["NO_SIDE_EFFECT", "MARGIN_BUY"] if side_l == "buy" else ["AUTO_BORROW_REPAY", "NO_SIDE_EFFECT"]
last_err = None
for effect in effects:
try:
params = {"timeInForce": "GTC", "sideEffectType": effect}
logger.info(f">>> margin simulated IOC {side_l} {qty} SOL @ {limit_price:.4f} sideEffect={effect}")
order = self.margin.create_order(SYMBOL, "limit", side_l, qty, limit_price, params)
time.sleep(1)
fetched = order
order_id = order.get("id") or order.get("orderId")
if order_id:
try:
fetched = self.margin.fetch_order(str(order_id), SYMBOL)
except Exception as e:
logger.warning(f"IOC fetch order failed: {e}")
filled = float(fetched.get("filled", fetched.get("executedQty", 0)) or 0)
remaining = float(fetched.get("remaining", max(0.0, qty - filled)) or 0)
if remaining > 0.000001 and order_id:
try:
self.margin.cancel_order(str(order_id), SYMBOL)
logger.info(f"IOC cancelled remaining {remaining:.6f} SOL")
except Exception as e:
logger.warning(f"IOC cancel remaining failed: {e}")
if filled <= 0:
raise RuntimeError("IOC order not filled")
fetched.setdefault("executedQty", filled)
logger.info(f"IOC filled {filled:.6f}/{qty:.6f} SOL")
return fetched
except Exception as e:
last_err = e
logger.warning(f"IOC {side_l} failed ({effect}): {str(e)[:160]}")
raise last_err or RuntimeError("IOC order failed")
def margin_buy(self, amount: float) -> dict:
logger.info(f">>> margin buy {amount} SOL")
return self._margin_order("BUY", amount)
def margin_sell(self, amount: float) -> dict:
logger.info(f">>> margin sell {amount} SOL")
return self._margin_order("SELL", amount)
def close_long(self, amount: float) -> dict:
logger.info(f">>> close long by selling {amount} SOL")
# Close long using held SOL only.
actual_sol = self.get_margin_sol()
qty = min(amount, actual_sol)
return self._margin_order("SELL", qty, effect_types=["AUTO_REPAY", "NO_SIDE_EFFECT"],
allow_balance_fallback=True, allow_ccxt_fallback=False)
def close_short(self, amount: float) -> dict:
logger.info(f">>> close short by buying {amount} SOL")
# Close short by buying back and repaying borrowed SOL.
return self._margin_order("BUY", amount, effect_types=["AUTO_REPAY", "NO_SIDE_EFFECT", "MARGIN_BUY"],
allow_balance_fallback=True, allow_ccxt_fallback=False)
def _repay_asset(self, asset: str, amount: float) -> bool:
amount = float(amount or 0)
if amount <= 0:
return False
if asset == "SOL":
amt = self.round_amount(amount)
else:
amt = round(amount, 6)
if amt <= 0:
return False
params_new = {"asset": asset, "isIsolated": "FALSE", "amount": str(amt), "type": "REPAY"}
params_old = {"asset": asset, "amount": str(amt)}
for method_name, params in [
("sapiPostMarginBorrowRepay", params_new),
("sapi_post_margin_borrow_repay", params_new),
("sapiPostMarginRepay", params_old),
("sapi_post_margin_repay", params_old),
]:
fn = getattr(self.margin, method_name, None)
if not fn:
continue
try:
fn(params)
logger.info(f"manual repay succeeded: {asset} {amt}")
return True
except Exception as e:
logger.warning(f"manual repay failed ({method_name} {asset} {amt}): {str(e)[:160]}")
return False
def repay_available_debts(self):
# Executions and auto-repay can lag briefly; wait before reading balances.
time.sleep(0.5)
for asset in ["SOL", "USDT"]:
debt = self.get_margin_asset_borrowed(asset)
total = self.get_margin_asset_total(asset)
repay_amt = min(debt, total)
if repay_amt > 0.000001:
self._repay_asset(asset, repay_amt)
# ============================================================
# Strategy engine.
# ============================================================
class StrategyEngine:
def __init__(self, runtime: RuntimeConfig = None):
self.runtime = runtime or build_runtime_config({})
self.features = self.runtime.features
def compute(self, klines: dict) -> dict:
c, h, l, v = klines["close"], klines["high"], klines["low"], klines["volume"]
ml, sl, hist = macd(c, MACD_FAST, MACD_SLOW, MACD_SIG)
bm, bu, bl = bb(c, BB_PERIOD, BB_STD)
bb_width = np.divide(
bu - bl, bm,
out=np.full_like(bm, np.nan, dtype=np.float64),
where=~np.isnan(bm) & (bm != 0),
)
return {
"ema_f": ema(c, EMA_FAST), "ema_m": ema(c, EMA_MID),
"ema_s": ema(c, EMA_SLOW), "rsi": rsi(c, RSI_PERIOD),
"macd_l": ml, "sig_l": sl, "hist": hist,
"bb_m": bm, "bb_u": bu, "bb_l": bl, "bb_width": bb_width,
"atr": atr(h, l, c, ATR_PERIOD),
"vol_ma": sma(v, VOL_MA),
}
@staticmethod
def last(arr: np.ndarray, off: int = 0) -> float:
v = arr[~np.isnan(arr)]
return v[-1 - off] if len(v) > off else np.nan
@staticmethod
def prev(arr: np.ndarray, off: int = 1) -> float:
return StrategyEngine.last(arr, off)
def mtf_trend(self, klines_15m, klines_1h) -> dict:
def one_tf(klines):