-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun_bot.py
More file actions
393 lines (329 loc) · 14.7 KB
/
run_bot.py
File metadata and controls
393 lines (329 loc) · 14.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Boros Funding Rate Trader — Production Entry Point
Runs continuous trading cycles on Railway (or any Linux host).
Designed to run 24/7 under the watchdog process.
Environment variables (set in Railway dashboard):
SYNTH_API_KEY — Synth volatility/prediction API key
WALLET_PRIVATE_KEY — Arbitrum wallet (0x...) for on-chain Boros trades
ARBITRUM_RPC_URL — Arbitrum RPC endpoint
TELEGRAM_BOT_TOKEN — Telegram notifications
TELEGRAM_CHAT_ID — Telegram chat ID
INITIAL_CAPITAL — Starting capital in USD (default: 1000)
CYCLE_INTERVAL — Seconds between cycles (default: 300)
DRY_RUN — "true" for paper mode, "false" for live (default: false)
BOROS_SDK_BRIDGE_URL — SDK bridge URL (default: http://localhost:3001)
"""
import csv
import os
import sys
import time
import signal
import atexit
import subprocess
import argparse
from pathlib import Path
from datetime import datetime, timedelta
from dotenv import load_dotenv
ENV_FILE = Path(__file__).parent / '.env'
if ENV_FILE.exists():
load_dotenv(ENV_FILE)
sys.path.insert(0, str(Path(__file__).parent))
from src.strategies.vol_regime_trader import VolRegimeTrader
from src.api.boros_sdk_wrapper import BorosSDKWrapper
from src.config.settings import (
DRY_RUN,
TELEGRAM_NOTIFICATIONS,
TRADABLE_ASSETS,
SYNTH_DAILY_CALL_LIMIT,
BOROS_MIN_EDGE_BPS,
CARRY_ENTRY_THRESHOLD_BPS,
BUILD_LABEL,
BOROS_SDK_BRIDGE_URL,
)
SDK_DIR = Path(__file__).parent / 'sdk'
LOCK_FILE = Path(__file__).parent / '.bot.lock'
LOG_ROOT = Path(__file__).parent / 'data' / 'boros_logs'
def _load_historical_pnl() -> float:
"""Sum realized P&L from all previous session log directories."""
total = 0.0
if not LOG_ROOT.exists():
return total
for csv_file in LOG_ROOT.glob("*/trades.csv"):
try:
with open(csv_file, newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
if row.get('trade_type') in ('CLOSE', 'FLIP'):
raw = row.get('pnl_usd', '')
if raw:
try:
total += float(raw)
except ValueError:
pass
except Exception:
pass
return total
def _pid_is_alive(pid: int) -> bool:
"""Check if a PID is still running (Linux-compatible)."""
try:
os.kill(pid, 0)
return True
except (OSError, ProcessLookupError):
return False
def _release_lock() -> None:
try:
if LOCK_FILE.exists():
LOCK_FILE.unlink()
except Exception:
pass
def _check_dev_instance_conflict() -> None:
"""Warn if the DEV build (boros_trader) appears to be running live on the same wallet.
This prevents accidental dual-instance trading on the same Boros account."""
dev_lock = Path(__file__).parent.parent / 'boros_trader' / 'data' / 'runtime.lock'
if not dev_lock.exists():
return
try:
import json
lock_data = json.loads(dev_lock.read_text())
dev_pid = lock_data.get('pid', 0)
if _pid_is_alive(dev_pid):
if not DRY_RUN:
print(f"\n[SAFETY] DEV build (boros_trader) is running LIVE (PID {dev_pid}).")
print(f"[SAFETY] PROD is also set to LIVE mode — this would create dual-instance")
print(f"[SAFETY] trading on the same wallet. Aborting to prevent conflicts.")
print(f"[SAFETY] Either set PROD DRY_RUN=True or stop the DEV instance first.")
sys.exit(3)
else:
print(f"[Info] DEV build running live (PID {dev_pid}). PROD is paper-mode — safe.")
except (json.JSONDecodeError, IOError, KeyError):
pass
def _acquire_lock() -> None:
_check_dev_instance_conflict()
if LOCK_FILE.exists():
try:
old_pid = int(LOCK_FILE.read_text().strip())
if _pid_is_alive(old_pid):
print(f"\n[Lock] Bot is already running (PID {old_pid}). Exiting.")
sys.exit(1)
except (ValueError, IOError):
pass
LOCK_FILE.write_text(str(os.getpid()))
atexit.register(_release_lock)
def _start_sdk_bridge() -> subprocess.Popen:
"""Start the Boros SDK Node.js bridge in the background."""
print(" [SDK] Starting Boros SDK bridge...")
dist_js = SDK_DIR / 'dist' / 'server.js'
if not dist_js.exists():
print(" [SDK] dist/server.js not found -- building...")
result = subprocess.run(
'npm run build',
shell=True,
cwd=str(SDK_DIR),
capture_output=True,
text=True
)
if not dist_js.exists():
print(f" [SDK] Build failed:\n{result.stderr}")
return None
proc = subprocess.Popen(
['node', 'dist/server.js'],
cwd=str(SDK_DIR),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
time.sleep(3)
return proc
class BotSession:
"""Production trading session — runs indefinitely until stopped."""
def __init__(self, capital: float = 1000.0, cycle_interval: int = 300):
self.capital = capital
self.cycle_interval = cycle_interval
self.trader: VolRegimeTrader = None
self.start_time: datetime = None
self.running = False
self._sdk_proc: subprocess.Popen = None
self.historical_pnl: float = _load_historical_pnl()
if self.historical_pnl != 0.0:
print(f"[History] Loaded ${self.historical_pnl:+.4f} realized P&L from prior sessions")
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
def _signal_handler(self, signum, frame):
print("\n\n[Session] Shutdown signal received -- wrapping up...")
self.running = False
def check_prerequisites(self) -> bool:
print("=" * 70)
mode_label = "PAPER TRADING" if DRY_RUN else "LIVE TRADING"
print(f"BOROS TRADER [{BUILD_LABEL}] -- {mode_label} -- PREREQUISITE CHECK")
print(f"SDK Bridge: {BOROS_SDK_BRIDGE_URL}")
print("=" * 70)
print("\n[1] Checking Boros SDK bridge...")
boros = BorosSDKWrapper()
if boros.health_check():
print(" [OK] SDK bridge already running")
else:
print(" [INFO] Bridge not running -- attempting auto-start...")
self._sdk_proc = _start_sdk_bridge()
if self._sdk_proc and boros.health_check():
print(" [OK] SDK bridge started successfully")
else:
if DRY_RUN:
print(" [WARN] Could not start bridge -- continuing in offline mode")
else:
print(" [FAIL] SDK bridge required for live trading")
return False
print("\n[2] Checking Synth API key...")
api_key = os.getenv('SYNTH_API_KEY', '')
if not api_key or api_key == 'your_synth_api_key_here':
print(" [FAIL] SYNTH_API_KEY not set")
return False
print(f" [OK] Key: {api_key[:8]}...{api_key[-4:]}")
print("\n[3] Trading mode...")
if DRY_RUN:
print(" [INFO] DRY_RUN=True (paper trading)")
else:
print(" [LIVE] DRY_RUN=False -- REAL MONEY ON THE LINE")
wallet = os.getenv('WALLET_PRIVATE_KEY', '')
if not wallet:
print(" [FAIL] WALLET_PRIVATE_KEY required for live trading")
return False
print(f" [OK] Wallet key present")
print("\n[4] Telegram notifications...")
if TELEGRAM_NOTIFICATIONS:
token = os.getenv('TELEGRAM_BOT_TOKEN', '')
chat = os.getenv('TELEGRAM_CHAT_ID', '')
if token and chat:
print(f" [OK] Enabled")
else:
print(" [WARN] Telegram enabled but credentials missing")
else:
print(" [INFO] Disabled")
print("\n[5] Strategy parameters...")
print(f" Assets: {TRADABLE_ASSETS}")
print(f" Min edge: {BOROS_MIN_EDGE_BPS}bps")
print(f" Carry threshold: {CARRY_ENTRY_THRESHOLD_BPS}bps")
print(f" Cycle interval: {self.cycle_interval}s")
print("\n" + "=" * 70)
print("READY TO START")
print("=" * 70)
return True
def run(self) -> int:
if not self.check_prerequisites():
return 1
print(f"\n[Init] Capital: ${self.capital:,.2f} | Cycle: {self.cycle_interval}s | Mode: {'PAPER' if DRY_RUN else 'LIVE'}")
self.trader = VolRegimeTrader(capital=self.capital, historical_pnl=self.historical_pnl)
self.trader.load_state()
self.start_time = datetime.now()
self.running = True
print(f"\n[Session] Started {self.start_time.strftime('%Y-%m-%d %H:%M:%S UTC')}")
print(f"[Session] Running indefinitely -- send SIGTERM to stop\n")
cycle = 0
try:
while self.running:
cycle += 1
now = datetime.now()
uptime_h = (now - self.start_time).total_seconds() / 3600
print(f"\n{'=' * 70}")
print(f"CYCLE #{cycle} | {now.strftime('%H:%M:%S')} | uptime {uptime_h:.1f}h")
print('=' * 70)
try:
executions = self.trader.run_cycle()
except Exception as cycle_err:
import traceback
print(f"\n[Session] ERROR in cycle #{cycle}: {cycle_err}")
traceback.print_exc()
print(f"[Session] Recovering -- sleeping {self.cycle_interval}s...")
time.sleep(self.cycle_interval)
continue
if executions:
for ex in executions:
if ex.trade_type == "OPEN":
print(f" [OPEN ] {ex.side} YU {ex.asset} ${ex.size:.0f}")
elif ex.trade_type == "CLOSE":
pnl_str = f"${ex.pnl:+.2f}" if ex.pnl is not None else "n/a"
print(f" [CLOSE] {ex.side} YU {ex.asset} PnL {pnl_str}"
f" | {ex.exit_reason}")
elif ex.trade_type == "FLIP":
pnl_str = f"${ex.pnl:+.2f}" if ex.pnl is not None else "n/a"
print(f" [FLIP ] -> {ex.side} YU {ex.asset} PnL {pnl_str}")
else:
print(" [No actions this cycle]")
status = self.trader.get_status()
capital = status['capital']
exposure = status['exposure_pct']
unreal = status.get('unrealized_pnl', 0)
print(f"\n Capital: ${capital:,.2f} | Exposure: {exposure:.1%}"
f" | Unrealized PnL: ${unreal:+.2f}")
print(f" Positions: {status['active_positions']}"
f" | Synth: {status['synth_stats']['calls_today']}/{SYNTH_DAILY_CALL_LIMIT}")
if status['positions']:
print("\n Open positions:")
for asset, pos in status['positions'].items():
fixed = pos.get('entry_fixed_rate', 0.0)
flt = pos.get('entry_funding', 0.0)
pnl = pos.get('unrealized_pnl', 0.0)
collat = pos.get('size', 0.0)
notional = pos.get('notional', collat)
lev = pos.get('leverage', 1.0)
spread = int(abs(fixed - flt) * 10_000)
daily = pos.get('daily_carry', abs(fixed - flt) * notional / 365)
pnl_str = f"${pnl:+.4f}" if abs(pnl) < 0.01 else f"${pnl:+.2f}"
print(f" [{pos['side']}] {asset} [{pos.get('venue','?')}] YU"
f" collateral=${collat:.0f} notional=${notional:,.0f}"
f" ({lev:.0f}x) hold={pos['hold_hours']:.1f}h")
print(f" float={flt:.2%} fixed={fixed:.2%}"
f" carry={spread}bps daily=${daily:.4f}"
f" unrealized={pnl_str}")
if not self.running:
break
print(f"\n Sleeping {self.cycle_interval}s...")
time.sleep(self.cycle_interval)
except KeyboardInterrupt:
print("\n\n[Session] Interrupted by user")
except Exception as fatal_err:
import traceback
print(f"\n\n[Session] FATAL ERROR: {fatal_err}")
traceback.print_exc()
print("[Session] Exiting with code 2 so watchdog can restart...")
self._shutdown()
sys.exit(2)
finally:
self._shutdown()
return 0
def _shutdown(self):
print("\n" + "=" * 70)
print("SESSION COMPLETE -- FINAL SUMMARY")
print("=" * 70)
if self.trader:
self.trader.save_state()
status = self.trader.get_status()
trade_stats = status.get('trade_stats', {})
portfolio = status.get('portfolio', {})
elapsed = (datetime.now() - self.start_time).total_seconds() / 3600 if self.start_time else 0
print(f"\nRun time: {elapsed:.1f}h ({self.trader.cycle_count} cycles)")
print(f"Capital: ${portfolio.get('total_capital', self.capital):,.2f}")
print(f"Unrealized PnL: ${portfolio.get('unrealized_pnl', 0):+.2f}")
print(f"\nTrades: {trade_stats.get('total_trades', 0)}"
f" | Win rate: {trade_stats.get('win_rate', 0):.1f}%"
f" | Avg hold: {trade_stats.get('avg_hold_time', 0):.1f}h")
print(f"Synth calls: {status['synth_stats']['calls_today']}/{SYNTH_DAILY_CALL_LIMIT}")
print(f"\nData files:")
for name, path in status.get('log_paths', {}).items():
print(f" {name}: {path}")
self.trader.shutdown()
if self._sdk_proc:
try:
self._sdk_proc.terminate()
print("\n[SDK] Bridge stopped")
except Exception:
pass
print("\n" + "=" * 70)
def main():
_acquire_lock()
capital = float(os.getenv('INITIAL_CAPITAL', '1000'))
interval = int(os.getenv('CYCLE_INTERVAL', '300'))
session = BotSession(capital=capital, cycle_interval=interval)
sys.exit(session.run())
if __name__ == "__main__":
main()