-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathbot.py
More file actions
2967 lines (2635 loc) · 112 KB
/
bot.py
File metadata and controls
2967 lines (2635 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
DeepSeek Multi-Asset Paper Trading Bot
Uses Binance API for market data and OpenRouter API for DeepSeek Chat V3.1 trading decisions
"""
from __future__ import annotations
import os
import re
import time
import json
import logging
import csv
from datetime import datetime, timezone
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
from decimal import Decimal
from pathlib import Path
import numpy as np
import pandas as pd
import requests
from requests.exceptions import RequestException, Timeout
from binance.client import Client
from dotenv import load_dotenv
from colorama import Fore, Style, init as colorama_init
from hyperliquid_client import HyperliquidTradingClient
colorama_init(autoreset=True)
BASE_DIR = Path(__file__).resolve().parent
DOTENV_PATH = BASE_DIR / ".env"
if DOTENV_PATH.exists():
dotenv_loaded = load_dotenv(dotenv_path=DOTENV_PATH, override=True)
else:
dotenv_loaded = load_dotenv(override=True)
DEFAULT_DATA_DIR = BASE_DIR / "data"
DATA_DIR = Path(os.getenv("TRADEBOT_DATA_DIR", str(DEFAULT_DATA_DIR))).expanduser()
DATA_DIR.mkdir(parents=True, exist_ok=True)
EARLY_ENV_WARNINGS: List[str] = []
def _parse_bool_env(value: Optional[str], *, default: bool = False) -> bool:
"""Convert environment string to bool with sensible defaults."""
if value is None:
return default
normalized = value.strip().lower()
if normalized in {"1", "true", "yes", "on"}:
return True
if normalized in {"0", "false", "no", "off"}:
return False
return default
def _parse_float_env(value: Optional[str], *, default: float) -> float:
"""Convert environment string to float with fallback and logging."""
if value is None or value == "":
return default
try:
return float(value)
except (TypeError, ValueError):
EARLY_ENV_WARNINGS.append(
f"Invalid float environment value '{value}'; using default {default:.2f}"
)
return default
def _parse_int_env(value: Optional[str], *, default: int) -> int:
"""Convert environment string to int with fallback and logging."""
if value is None or value == "":
return default
try:
return int(value)
except (TypeError, ValueError):
EARLY_ENV_WARNINGS.append(
f"Invalid int environment value '{value}'; using default {default}"
)
return default
def _parse_thinking_env(value: Optional[str]) -> Optional[Any]:
"""Parse LLM thinking budget/configuration from environment."""
if value is None:
return None
raw = value.strip()
if not raw:
return None
try:
return json.loads(raw)
except json.JSONDecodeError:
pass
try:
return int(raw)
except (TypeError, ValueError):
pass
try:
return float(raw)
except (TypeError, ValueError):
pass
return raw
# ───────────────────────── CONFIG ─────────────────────────
API_KEY = os.getenv("BN_API_KEY", "")
API_SECRET = os.getenv("BN_SECRET", "")
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "")
TELEGRAM_SIGNALS_CHAT_ID = os.getenv("TELEGRAM_SIGNALS_CHAT_ID", "")
HYPERLIQUID_LIVE_TRADING = _parse_bool_env(
os.getenv("HYPERLIQUID_LIVE_TRADING"),
default=False,
)
HYPERLIQUID_WALLET_ADDRESS = os.getenv("HYPERLIQUID_WALLET_ADDRESS", "")
HYPERLIQUID_PRIVATE_KEY = os.getenv("HYPERLIQUID_PRIVATE_KEY", "")
PAPER_START_CAPITAL = _parse_float_env(
os.getenv("PAPER_START_CAPITAL"),
default=10000.0,
)
HYPERLIQUID_CAPITAL = _parse_float_env(
os.getenv("HYPERLIQUID_CAPITAL"),
default=500.0,
)
START_CAPITAL = HYPERLIQUID_CAPITAL if HYPERLIQUID_LIVE_TRADING else PAPER_START_CAPITAL
# Trading symbols to monitor
SYMBOLS = ["ETHUSDT", "SOLUSDT", "XRPUSDT", "BTCUSDT", "DOGEUSDT", "BNBUSDT"]
SYMBOL_TO_COIN = {
"ETHUSDT": "ETH",
"SOLUSDT": "SOL",
"XRPUSDT": "XRP",
"BTCUSDT": "BTC",
"DOGEUSDT": "DOGE",
"BNBUSDT": "BNB"
}
COIN_TO_SYMBOL = {coin: symbol for symbol, coin in SYMBOL_TO_COIN.items()}
DEFAULT_TRADING_RULES_PROMPT = """
You are a top level crypto trader focused on multiplying the account while safeguarding capital. Always apply these core rules:
Most Important Rules for Crypto Traders
Capital preservation is the foundation of successful crypto trading—your primary goal is to protect what you have so you can continue trading and growing.
Never Risk More Than 1-2% Per Trade
- Treat the 1% rule as non-negotiable; never risk more than 1-2% of total capital on a single trade.
- Survive losing streaks with enough capital to recover.
Use Stop-Loss Orders on Every Trade
- Define exit points before entering any position.
- Stop-loss orders are mandatory safeguards against emotional decisions.
Follow the Trend—Don't Fight the Market
- Buy rising coins and sell falling ones; the market is always right.
- Wait for confirmation before committing capital.
Stay Inactive Most of the Time
- Trade only when high-probability setups emerge.
- Avoid overtrading; patience and discipline preserve capital.
Cut Losses Quickly and Let Profits Run
- Close losing trades decisively; exit weak performers without hesitation.
- Let winning trades develop and grow when they show early profit.
Maintain a Written Trading Plan
- Know entry, exit, and profit targets before executing.
- Consistently follow the plan to keep emotions in check.
Control Leverage and Position Sizing
- Use leverage responsibly; ensure even a worst-case loss stays within the 1-2% risk cap.
- Proper sizing is central to risk management.
Focus on Small Consistent Wins
- Prioritize steady gains over chasing moonshots.
- Incremental growth compounds reliably and is easier to manage.
Think in Probabilities, Not Predictions
- Treat trading like a probability game with positive expectancy over many trades.
- Shift mindset from needing to be right to managing outcomes.
Stay Informed but Trade Less
- Track market-moving news but trade only when indicators align and risk-reward is favorable.
""".strip()
SYSTEM_PROMPT_SOURCE: Dict[str, Any] = {"type": "default"}
def _load_system_prompt() -> str:
"""Load system prompt from env variables or fall back to default."""
global SYSTEM_PROMPT_SOURCE
prompt_file = os.getenv("TRADEBOT_SYSTEM_PROMPT_FILE")
if prompt_file:
path = Path(prompt_file).expanduser()
if not path.is_absolute():
path = (BASE_DIR / path).resolve()
try:
if path.exists():
SYSTEM_PROMPT_SOURCE = {"type": "file", "path": str(path)}
return path.read_text(encoding="utf-8").strip()
EARLY_ENV_WARNINGS.append(
f"System prompt file '{path}' not found; using default prompt."
)
except Exception as exc:
EARLY_ENV_WARNINGS.append(
f"Failed to read system prompt file '{path}': {exc}; using default prompt."
)
prompt_env = os.getenv("TRADEBOT_SYSTEM_PROMPT")
if prompt_env:
SYSTEM_PROMPT_SOURCE = {"type": "env"}
return prompt_env.strip()
SYSTEM_PROMPT_SOURCE = {"type": "default"}
return DEFAULT_TRADING_RULES_PROMPT
def describe_system_prompt_source() -> str:
"""Return human-readable description of the active system prompt."""
source_type = SYSTEM_PROMPT_SOURCE.get("type", "default")
if source_type == "file":
return f"file:{SYSTEM_PROMPT_SOURCE.get('path', '?')}"
if source_type == "env":
return "env:TRADEBOT_SYSTEM_PROMPT"
return "default prompt"
TRADING_RULES_PROMPT = _load_system_prompt()
DEFAULT_INTERVAL = "15m"
_INTERVAL_TO_SECONDS = {
"1m": 60,
"3m": 180,
"5m": 300,
"15m": 900,
"30m": 1800,
"1h": 3600,
"2h": 7200,
"4h": 14400,
"6h": 21600,
"8h": 28800,
"12h": 43200,
"1d": 86400,
}
def _load_trade_interval(default: str = DEFAULT_INTERVAL) -> str:
"""Resolve trade interval from environment."""
raw = os.getenv("TRADEBOT_INTERVAL")
if raw:
candidate = raw.strip().lower()
if candidate in _INTERVAL_TO_SECONDS:
return candidate
EARLY_ENV_WARNINGS.append(
f"Unsupported TRADEBOT_INTERVAL '{raw}'; using default {default}."
)
return default
INTERVAL = _load_trade_interval()
CHECK_INTERVAL = _INTERVAL_TO_SECONDS[INTERVAL]
DEFAULT_RISK_FREE_RATE = 0.0 # Annualized baseline for Sortino ratio calculations
DEFAULT_LLM_MODEL = "deepseek/deepseek-chat-v3.1"
def _load_llm_model_name() -> str:
raw = os.getenv("TRADEBOT_LLM_MODEL", DEFAULT_LLM_MODEL)
if not raw:
return DEFAULT_LLM_MODEL
value = raw.strip()
return value or DEFAULT_LLM_MODEL
def _load_llm_temperature() -> float:
return _parse_float_env(
os.getenv("TRADEBOT_LLM_TEMPERATURE"),
default=0.7,
)
def _load_llm_max_tokens() -> int:
return _parse_int_env(
os.getenv("TRADEBOT_LLM_MAX_TOKENS"),
default=4000,
)
def refresh_llm_configuration_from_env() -> None:
"""Reload LLM-related runtime settings from environment variables."""
global LLM_MODEL_NAME, LLM_TEMPERATURE, LLM_MAX_TOKENS, LLM_THINKING_PARAM, TRADING_RULES_PROMPT
LLM_MODEL_NAME = _load_llm_model_name()
LLM_TEMPERATURE = _load_llm_temperature()
LLM_MAX_TOKENS = _load_llm_max_tokens()
LLM_THINKING_PARAM = _parse_thinking_env(os.getenv("TRADEBOT_LLM_THINKING"))
TRADING_RULES_PROMPT = _load_system_prompt()
def log_system_prompt_info(prefix: str = "System prompt in use") -> None:
"""Log the current system prompt configuration."""
description = describe_system_prompt_source()
logging.info("%s: %s", prefix, description)
LLM_MODEL_NAME = _load_llm_model_name()
LLM_TEMPERATURE = _load_llm_temperature()
LLM_MAX_TOKENS = _load_llm_max_tokens()
LLM_THINKING_PARAM = _parse_thinking_env(os.getenv("TRADEBOT_LLM_THINKING"))
# Indicator settings
EMA_LEN = 20
RSI_LEN = 14
MACD_FAST = 12
MACD_SLOW = 26
MACD_SIGNAL = 9
# Binance fee structure (as decimals)
MAKER_FEE_RATE = 0.0 # 0.0000%
TAKER_FEE_RATE = 0.000275 # 0.0275%
# ───────────────────────────────────────────────────────────
logging.basicConfig(
format="%(asctime)s | %(levelname)s | %(message)s",
level=logging.INFO
)
for warning_msg in EARLY_ENV_WARNINGS:
logging.warning(warning_msg)
EARLY_ENV_WARNINGS.clear()
def _resolve_risk_free_rate() -> float:
"""Determine the annualized risk-free rate used in Sortino calculations."""
env_value = os.getenv("SORTINO_RISK_FREE_RATE")
if env_value is None:
env_value = os.getenv("RISK_FREE_RATE")
if env_value is None:
return DEFAULT_RISK_FREE_RATE
try:
return float(env_value)
except (TypeError, ValueError):
logging.warning(
"Invalid SORTINO_RISK_FREE_RATE/RISK_FREE_RATE value '%s'; using default %.4f",
env_value,
DEFAULT_RISK_FREE_RATE,
)
return DEFAULT_RISK_FREE_RATE
RISK_FREE_RATE = _resolve_risk_free_rate()
if not dotenv_loaded:
logging.warning(f"No .env file found at {DOTENV_PATH}; falling back to system environment variables.")
if OPENROUTER_API_KEY:
masked_key = (
OPENROUTER_API_KEY
if len(OPENROUTER_API_KEY) <= 12
else f"{OPENROUTER_API_KEY[:6]}...{OPENROUTER_API_KEY[-4:]}"
)
logging.info(
"OpenRouter API key detected: %s (length %d)",
masked_key,
len(OPENROUTER_API_KEY),
)
else:
logging.error("OPENROUTER_API_KEY not found; please check your .env file.")
client: Optional[Client] = None
try:
hyperliquid_trader = HyperliquidTradingClient(
live_mode=HYPERLIQUID_LIVE_TRADING,
wallet_address=HYPERLIQUID_WALLET_ADDRESS,
secret_key=HYPERLIQUID_PRIVATE_KEY,
)
except Exception as exc:
logging.critical("Hyperliquid live trading initialization failed: %s", exc)
raise SystemExit(1) from exc
def get_binance_client() -> Optional[Client]:
"""Return a connected Binance client or None if initialization failed."""
global client
if client is not None:
return client
if not API_KEY or not API_SECRET:
logging.error("BN_API_KEY and/or BN_SECRET missing; unable to initialize Binance client.")
return None
try:
logging.info("Attempting to initialize Binance client...")
client = Client(API_KEY, API_SECRET, testnet=False)
logging.info("Binance client initialized successfully.")
except Timeout as exc:
logging.warning(
"Timed out while connecting to Binance API: %s. Will retry automatically without exiting.",
exc,
)
client = None
except RequestException as exc:
logging.error(
"Network error while connecting to Binance API: %s. Will retry automatically.",
exc,
)
client = None
except Exception as exc:
logging.error(
"Unexpected error while initializing Binance client: %s",
exc,
exc_info=True,
)
client = None
return client
# ──────────────────────── GLOBAL STATE ─────────────────────
balance: float = START_CAPITAL
positions: Dict[str, Dict[str, Any]] = {} # coin -> position info
trade_history: List[Dict[str, Any]] = []
def _default_time_provider() -> datetime:
"""Return current UTC time; overridable for testing/backtests."""
return datetime.now(timezone.utc)
_current_time_provider: Callable[[], datetime] = _default_time_provider
def get_current_time() -> datetime:
"""Return the current time from the active provider."""
return _current_time_provider()
def set_time_provider(provider: Optional[Callable[[], datetime]]) -> None:
"""Override the time provider; pass None to restore wall-clock time."""
global _current_time_provider
_current_time_provider = provider or _default_time_provider
BOT_START_TIME = get_current_time()
invocation_count: int = 0
iteration_counter: int = 0
ANSI_ESCAPE_RE = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
current_iteration_messages: List[str] = []
equity_history: List[float] = []
# CSV files
STATE_CSV = DATA_DIR / "portfolio_state.csv"
STATE_JSON = DATA_DIR / "portfolio_state.json"
TRADES_CSV = DATA_DIR / "trade_history.csv"
DECISIONS_CSV = DATA_DIR / "ai_decisions.csv"
MESSAGES_CSV = DATA_DIR / "ai_messages.csv"
STATE_COLUMNS = [
'timestamp',
'total_balance',
'total_equity',
'total_return_pct',
'num_positions',
'position_details',
'total_margin',
'net_unrealized_pnl',
'btc_price',
]
last_btc_price: Optional[float] = None
# ───────────────────────── CSV LOGGING ──────────────────────
def init_csv_files() -> None:
"""Initialize CSV files with headers."""
if not STATE_CSV.exists():
with open(STATE_CSV, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(STATE_COLUMNS)
else:
try:
df = pd.read_csv(STATE_CSV)
except Exception as exc:
logging.warning("Unable to load %s for schema check: %s", STATE_CSV, exc)
else:
if list(df.columns) != STATE_COLUMNS:
for column in STATE_COLUMNS:
if column not in df.columns:
df[column] = np.nan
try:
df = df[STATE_COLUMNS]
except KeyError:
# Fall back to writing header only if severe mismatch
df = pd.DataFrame(columns=STATE_COLUMNS)
df.to_csv(STATE_CSV, index=False)
if not TRADES_CSV.exists():
with open(TRADES_CSV, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow([
'timestamp', 'coin', 'action', 'side', 'quantity', 'price',
'profit_target', 'stop_loss', 'leverage', 'confidence',
'pnl', 'balance_after', 'reason'
])
if not DECISIONS_CSV.exists():
with open(DECISIONS_CSV, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow([
'timestamp', 'coin', 'signal', 'reasoning', 'confidence'
])
if not MESSAGES_CSV.exists():
with open(MESSAGES_CSV, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow([
'timestamp', 'direction', 'role', 'content', 'metadata'
])
def get_btc_benchmark_price() -> Optional[float]:
"""Fetch the current BTC/USDT price for benchmarking."""
global last_btc_price
data = fetch_market_data("BTCUSDT")
if data and "price" in data:
try:
last_btc_price = float(data["price"])
except (TypeError, ValueError):
logging.debug("Received non-numeric BTC price: %s", data["price"])
return last_btc_price
def log_portfolio_state() -> None:
"""Log current portfolio state."""
total_equity = calculate_total_equity()
total_return = ((total_equity - START_CAPITAL) / START_CAPITAL) * 100
total_margin = calculate_total_margin()
net_unrealized = total_equity - balance - total_margin
position_details = "; ".join([
f"{coin}:{pos['side']}:{pos['quantity']:.4f}@{pos['entry_price']:.4f}"
for coin, pos in positions.items()
]) if positions else "No positions"
btc_price = get_btc_benchmark_price()
btc_price_str = f"{btc_price:.2f}" if btc_price is not None else ""
with open(STATE_CSV, 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([
get_current_time().isoformat(),
f"{balance:.2f}",
f"{total_equity:.2f}",
f"{total_return:.2f}",
len(positions),
position_details,
f"{total_margin:.2f}",
f"{net_unrealized:.2f}",
btc_price_str,
])
def log_trade(coin: str, action: str, details: Dict[str, Any]) -> None:
"""Log trade execution."""
with open(TRADES_CSV, 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([
get_current_time().isoformat(),
coin,
action,
details.get('side', ''),
details.get('quantity', 0),
details.get('price', 0),
details.get('profit_target', 0),
details.get('stop_loss', 0),
details.get('leverage', 1),
details.get('confidence', 0),
details.get('pnl', 0),
balance,
details.get('reason', '')
])
def log_ai_decision(coin: str, signal: str, reasoning: str, confidence: float) -> None:
"""Log AI decision."""
with open(DECISIONS_CSV, 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([
get_current_time().isoformat(),
coin,
signal,
reasoning,
confidence
])
def log_ai_message(direction: str, role: str, content: str, metadata: Optional[Dict[str, Any]] = None) -> None:
"""Log raw messages exchanged with the AI provider."""
with open(MESSAGES_CSV, 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([
get_current_time().isoformat(),
direction,
role,
content,
json.dumps(metadata) if metadata else ""
])
def strip_ansi_codes(text: str) -> str:
"""Remove ANSI color codes so Telegram receives plain text."""
return ANSI_ESCAPE_RE.sub("", text)
def escape_markdown(text: str) -> str:
"""Escape characters that have special meaning in Telegram Markdown."""
if not text:
return text
specials = r"_*[]()~`>#+-=|{}.!\\"
return "".join(f"\\{char}" if char in specials else char for char in text)
def record_iteration_message(text: str) -> None:
"""Record console output for this iteration to share via Telegram."""
if current_iteration_messages is not None:
current_iteration_messages.append(strip_ansi_codes(text).rstrip())
def send_telegram_message(text: str, chat_id: Optional[str] = None, parse_mode: Optional[str] = "Markdown") -> None:
"""Send a notification message to Telegram if credentials are configured.
If `chat_id` is provided it will be used; otherwise `TELEGRAM_CHAT_ID` is used.
This allows sending different message types to a dedicated signals group (`TELEGRAM_SIGNALS_CHAT_ID`).
"""
effective_chat = (chat_id or TELEGRAM_CHAT_ID or "").strip()
if not TELEGRAM_BOT_TOKEN or not effective_chat:
return
try:
payload = {
"chat_id": effective_chat,
"text": text,
}
if parse_mode:
payload["parse_mode"] = parse_mode
response = requests.post(
f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage",
json=payload,
timeout=10,
)
if response.status_code == 200:
return
response_text_lower = response.text.lower()
logging.warning(
"Telegram notification failed (%s): %s",
response.status_code,
response.text,
)
if (
response.status_code == 400
and "can't parse entities" in response_text_lower
and parse_mode
):
fallback_payload = {
"chat_id": effective_chat,
"text": strip_ansi_codes(text),
}
try:
fallback_response = requests.post(
f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage",
json=fallback_payload,
timeout=10,
)
if fallback_response.status_code != 200:
logging.warning(
"Telegram fallback notification failed (%s): %s",
fallback_response.status_code,
fallback_response.text,
)
except Exception as fallback_exc:
logging.error("Fallback Telegram message failed: %s", fallback_exc)
except Exception as exc:
logging.error("Error sending Telegram message: %s", exc)
def notify_error(
message: str,
metadata: Optional[Dict[str, Any]] = None,
*,
log_error: bool = True,
) -> None:
"""Log an error and forward a brief description to Telegram."""
if log_error:
logging.error(message)
log_ai_message(
direction="error",
role="system",
content=message,
metadata=metadata,
)
send_telegram_message(message, parse_mode=None)
# ───────────────────────── STATE MGMT ───────────────────────
def load_state() -> None:
"""Load persisted balance and positions if available."""
global balance, positions, iteration_counter
if not STATE_JSON.exists():
logging.info("No existing state file found; starting fresh.")
return
try:
with open(STATE_JSON, "r") as f:
data = json.load(f)
balance = float(data.get("balance", START_CAPITAL))
try:
iteration_counter = int(data.get("iteration", 0))
except (TypeError, ValueError):
iteration_counter = 0
loaded_positions = data.get("positions", {})
if isinstance(loaded_positions, dict):
restored_positions: Dict[str, Dict[str, Any]] = {}
for coin, pos in loaded_positions.items():
if not isinstance(pos, dict):
continue
fees_paid_raw = pos.get("fees_paid", pos.get("entry_fee", 0.0))
if fees_paid_raw is None:
fees_paid_value = 0.0
else:
try:
fees_paid_value = float(fees_paid_raw)
except (TypeError, ValueError):
fees_paid_value = 0.0
risk_usd_raw = pos.get("risk_usd", 0.0)
try:
risk_usd_value = float(risk_usd_raw)
except (TypeError, ValueError):
risk_usd_value = 0.0
initial_stop_raw = pos.get("initial_stop", pos.get("stop_loss", 0.0))
try:
initial_stop_value = float(initial_stop_raw)
except (TypeError, ValueError):
initial_stop_value = float(pos.get("stop_loss", 0.0))
initial_risk_per_unit_raw = pos.get("initial_risk_per_unit", 0.0)
try:
initial_risk_per_unit_value = float(initial_risk_per_unit_raw)
except (TypeError, ValueError):
initial_risk_per_unit_value = 0.0
initial_risk_usd_raw = pos.get("initial_risk_usd", risk_usd_value)
try:
initial_risk_usd_value = float(initial_risk_usd_raw)
except (TypeError, ValueError):
initial_risk_usd_value = risk_usd_value
trail_history_raw = pos.get("trail_history", [])
trail_history_value = [
hist for hist in trail_history_raw
if isinstance(hist, dict)
]
fee_rate_raw = pos.get("fee_rate", TAKER_FEE_RATE)
try:
fee_rate_value = float(fee_rate_raw)
except (TypeError, ValueError):
fee_rate_value = TAKER_FEE_RATE
restored_positions[coin] = {
"side": pos.get("side", "long"),
"quantity": float(pos.get("quantity", 0.0)),
"entry_price": float(pos.get("entry_price", 0.0)),
"profit_target": float(pos.get("profit_target", 0.0)),
"stop_loss": float(pos.get("stop_loss", 0.0)),
"leverage": float(pos.get("leverage", 1)),
"confidence": float(pos.get("confidence", 0.0)),
"invalidation_condition": pos.get("invalidation_condition", ""),
"margin": float(pos.get("margin", 0.0)),
"fees_paid": fees_paid_value,
"fee_rate": fee_rate_value,
"liquidity": pos.get("liquidity", "taker"),
"entry_justification": pos.get("entry_justification", ""),
"last_justification": pos.get("last_justification", pos.get("entry_justification", "")),
"risk_usd": risk_usd_value,
"trade_type": pos.get("trade_type"),
"trail_phase": pos.get("trail_phase", "Phase 1"),
"initial_stop": initial_stop_value,
"initial_risk_per_unit": initial_risk_per_unit_value,
"initial_risk_usd": initial_risk_usd_value,
"trail_history": trail_history_value,
}
positions = restored_positions
logging.info(
"Loaded state from %s (balance: %.2f, positions: %d)",
STATE_JSON,
balance,
len(positions),
)
except Exception as e:
logging.error("Failed to load state from %s: %s", STATE_JSON, e, exc_info=True)
balance = START_CAPITAL
positions = {}
def save_state() -> None:
"""Persist current balance, open positions, and iteration counter."""
try:
with open(STATE_JSON, "w") as f:
json.dump(
{
"balance": balance,
"positions": positions,
"iteration": iteration_counter,
"updated_at": get_current_time().isoformat(),
},
f,
indent=2,
)
except Exception as e:
logging.error("Failed to save state to %s: %s", STATE_JSON, e, exc_info=True)
def reset_state(initial_balance: Optional[float] = None) -> None:
"""Reset in-memory trading state to start a fresh run."""
global balance, positions, trade_history, iteration_counter, equity_history, invocation_count, current_iteration_messages, BOT_START_TIME
balance = float(initial_balance) if initial_balance is not None else START_CAPITAL
positions = {}
trade_history = []
iteration_counter = 0
invocation_count = 0
equity_history.clear()
current_iteration_messages = []
BOT_START_TIME = get_current_time()
def load_equity_history() -> None:
"""Populate the in-memory equity history for performance calculations."""
equity_history.clear()
if not STATE_CSV.exists():
return
try:
df = pd.read_csv(STATE_CSV, usecols=["total_equity"])
except ValueError:
logging.warning(
"%s missing 'total_equity' column; Sortino ratio unavailable until new data is logged.",
STATE_CSV,
)
return
except Exception as exc:
logging.warning("Unable to load historical equity data: %s", exc)
return
values = pd.to_numeric(df["total_equity"], errors="coerce").dropna()
if not values.empty:
equity_history.extend(float(v) for v in values.tolist())
def register_equity_snapshot(total_equity: float) -> None:
"""Append the latest equity to the history if it is a finite value."""
if total_equity is None:
return
if isinstance(total_equity, (int, float, np.floating)) and np.isfinite(total_equity):
equity_history.append(float(total_equity))
# ───────────────────────── INDICATORS ───────────────────────
def calculate_rsi_series(close: pd.Series, period: int) -> pd.Series:
"""Return RSI series for specified period using Wilder's smoothing."""
delta = close.astype(float).diff()
gain = delta.where(delta > 0, 0.0)
loss = -delta.where(delta < 0, 0.0)
alpha = 1 / period
avg_gain = gain.ewm(alpha=alpha, adjust=False).mean()
avg_loss = loss.ewm(alpha=alpha, adjust=False).mean()
rs = avg_gain / avg_loss.replace(0, np.nan)
return 100 - 100 / (1 + rs)
def add_indicator_columns(
df: pd.DataFrame,
ema_lengths: Iterable[int] = (EMA_LEN,),
rsi_periods: Iterable[int] = (RSI_LEN,),
macd_params: Iterable[int] = (MACD_FAST, MACD_SLOW, MACD_SIGNAL),
) -> pd.DataFrame:
"""Return copy of df with EMA, RSI, and MACD columns added."""
ema_lengths = tuple(dict.fromkeys(ema_lengths)) # remove duplicates, preserve order
rsi_periods = tuple(dict.fromkeys(rsi_periods))
fast, slow, signal = macd_params
result = df.copy()
close = result["close"]
for span in ema_lengths:
result[f"ema{span}"] = close.ewm(span=span, adjust=False).mean()
for period in rsi_periods:
result[f"rsi{period}"] = calculate_rsi_series(close, period)
ema_fast = close.ewm(span=fast, adjust=False).mean()
ema_slow = close.ewm(span=slow, adjust=False).mean()
macd_line = ema_fast - ema_slow
result["macd"] = macd_line
result["macd_signal"] = macd_line.ewm(span=signal, adjust=False).mean()
return result
def calculate_atr_series(df: pd.DataFrame, period: int) -> pd.Series:
"""Return Average True Range series for the provided period."""
high = df["high"]
low = df["low"]
close = df["close"]
prev_close = close.shift(1)
tr_components = pd.concat(
[
high - low,
(high - prev_close).abs(),
(low - prev_close).abs(),
],
axis=1,
)
true_range = tr_components.max(axis=1)
alpha = 1 / period
return true_range.ewm(alpha=alpha, adjust=False).mean()
def calculate_adx_series(df: pd.DataFrame, period: int) -> pd.Series:
"""Return Average Directional Index (ADX) series."""
high = df["high"].astype(float)
low = df["low"].astype(float)
close = df["close"].astype(float)
prev_high = high.shift(1)
prev_low = low.shift(1)
plus_dm = (high - prev_high).where((high - prev_high) > (prev_low - low), 0.0)
plus_dm = plus_dm.where(plus_dm > 0, 0.0)
minus_dm = (prev_low - low).where((prev_low - low) > (high - prev_high), 0.0)
minus_dm = minus_dm.where(minus_dm > 0, 0.0)
tr_components = pd.concat(
[
high - low,
(high - close.shift(1)).abs(),
(low - close.shift(1)).abs(),
],
axis=1,
)
true_range = tr_components.max(axis=1)
alpha = 1 / period
smoothed_tr = true_range.ewm(alpha=alpha, adjust=False).mean().replace(0, np.nan)
smoothed_plus_dm = plus_dm.ewm(alpha=alpha, adjust=False).mean()
smoothed_minus_dm = minus_dm.ewm(alpha=alpha, adjust=False).mean()
plus_di = 100 * (smoothed_plus_dm / smoothed_tr)
minus_di = 100 * (smoothed_minus_dm / smoothed_tr)
dx = (100 * (plus_di - minus_di).abs() / (plus_di + minus_di).replace(0, np.nan)).fillna(0.0)
return dx.ewm(alpha=alpha, adjust=False).mean()
def calculate_indicators(df: pd.DataFrame) -> pd.Series:
"""Calculate technical indicators and return the latest row."""
enriched = add_indicator_columns(
df,
ema_lengths=(EMA_LEN,),
rsi_periods=(RSI_LEN,),
macd_params=(MACD_FAST, MACD_SLOW, MACD_SIGNAL),
)
enriched["rsi"] = enriched[f"rsi{RSI_LEN}"]
return enriched.iloc[-1]
def fetch_market_data(symbol: str) -> Optional[Dict[str, Any]]:
"""Fetch current market data for a symbol."""
binance_client = get_binance_client()
if not binance_client:
logging.warning("Skipping market data fetch for %s: Binance client unavailable.", symbol)
return None
try:
# Get recent klines
klines = binance_client.get_klines(symbol=symbol, interval=INTERVAL, limit=50)
df = pd.DataFrame(
klines,
columns=[
"timestamp",
"open",
"high",
"low",
"close",
"volume",
"close_time",
"quote_volume",
"trades",
"taker_base",
"taker_quote",
"ignore",
],
)
df["close"] = df["close"].astype(float)
df["high"] = df["high"].astype(float)
df["low"] = df["low"].astype(float)
df["open"] = df["open"].astype(float)
last = calculate_indicators(df)
latest_bar = df.iloc[-1]
last_high = float(latest_bar["high"])
last_low = float(latest_bar["low"])
last_close = float(latest_bar["close"])