"""CryptoVolk signal copier — listen & trade.""" from __future__ import annotations import asyncio import logging import os from dataclasses import dataclass from pathlib import Path import yaml from dotenv import load_dotenv from telethon import TelegramClient, events from signal_parser import parse_signal, parse_close, Signal, CloseSignal from llm_parser import LLMParser from executor import FuturesExecutor log = logging.getLogger("copier") @dataclass class Config: api_id: int api_hash: str signal_bot: str api_key: str api_secret: str risk_pct: float = 0.03 max_positions: int = 3 def load_config() -> Config: load_dotenv(Path(__file__).parent / ".env") cfg_path = Path(__file__).parent / "config.yaml" raw = yaml.safe_load(open(cfg_path)) if cfg_path.exists() else {} trading = raw.get("trading", {}) return Config( api_id=int(os.environ.get("TELEGRAM_API_ID", 0)), api_hash=os.environ.get("TELEGRAM_API_HASH", ""), signal_bot=raw.get("signal_bot", "Cryptovolksignalbot"), api_key=os.environ.get("REMIZOV_API_KEY", ""), api_secret=os.environ.get("REMIZOV_API_SECRET", ""), risk_pct=trading.get("risk_pct", 0.03), max_positions=trading.get("max_positions", 3), ) async def main(): logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(name)s] %(levelname)s %(message)s", ) cfg = load_config() if not cfg.api_id or not cfg.api_hash: log.error("Set TELEGRAM_API_ID and TELEGRAM_API_HASH in .env") return if not cfg.api_key or not cfg.api_secret: log.error("Set REMIZOV_API_KEY and REMIZOV_API_SECRET in .env") return session_path = str(Path(__file__).parent / "copier_session") client = TelegramClient(session_path, cfg.api_id, cfg.api_hash) executor = FuturesExecutor(cfg) # LLM fallback parser (z.ai) llm = LLMParser( base_url="https://api.z.ai/api/anthropic", api_key="4d13fce5f9f247f18e2670ee00a369d7.PWbacOpikzPJ62Qu", model="glm-4.7", ) await client.start() me = await client.get_me() log.info(f"Telegram: logged in as {me.username or me.phone}") # Resolve signal bot try: bot_entity = await client.get_entity(cfg.signal_bot) log.info(f"Listening to @{bot_entity.username} (id={bot_entity.id})") except Exception as e: log.error(f"Cannot find {cfg.signal_bot}: {e}") await executor.close() return @client.on(events.NewMessage(from_users=bot_entity)) async def on_signal(event): text = event.raw_text log.info(f"Signal bot: {text[:120]}...") # 1. Regex parser (fast, free) signal = parse_signal(text) close = parse_close(text) if not signal else None # 2. LLM fallback if regex missed but text has signal markers if not signal and not close and _looks_like_signal(text): log.info("Regex missed, trying LLM fallback...") result = await llm.parse(text) if isinstance(result, Signal): signal = result log.info(f"LLM parsed signal: {signal.direction} {signal.symbol}") elif isinstance(result, CloseSignal): close = result log.info(f"LLM parsed close: {close.symbol}") # 3. Execute if signal: log.info(f">>> {signal.direction.upper()} {signal.symbol} " f"entry={signal.entry} stop={signal.stop} " f"TP={signal.targets} lev={signal.leverage}x") ok = await executor.handle_signal(signal) if ok: await client.send_message( "me", f"Executed: {signal.direction.upper()} {signal.raw_symbol}\n" f"Entry: {signal.entry}, SL: {signal.stop}\n" f"TP: {signal.targets}") return if close: log.info(f">>> CLOSE {close.symbol} @ {close.price}") ok = await executor.handle_close(close) if ok: await client.send_message( "me", f"Closed: {close.symbol} @ {close.price}") return log.debug(f"Ignored: {text[:60]}") def _looks_like_signal(text: str) -> bool: """Quick heuristic: does the text look like it could be a signal?""" upper = text.upper() has_direction = "LONG" in upper or "SHORT" in upper has_symbol = "#" in text and ("USDT" in upper or "USDC" in upper) has_numbers = any(c.isdigit() for c in text) return has_direction and has_symbol and has_numbers # Background: check TP3 → move SL to breakeven (every 30s) async def monitor(): while True: await asyncio.sleep(30) try: await executor.check_tp3_breakeven() except Exception as e: log.error(f"Monitor: {e}") asyncio.create_task(monitor()) log.info("Signal copier running. Ctrl+C to stop.") try: await client.run_until_disconnected() finally: await executor.close() if __name__ == "__main__": asyncio.run(main())