Repository navigation
Expand file tree
/
Copy pathstart.py
More file actions
514 lines (433 loc) · 18.7 KB
/
Copy pathstart.py
File metadata and controls
514 lines (433 loc) · 18.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
import asyncio
import atexit
import hashlib
import logging
import os
import shutil
import sys
import time
import warnings
from pathlib import Path
from rich.console import Console
from rich.progress import (
BarColumn,
Progress,
SpinnerColumn,
TextColumn,
TimeElapsedColumn,
TimeRemainingColumn,
)
from src.analyzer.sentiment_analyst import SocialSentimentAnalyst
from src.app import BotServices, CryptoTradingBot
from src.composition.provisioners import ProvisioningMixin
from src.composition.startup_support import (
build_startup_banner,
show_error_dialog,
)
from src.config.loader import config
from src.logger.logger import Logger
from src.trading import (
ExecutorHandler,
PositionStatusMonitor,
)
from src.utils.graceful_shutdown_manager import GracefulShutdownManager
# pylint: disable=wrong-import-position
warnings.filterwarnings("ignore", category=SyntaxWarning, module="docopt")
warnings.filterwarnings("ignore", category=DeprecationWarning, module="discord")
warnings.filterwarnings("ignore", category=DeprecationWarning, module="google.genai")
class SingleInstanceLock:
def __init__(
self, app_name: str = ".llm_trader.lock", logger: Logger | None = None
):
self.lock_file_path = Path.home() / app_name
self._lock_handle: int | None = None
self._mutex_handle = None
self.logger = logger or logging.getLogger(__name__)
def _acquire_windows_mutex(self) -> bool:
try:
import ctypes
lock_key = hashlib.sha1(
str(self.lock_file_path).encode("utf-8")
).hexdigest()[:16]
mutex_name = f"Local\\LLMTraderSingleInstance_{lock_key}"
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
handle = kernel32.CreateMutexW(None, False, mutex_name)
if not handle:
return True
self._mutex_handle = handle
ERROR_ALREADY_EXISTS = 183
if ctypes.get_last_error() == ERROR_ALREADY_EXISTS:
kernel32.CloseHandle(handle)
self._mutex_handle = None
return False
return True
except Exception: # noqa: BLE001
return True
def _release_windows_mutex(self) -> None:
if self._mutex_handle:
try:
import ctypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.CloseHandle(self._mutex_handle)
except Exception:
self.logger.exception("Failed to release Windows mutex handle")
self._mutex_handle = None
def acquire(self) -> bool:
try:
if sys.platform == "win32" and not self._acquire_windows_mutex():
return False
self._lock_handle = os.open(
str(self.lock_file_path), os.O_CREAT | os.O_RDWR
)
if sys.platform == "win32":
import msvcrt
try:
msvcrt.locking(self._lock_handle, msvcrt.LK_NBLCK, 1)
except OSError:
self._release_windows_mutex()
return False
else:
import fcntl # pylint: disable=import-error
try:
fcntl.flock(self._lock_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return False
atexit.register(self.release)
return True
except Exception as e: # noqa: BLE001
self._release_windows_mutex()
print(f"Warning: Could not create lock file: {e}")
return True
def release(self) -> None:
if self._lock_handle is not None:
try:
if sys.platform == "win32":
import msvcrt
msvcrt.locking(self._lock_handle, msvcrt.LK_UNLCK, 1)
else:
import fcntl # pylint: disable=import-error
fcntl.flock(self._lock_handle, fcntl.LOCK_UN)
os.close(self._lock_handle)
except Exception: # noqa: BLE001
self.logger.warning("Failed to release lock")
self._lock_handle = None
try:
self.lock_file_path.unlink(missing_ok=True)
except Exception: # noqa: BLE001
self.logger.warning("Failed to unlink lock file")
self._release_windows_mutex()
RELOAD_EXIT_CODE = 42
class CompositionRoot(ProvisioningMixin):
def __init__(self):
self.config = config
self.console = Console(color_system="auto")
self.logger = Logger(
logger_name="Bot", logger_debug=config.LOGGER_DEBUG, console=self.console
)
self.logger.install_crash_handler()
self.loop = None
self.shutdown_manager: GracefulShutdownManager | None = None
# pylint: disable=too-many-statements
async def build_dependencies(self) -> dict:
start_time = time.perf_counter()
self.console.clear()
project_root = Path(__file__).parent.resolve()
self.console.print(build_startup_banner(project_root))
self.console.print()
self.console.rule("[dim]Initializing...[/]")
self.console.print()
progress = Progress(
SpinnerColumn(spinner_name="dots12", style="cyan"),
TextColumn("[progress.description]{task.description}"),
BarColumn(bar_width=None, style="blue", complete_style="green"),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
TimeElapsedColumn(),
TimeRemainingColumn(elapsed_when_finished=True),
console=self.console,
expand=True,
)
with progress:
task = progress.add_task(
"[cyan]Stage 1/9 — Core infrastructure (exchanges, sessions)...",
total=9,
)
self._init_directories()
infra = await self._provision_infrastructure()
progress.update(task, completed=1)
progress.update(
task, description="[cyan]Stage 2/9 — Helper utilities & parsers..."
)
utils = self._provision_utilities()
progress.update(task, completed=2)
progress.update(
task,
description="[cyan]Stage 3/9 — Market data platforms (CoinGecko, DeFiLlama, CCXT)...",
)
apis = await self._provision_platforms(infra)
progress.update(task, completed=3)
progress.update(
task, description="[cyan]Stage 4/9 — RAG news engine & taxonomy..."
)
rag = await self._provision_rag_layer(infra, apis, utils)
progress.update(task, completed=4)
progress.update(
task,
description="[cyan]Stage 5/9 — AI provider models & orchestrator...",
)
models = self._provision_model_layer(utils)
progress.update(task, completed=5)
progress.update(
task,
description="[cyan]Stage 6/9 — Technical analysis engine & patterns...",
)
analyzer = await self._provision_analyzer_layer(
infra, apis, utils, rag, models
)
progress.update(task, completed=6)
progress.update(
task,
description="[cyan]Stage 7/9 — Trading brain, memory, risk manager & guards...",
)
trading = self._provision_trading_layer(utils, models)
progress.update(task, completed=7)
progress.update(
task,
description="[cyan]Stage 8/9 — Notification channels (Discord)...",
)
notifiers = await self._provision_notifiers(utils)
progress.update(task, completed=8)
progress.update(
task, description="[green]Stage 9/9 — Dashboard server..."
)
dashboard = self._provision_dashboard_layer(infra, utils, analyzer, trading)
progress.update(task, completed=9)
end_time = time.perf_counter()
init_duration = end_time - start_time
self.logger.info(
"All 9 provisioning stages initialized successfully in %.2f seconds",
init_duration,
)
self._display_startup_summary(apis, rag, trading, init_duration)
deps = {
"exchange_manager": infra["exchange_manager"],
"market_analyzer": analyzer["engine"],
"trading_strategy": trading["strategy"],
"discord_notifier": notifiers["notifier"],
"discord_task": notifiers["task"],
"keyboard_handler": infra["keyboard_handler"],
"rag_engine": rag,
"coingecko_api": apis["coingecko"],
"market_api": apis["market"],
"alternative_me_api": apis["alternative_me"],
"http_session": infra["session"],
"persistence": trading["persistence"],
"model_manager": models["manager"],
"brain_service": trading["brain_service"],
"statistics_service": trading["statistics_service"],
"memory_service": trading["memory_service"],
"exit_monitor": trading["exit_monitor"],
"sentiment_analyst": SocialSentimentAnalyst(
logger=self.logger,
token_counter=utils["token_counter"],
pair=self.config.CRYPTO_PAIR,
curl_path=self._resolve_curl(),
),
"ev_formatter": analyzer["ev_formatter"],
"executor_handler": ExecutorHandler(
persistence=trading["persistence"],
config=self.config,
logger=self.logger,
),
"dashboard_server": dashboard["dashboard_server"],
"dashboard_state": dashboard["dashboard_state"],
"force_analysis_event": dashboard["force_analysis_event"],
}
return deps
def _resolve_curl(self) -> str | None:
curl_path = shutil.which("curl.exe") or shutil.which("curl")
if curl_path is None and self.config.SOCIAL_SENTIMENT_ENABLED:
self.logger.error(
"social_sentiment is enabled but no curl binary is on PATH — the StockTwits "
"stream cannot be fetched and the social section stays empty"
)
return curl_path
async def run_async(self):
def _asyncio_exception_handler(_loop, context):
if self.shutdown_manager and self.shutdown_manager.is_shutting_down:
return
if _loop.is_closed():
return
exc = context.get("exception")
msg = context.get("message", "Unknown asyncio error")
if exc is not None:
if isinstance(exc, KeyboardInterrupt):
self.logger.debug("Asyncio task KeyboardInterrupt: %s", msg)
return
self.logger.error("Asyncio unhandled exception: %s", msg, exc_info=exc)
else:
self.logger.error("Asyncio error: %s", msg)
if self.loop:
self.loop.set_exception_handler(_asyncio_exception_handler)
dependencies = await self.build_dependencies()
dashboard_server = dependencies.pop("dashboard_server", None)
force_analysis_event = dependencies.pop("force_analysis_event", None)
def _create_position_monitor(bot: CryptoTradingBot) -> PositionStatusMonitor:
if self.config.EXECUTOR_API_ENABLED and self.config.EXCHANGE_SANDBOX:
self.logger.warning(
"SANDBOX MARKET DATA + EXECUTOR: the bot reads the TESTNET book, so the "
"real-market exit check evaluates testnet prices and the exchange backstop "
"is the only protection against a venue-only move. Set [exchanges] "
"sandbox = false to keep the real stop."
)
return PositionStatusMonitor(
logger=self.logger,
config=self.config,
persistence=dependencies["persistence"],
trading_strategy=dependencies["trading_strategy"],
exit_monitor=dependencies["exit_monitor"],
notifier=dependencies["discord_notifier"],
active_tasks=bot.active_tasks,
is_running=lambda: bot.running,
fetch_current_ticker=bot.fetch_current_ticker,
interruptible_sleep=bot.interruptible_sleep,
get_symbol=lambda: bot.current_symbol,
manages_exits=lambda: not self.config.EXECUTOR_API_ENABLED,
reconcile_position=dependencies["trading_strategy"].reconcile_local_position,
reference_exits_enabled=dependencies["trading_strategy"].executor_query_available,
reference_exit_check_seconds=self.config.REFERENCE_EXIT_CHECK_SECONDS,
forward_local_close=bot.forward_local_exit_request,
)
bot = CryptoTradingBot(
BotServices(
logger=self.logger,
config=self.config,
shutdown_manager=self.shutdown_manager,
position_monitor_factory=_create_position_monitor,
force_analysis_event=force_analysis_event,
**dependencies,
)
)
if bot.dashboard_state is not None:
bot.dashboard_state.lifecycle_provider = bot.lifecycle_snapshot
try:
await bot.initialize()
symbol = self.config.CRYPTO_PAIR
timeframe = self.config.TIMEFRAME
dashboard_running = False
async def _toggle_dashboard():
nonlocal dashboard_running
if not dashboard_server:
return
if dashboard_running:
self.logger.info("Dashboard: stopping (kill switch)...")
await dashboard_server.stop()
dashboard_running = False
self.logger.info("Dashboard stopped. Press 'd' to restart.")
else:
self.logger.info("Dashboard: starting...")
await dashboard_server.start()
dashboard_running = True
self.logger.info(
"Dashboard live at http://localhost:%s",
self.config.DASHBOARD_PORT,
)
bot.keyboard_handler.register_command(
"d", _toggle_dashboard, "Toggle dashboard on/off"
)
if dashboard_server and self.config.DASHBOARD_ENABLED:
await dashboard_server.start()
dashboard_running = True
elif not self.config.DASHBOARD_ENABLED:
self.logger.info("Dashboard disabled (config). Press 'd' to start it.")
if dashboard_server and self.shutdown_manager:
self.shutdown_manager.register_shutdown_callback(dashboard_server.stop)
await bot.run(symbol, timeframe)
except asyncio.CancelledError:
self.logger.info("Trading cancelled, shutting down...")
finally:
if dashboard_server:
await dashboard_server.stop()
def start(self) -> int:
single_instance_lock = SingleInstanceLock(logger=self.logger)
if not single_instance_lock.acquire():
shown = show_error_dialog(
"Crypto Trading Bot",
"Another instance of Crypto Trading Bot is already running.",
)
if not shown:
print("Another instance of Crypto Trading Bot is already running.")
sys.exit(1)
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8") # type: ignore[reportAttributeAccessIssue]
sys.stderr.reconfigure(encoding="utf-8") # type: ignore[reportAttributeAccessIssue]
except Exception: # noqa: S110, BLE001
pass
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
self.loop = asyncio.SelectorEventLoop()
else:
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.shutdown_manager = GracefulShutdownManager(
self.loop,
logger=self.logger,
confirmation_callback=GracefulShutdownManager.show_exit_confirmation,
)
self.shutdown_manager.setup_signal_handlers()
exit_code = 0
try:
while True:
try:
self.loop.run_until_complete(self.run_async())
break
except KeyboardInterrupt:
print("\nKeyboardInterrupt received.")
if not GracefulShutdownManager.show_exit_confirmation():
print("Shutdown cancelled. Continuing operation...")
continue
self.loop.run_until_complete(
self.shutdown_manager.shutdown_gracefully()
)
break
except Exception:
self.logger.exception(
"Unhandled exception in main loop — shutting down"
)
self.loop.run_until_complete(
self.shutdown_manager.shutdown_gracefully()
)
break
if self.shutdown_manager.reload_requested:
self.logger.info(
"Reload requested - completing graceful shutdown for in-place restart..."
)
try:
self.loop.run_until_complete(
self.shutdown_manager.shutdown_gracefully()
)
except Exception as exc: # noqa: BLE001
self.logger.error("Error during reload shutdown: %s", exc)
exit_code = RELOAD_EXIT_CODE
finally:
try:
if not self.loop.is_closed():
self.loop.close()
except Exception as e: # noqa: BLE001
self.logger.error("Error closing event loop: %s", e)
return exit_code
if __name__ == "__main__":
try:
exit_code = CompositionRoot().start()
except BaseException:
import traceback
print("\n" + "=" * 60)
print("FATAL: Unhandled exception — copy this error and press Enter")
print("=" * 60)
traceback.print_exc()
print("=" * 60)
try:
input("Press Enter to close...")
except (EOFError, KeyboardInterrupt):
pass
raise
sys.exit(exit_code)