feat: signal-copier — копитрейдинг бот для @Cryptovolksignalbot
Telegram userbot (Telethon) слушает сигналы от CryptoVolk и автоматически торгует на Bybit Futures. Двухуровневый парсер: regex (быстро) + LLM fallback (z.ai) для нестандартных форматов. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
TELEGRAM_API_ID=
|
||||
TELEGRAM_API_HASH=
|
||||
REMIZOV_API_KEY=
|
||||
REMIZOV_API_SECRET=
|
||||
@@ -0,0 +1,5 @@
|
||||
.env
|
||||
*.session
|
||||
*.session-journal
|
||||
__pycache__/
|
||||
.venv/
|
||||
@@ -0,0 +1,6 @@
|
||||
signal_bot: "Cryptovolksignalbot"
|
||||
|
||||
trading:
|
||||
risk_pct: 0.03 # 3% risk per trade
|
||||
max_positions: 3 # max simultaneous positions
|
||||
default_leverage: 20 # fallback if signal has no leverage
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
"""Bybit linear futures executor for signal copier."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import ccxt.async_support as ccxt
|
||||
|
||||
from signal_parser import Signal, CloseSignal
|
||||
|
||||
log = logging.getLogger("copier.executor")
|
||||
|
||||
|
||||
class FuturesExecutor:
|
||||
def __init__(self, cfg):
|
||||
self.exchange = ccxt.bybit({
|
||||
"apiKey": cfg.api_key,
|
||||
"secret": cfg.api_secret,
|
||||
"enableRateLimit": True,
|
||||
"options": {"recvWindow": 30000, "defaultType": "linear"},
|
||||
})
|
||||
self.risk_pct = cfg.risk_pct
|
||||
self.max_positions = cfg.max_positions
|
||||
self.positions: dict[str, dict] = {}
|
||||
self._markets_loaded = False
|
||||
|
||||
async def _ensure_markets(self):
|
||||
if not self._markets_loaded:
|
||||
await self.exchange.load_markets()
|
||||
self._markets_loaded = True
|
||||
|
||||
# ── public handlers ──────────────────────────────────────────────
|
||||
|
||||
async def handle_signal(self, signal: Signal) -> bool:
|
||||
"""Returns True if trade was executed."""
|
||||
await self._ensure_markets()
|
||||
symbol = signal.symbol
|
||||
|
||||
if symbol not in self.exchange.symbols:
|
||||
log.error(f"Symbol {symbol} not found on exchange")
|
||||
return False
|
||||
|
||||
# Already in same direction → skip
|
||||
if symbol in self.positions:
|
||||
if self.positions[symbol]["direction"] == signal.direction:
|
||||
log.info(f"Already {signal.direction} {symbol}, skip")
|
||||
return False
|
||||
# Flip: close then open opposite
|
||||
log.info(f"Flip {symbol}: {self.positions[symbol]['direction']} → {signal.direction}")
|
||||
await self._close_position(symbol)
|
||||
|
||||
if len(self.positions) >= self.max_positions:
|
||||
log.warning(f"Max {self.max_positions} positions, skip {symbol}")
|
||||
return False
|
||||
|
||||
return await self._open_position(signal)
|
||||
|
||||
async def handle_close(self, cs: CloseSignal) -> bool:
|
||||
"""Returns True if position was closed."""
|
||||
await self._ensure_markets()
|
||||
if cs.symbol in self.positions:
|
||||
log.info(f"Close signal: {cs.symbol} @ {cs.price}")
|
||||
await self._close_position(cs.symbol)
|
||||
return True
|
||||
log.info(f"Close signal for {cs.symbol} but no tracked position")
|
||||
return False
|
||||
|
||||
async def check_tp3_breakeven(self):
|
||||
"""Move SL to breakeven after TP3 is filled."""
|
||||
for symbol, pos in list(self.positions.items()):
|
||||
if pos["sl_at_be"] or len(pos["tp_ids"]) < 3:
|
||||
continue
|
||||
try:
|
||||
order = await self.exchange.fetch_order(pos["tp_ids"][2], symbol)
|
||||
if order.get("status") == "closed":
|
||||
await self._move_sl_to_breakeven(symbol, pos)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def close(self):
|
||||
await self.exchange.close()
|
||||
|
||||
# ── internal ─────────────────────────────────────────────────────
|
||||
|
||||
async def _calc_qty(self, signal: Signal) -> float:
|
||||
bal = await self.exchange.fetch_balance()
|
||||
equity = 0.0
|
||||
for coin in ("USDC", "USDT"):
|
||||
equity += float(bal.get(coin, {}).get("total", 0) or 0)
|
||||
|
||||
risk_amount = equity * self.risk_pct
|
||||
risk_per_unit = abs(signal.entry - signal.stop)
|
||||
if risk_per_unit <= 0:
|
||||
log.error(f"Invalid stop distance: entry={signal.entry} stop={signal.stop}")
|
||||
return 0
|
||||
|
||||
qty = risk_amount / risk_per_unit
|
||||
qty = float(self.exchange.amount_to_precision(signal.symbol, qty))
|
||||
|
||||
market = self.exchange.market(signal.symbol)
|
||||
min_qty = float(market["limits"]["amount"]["min"] or 0)
|
||||
if qty < min_qty:
|
||||
log.error(f"{signal.symbol}: qty {qty} < min {min_qty}")
|
||||
return 0
|
||||
|
||||
log.info(f"Size: equity=${equity:.2f}, risk=${risk_amount:.2f}, "
|
||||
f"stop_dist={risk_per_unit:.4f}, qty={qty}")
|
||||
return qty
|
||||
|
||||
async def _open_position(self, signal: Signal) -> bool:
|
||||
symbol = signal.symbol
|
||||
qty = await self._calc_qty(signal)
|
||||
if qty <= 0:
|
||||
return False
|
||||
|
||||
side = "buy" if signal.direction == "long" else "sell"
|
||||
close_side = "sell" if signal.direction == "long" else "buy"
|
||||
|
||||
# Set leverage
|
||||
try:
|
||||
await self.exchange.set_leverage(signal.leverage, symbol)
|
||||
except Exception as e:
|
||||
log.warning(f"set_leverage({signal.leverage}x) {symbol}: {e}")
|
||||
|
||||
# Market entry
|
||||
try:
|
||||
order = await self.exchange.create_market_order(symbol, side, qty)
|
||||
filled = float(order.get("filled") or qty)
|
||||
avg = float(order.get("average") or signal.entry)
|
||||
log.info(f"OPEN {signal.direction.upper()} {symbol}: "
|
||||
f"qty={filled} @ ${avg:,.2f} lev={signal.leverage}x")
|
||||
except Exception as e:
|
||||
log.error(f"OPEN {symbol} FAILED: {e}")
|
||||
return False
|
||||
|
||||
# SL: conditional trigger order (reduce-only)
|
||||
sl_id = None
|
||||
trigger_dir = 2 if signal.direction == "long" else 1 # 2=fall, 1=rise
|
||||
try:
|
||||
sl = await self.exchange.create_order(
|
||||
symbol, "market", close_side, filled,
|
||||
params={
|
||||
"triggerPrice": str(signal.stop),
|
||||
"triggerDirection": trigger_dir,
|
||||
"reduceOnly": True,
|
||||
},
|
||||
)
|
||||
sl_id = sl.get("id")
|
||||
log.info(f"SL: ${signal.stop:,.2f} (order={sl_id})")
|
||||
except Exception as e:
|
||||
log.error(f"SL order failed: {e}")
|
||||
|
||||
# TPs: limit reduce-only orders (equal split by target count)
|
||||
tp_ids = []
|
||||
n_targets = len(signal.targets)
|
||||
tp_qty = float(self.exchange.amount_to_precision(
|
||||
symbol, filled / n_targets))
|
||||
for i, tp_price in enumerate(signal.targets):
|
||||
if i == n_targets - 1:
|
||||
this_qty = float(self.exchange.amount_to_precision(
|
||||
symbol, filled - tp_qty * i))
|
||||
else:
|
||||
this_qty = tp_qty
|
||||
if this_qty <= 0:
|
||||
continue
|
||||
try:
|
||||
tp = await self.exchange.create_order(
|
||||
symbol, "limit", close_side, this_qty, tp_price,
|
||||
params={"reduceOnly": True},
|
||||
)
|
||||
tp_ids.append(tp.get("id"))
|
||||
log.info(f"TP{i+1}: ${tp_price:,.2f} qty={this_qty}")
|
||||
except Exception as e:
|
||||
log.error(f"TP{i+1} failed: {e}")
|
||||
|
||||
self.positions[symbol] = {
|
||||
"direction": signal.direction,
|
||||
"entry": avg,
|
||||
"qty": filled,
|
||||
"sl_id": sl_id,
|
||||
"tp_ids": tp_ids,
|
||||
"sl_at_be": False,
|
||||
}
|
||||
return True
|
||||
|
||||
async def _close_position(self, symbol: str):
|
||||
pos = self.positions.pop(symbol, None)
|
||||
close_side = "sell" if (pos and pos["direction"] == "long") else "buy"
|
||||
|
||||
# Cancel regular limit orders (TPs)
|
||||
try:
|
||||
for o in await self.exchange.fetch_open_orders(symbol):
|
||||
await self.exchange.cancel_order(o["id"], symbol)
|
||||
except Exception as e:
|
||||
log.warning(f"Cancel limit orders {symbol}: {e}")
|
||||
|
||||
# Cancel conditional orders (SL) — Bybit separates them
|
||||
if pos and pos.get("sl_id"):
|
||||
try:
|
||||
await self.exchange.cancel_order(
|
||||
pos["sl_id"], symbol,
|
||||
params={"orderFilter": "StopOrder"})
|
||||
except Exception:
|
||||
pass
|
||||
# Also try to cancel any remaining stop orders
|
||||
try:
|
||||
stops = await self.exchange.fetch_open_orders(
|
||||
symbol, params={"orderFilter": "StopOrder"})
|
||||
for o in stops:
|
||||
await self.exchange.cancel_order(
|
||||
o["id"], symbol, params={"orderFilter": "StopOrder"})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Close via exchange position size
|
||||
try:
|
||||
for p in await self.exchange.fetch_positions([symbol]):
|
||||
size = abs(float(p.get("contracts") or 0))
|
||||
if size > 0:
|
||||
await self.exchange.create_market_order(
|
||||
symbol, close_side, size, params={"reduceOnly": True})
|
||||
log.info(f"CLOSE {symbol}: qty={size}")
|
||||
except Exception as e:
|
||||
log.error(f"CLOSE {symbol} FAILED: {e}")
|
||||
|
||||
async def _move_sl_to_breakeven(self, symbol: str, pos: dict):
|
||||
close_side = "sell" if pos["direction"] == "long" else "buy"
|
||||
trigger_dir = 2 if pos["direction"] == "long" else 1
|
||||
|
||||
# Cancel old SL (conditional order on Bybit)
|
||||
if pos["sl_id"]:
|
||||
try:
|
||||
await self.exchange.cancel_order(
|
||||
pos["sl_id"], symbol,
|
||||
params={"orderFilter": "StopOrder"})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Get remaining size
|
||||
try:
|
||||
for p in await self.exchange.fetch_positions([symbol]):
|
||||
size = abs(float(p.get("contracts") or 0))
|
||||
if size > 0:
|
||||
sl = await self.exchange.create_order(
|
||||
symbol, "market", close_side, size,
|
||||
params={
|
||||
"triggerPrice": str(pos["entry"]),
|
||||
"triggerDirection": trigger_dir,
|
||||
"reduceOnly": True,
|
||||
},
|
||||
)
|
||||
pos["sl_id"] = sl.get("id")
|
||||
pos["sl_at_be"] = True
|
||||
log.info(f"SL → breakeven ${pos['entry']:,.2f} for {symbol}")
|
||||
except Exception as e:
|
||||
log.error(f"SL→BE {symbol} failed: {e}")
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
"""LLM-based signal parser (fallback when regex fails)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
import aiohttp
|
||||
|
||||
from signal_parser import Signal, CloseSignal, _convert_symbol
|
||||
|
||||
log = logging.getLogger("copier.llm")
|
||||
|
||||
SYSTEM_PROMPT = """You parse crypto trading signals from Telegram bots.
|
||||
Extract signal data and return ONLY valid JSON, no other text.
|
||||
|
||||
For entry signals return:
|
||||
{"type":"signal","direction":"long"|"short","symbol":"BTCUSDT.P","entry":68314.5,"stop":65923.5,"targets":[70363.9,71730.2],"leverage":20}
|
||||
|
||||
For close/profit-take signals return:
|
||||
{"type":"close","direction":"long"|"short","symbol":"BTCUSDT.P","price":70880.1}
|
||||
|
||||
If the message is NOT a trading signal (spam, news, info), return:
|
||||
{"type":"none"}"""
|
||||
|
||||
|
||||
class LLMParser:
|
||||
def __init__(self, base_url: str, api_key: str, model: str):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.api_key = api_key
|
||||
self.model = model
|
||||
|
||||
async def parse(self, text: str) -> Signal | CloseSignal | None:
|
||||
"""Send text to LLM, parse JSON response into Signal/CloseSignal."""
|
||||
try:
|
||||
data = await self._call_llm(text)
|
||||
except Exception as e:
|
||||
log.warning(f"LLM parse failed: {e}")
|
||||
return None
|
||||
|
||||
if not data or data.get("type") == "none":
|
||||
return None
|
||||
|
||||
if data.get("type") == "signal":
|
||||
return self._build_signal(data)
|
||||
|
||||
if data.get("type") == "close":
|
||||
return self._build_close(data)
|
||||
|
||||
return None
|
||||
|
||||
async def _call_llm(self, text: str) -> dict | None:
|
||||
payload = {
|
||||
"model": self.model,
|
||||
"max_tokens": 256,
|
||||
"temperature": 0.0,
|
||||
"system": SYSTEM_PROMPT,
|
||||
"messages": [{"role": "user", "content": text}],
|
||||
}
|
||||
headers = {
|
||||
"x-api-key": self.api_key,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"content-type": "application/json",
|
||||
}
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(
|
||||
f"{self.base_url}/v1/messages",
|
||||
json=payload,
|
||||
headers=headers,
|
||||
timeout=aiohttp.ClientTimeout(total=10),
|
||||
) as resp:
|
||||
if resp.status != 200:
|
||||
body = await resp.text()
|
||||
log.warning(f"LLM HTTP {resp.status}: {body[:200]}")
|
||||
return None
|
||||
result = await resp.json()
|
||||
|
||||
# Extract text from Anthropic response format
|
||||
content = result.get("content", [])
|
||||
if not content:
|
||||
return None
|
||||
raw = content[0].get("text", "")
|
||||
|
||||
# Parse JSON from response (may have markdown fences)
|
||||
raw = raw.strip()
|
||||
if raw.startswith("```"):
|
||||
raw = raw.split("\n", 1)[-1].rsplit("```", 1)[0]
|
||||
return json.loads(raw)
|
||||
|
||||
@staticmethod
|
||||
def _build_signal(data: dict) -> Signal | None:
|
||||
try:
|
||||
raw_sym = data["symbol"]
|
||||
return Signal(
|
||||
direction=data["direction"],
|
||||
symbol=_convert_symbol(raw_sym),
|
||||
raw_symbol=raw_sym,
|
||||
entry=float(data["entry"]),
|
||||
stop=float(data["stop"]),
|
||||
targets=[float(t) for t in data["targets"]],
|
||||
leverage=int(data.get("leverage", 20)),
|
||||
)
|
||||
except (KeyError, ValueError, TypeError) as e:
|
||||
log.warning(f"LLM signal build failed: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _build_close(data: dict) -> CloseSignal | None:
|
||||
try:
|
||||
raw_sym = data["symbol"]
|
||||
return CloseSignal(
|
||||
direction=data["direction"],
|
||||
symbol=_convert_symbol(raw_sym),
|
||||
price=float(data.get("price", 0)),
|
||||
)
|
||||
except (KeyError, ValueError, TypeError) as e:
|
||||
log.warning(f"LLM close build failed: {e}")
|
||||
return None
|
||||
@@ -0,0 +1,157 @@
|
||||
"""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())
|
||||
@@ -0,0 +1,4 @@
|
||||
telethon>=1.36
|
||||
ccxt>=4.0
|
||||
pyyaml>=6.0
|
||||
python-dotenv>=1.0
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Parse CryptoVolk signal bot messages.
|
||||
|
||||
Handles Russian, English, and emoji-only formats.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Signal:
|
||||
direction: str # "long" | "short"
|
||||
symbol: str # ccxt: BTC/USDT:USDT
|
||||
raw_symbol: str # original: BTCUSDT
|
||||
entry: float
|
||||
stop: float
|
||||
targets: list[float]
|
||||
leverage: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class CloseSignal:
|
||||
direction: str # original position direction
|
||||
symbol: str
|
||||
price: float
|
||||
|
||||
|
||||
def _convert_symbol(raw: str) -> str:
|
||||
"""BTCUSDT.P -> BTC/USDT:USDT"""
|
||||
s = raw.lstrip("#").replace(".P", "")
|
||||
for quote in ("USDT", "USDC"):
|
||||
if s.endswith(quote):
|
||||
base = s[: -len(quote)]
|
||||
return f"{base}/{quote}:{quote}"
|
||||
return f"{s}/USDT:USDT"
|
||||
|
||||
|
||||
def _find_number(text: str, patterns: list[str]) -> float | None:
|
||||
"""Try multiple regex patterns, return first match as float."""
|
||||
for pat in patterns:
|
||||
m = re.search(pat, text, re.IGNORECASE)
|
||||
if m:
|
||||
return float(m.group(1))
|
||||
return None
|
||||
|
||||
|
||||
def parse_signal(text: str) -> Signal | None:
|
||||
"""Parse new entry signal."""
|
||||
# Direction: emoji + keyword
|
||||
upper = text.upper()
|
||||
if ("LONG" in upper) and ("\U0001f7e2" in text or "LONG" in upper):
|
||||
direction = "long"
|
||||
elif ("SHORT" in upper) and ("\U0001f534" in text or "SHORT" in upper):
|
||||
direction = "short"
|
||||
else:
|
||||
return None
|
||||
|
||||
# Symbol: #BTCUSDT.P
|
||||
m = re.search(r"#(\w+\.P)", text)
|
||||
if not m:
|
||||
return None
|
||||
raw_sym = m.group(1)
|
||||
symbol = _convert_symbol(raw_sym)
|
||||
|
||||
# Entry price: Вход / Entry / 📍 Вход
|
||||
entry = _find_number(text, [
|
||||
r"Вход[:\s]*([\d.]+)",
|
||||
r"Entry[:\s]*([\d.]+)",
|
||||
r"📍\s*(?:Вход|Entry)?[:\s]*([\d.]+)",
|
||||
])
|
||||
if entry is None:
|
||||
return None
|
||||
|
||||
# Stop-loss: Стоп / Stop / SL / ⛔ Стоп
|
||||
stop = _find_number(text, [
|
||||
r"Стоп[:\s]*([\d.]+)",
|
||||
r"Stop[:\s]*([\d.]+)",
|
||||
r"SL[:\s]*([\d.]+)",
|
||||
r"⛔️?\s*(?:Стоп|Stop|SL)?[:\s]*([\d.]+)",
|
||||
])
|
||||
if stop is None:
|
||||
return None
|
||||
|
||||
# Targets: Цель / Target / TP / 🎯 Цель
|
||||
targets = []
|
||||
for pat in [
|
||||
r"Цель\s*\d*[:\s]*([\d.]+)",
|
||||
r"Target\s*\d*[:\s]*([\d.]+)",
|
||||
r"TP\s*\d*[:\s]*([\d.]+)",
|
||||
r"🎯\s*(?:Цель|Target|TP)?\s*\d*[:\s]*([\d.]+)",
|
||||
]:
|
||||
found = [float(x) for x in re.findall(pat, text, re.IGNORECASE)]
|
||||
if found:
|
||||
targets = found
|
||||
break
|
||||
if not targets:
|
||||
return None
|
||||
|
||||
# Leverage: Плечо / Leverage / X
|
||||
lev = _find_number(text, [
|
||||
r"Плечо[:\s]*(\d+)",
|
||||
r"Leverage[:\s]*(\d+)",
|
||||
r"(\d+)\s*[Xx](?:\s|$)",
|
||||
])
|
||||
leverage = int(lev) if lev else 20
|
||||
|
||||
return Signal(direction, symbol, raw_sym, entry, stop, targets, leverage)
|
||||
|
||||
|
||||
def parse_close(text: str) -> CloseSignal | None:
|
||||
"""Parse profit-taking / close recommendation."""
|
||||
upper = text.upper()
|
||||
is_close = any(kw in text for kw in [
|
||||
"Фиксация прибыли", "Take profit", "Close position",
|
||||
]) or ("✅" in text and "#" in text)
|
||||
|
||||
if not is_close:
|
||||
return None
|
||||
|
||||
direction = "long" if "LONG" in upper else "short" if "SHORT" in upper else None
|
||||
if direction is None:
|
||||
return None
|
||||
|
||||
m = re.search(r"#(\w+\.P)", text)
|
||||
if not m:
|
||||
return None
|
||||
symbol = _convert_symbol(m.group(1))
|
||||
|
||||
price = _find_number(text, [
|
||||
r"Цена[:\s]*([\d.]+)",
|
||||
r"Price[:\s]*([\d.]+)",
|
||||
r"📊\s*[:\s]*([\d.]+)",
|
||||
])
|
||||
|
||||
return CloseSignal(direction, symbol, price or 0.0)
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
"""Tests for regex + LLM signal parsers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
|
||||
from signal_parser import parse_signal, parse_close, Signal, CloseSignal
|
||||
from llm_parser import LLMParser
|
||||
|
||||
# ── Test data ────────────────────────────────────────────────────────
|
||||
|
||||
SIGNAL_RU = """🟢 LONG #BTCUSDT.P
|
||||
|
||||
📍 Вход: 68314.5
|
||||
⛔️ Стоп: 65923.5 (3.5%)
|
||||
|
||||
🎯 Цель 1: 70363.9 (3%)
|
||||
🎯 Цель 2: 71730.2 (5%)
|
||||
🎯 Цель 3: 72413.4 (6%)
|
||||
🎯 Цель 4: 73096.5 (7%)
|
||||
|
||||
📌 После достижения 3-го тейка рекомендуется поставить стоп в безубыток (Б/У).
|
||||
|
||||
⚙️ Плечо: 20X
|
||||
💰 Риск: до 3% от депозита"""
|
||||
|
||||
SIGNAL_EN = """🟢 LONG #ETHUSDT.P
|
||||
|
||||
Entry: 3450.5
|
||||
Stop: 3350.0 (2.9%)
|
||||
|
||||
Target 1: 3550.0 (2.9%)
|
||||
Target 2: 3650.0 (5.8%)
|
||||
|
||||
Leverage: 15X"""
|
||||
|
||||
SIGNAL_SHORT = """🔴 SHORT #SOLUSDT.P
|
||||
|
||||
📍 Вход: 180.50
|
||||
⛔️ Стоп: 190.00 (5.3%)
|
||||
|
||||
🎯 Цель 1: 170.00 (5.8%)
|
||||
🎯 Цель 2: 160.00 (11.4%)
|
||||
🎯 Цель 3: 150.00 (16.9%)
|
||||
|
||||
⚙️ Плечо: 10X"""
|
||||
|
||||
CLOSE_RU = """🎯 Фиксация прибыли по LONG позиции
|
||||
✅ #BTCUSDT.P
|
||||
📊 Цена: 70880.1"""
|
||||
|
||||
CLOSE_EN = """✅ Close position SHORT #ETHUSDT.P
|
||||
Price: 3200.0"""
|
||||
|
||||
SPAM_MESSAGES = [
|
||||
"🎁 Нажми «+», если хочешь получить мини курс трейдинга в подарок 🎁",
|
||||
"😀 РАСПИСАНИЕ ЭФИРОВ НА СЛЕДУЮЩУЮ НЕДЕЛЮ",
|
||||
"Ну что, получилось разобраться с инструкцией?",
|
||||
"👋 Отлично, супер, что вышло разобраться.",
|
||||
"",
|
||||
]
|
||||
|
||||
# Unusual format that regex won't parse but LLM should
|
||||
SIGNAL_UNUSUAL = """LONG позиция по #XRPUSDT.P
|
||||
Цена входа — 0.62
|
||||
Защитный стоп — 0.58
|
||||
Первая цель — 0.66
|
||||
Вторая цель — 0.70
|
||||
Третья цель — 0.75
|
||||
Кредитное плечо 20"""
|
||||
|
||||
|
||||
# ── Regex tests ──────────────────────────────────────────────────────
|
||||
|
||||
def test_regex():
|
||||
passed = 0
|
||||
failed = 0
|
||||
|
||||
def check(name, result, expected_type, checks=None):
|
||||
nonlocal passed, failed
|
||||
if expected_type is None:
|
||||
if result is None:
|
||||
print(f" ✓ {name}: None")
|
||||
passed += 1
|
||||
else:
|
||||
print(f" ✗ {name}: expected None, got {result}")
|
||||
failed += 1
|
||||
return
|
||||
if result is None:
|
||||
print(f" ✗ {name}: expected {expected_type.__name__}, got None")
|
||||
failed += 1
|
||||
return
|
||||
if not isinstance(result, expected_type):
|
||||
print(f" ✗ {name}: wrong type {type(result).__name__}")
|
||||
failed += 1
|
||||
return
|
||||
if checks:
|
||||
for field, expected in checks.items():
|
||||
actual = getattr(result, field, "MISSING")
|
||||
if actual != expected:
|
||||
print(f" ✗ {name}.{field}: {actual} != {expected}")
|
||||
failed += 1
|
||||
return
|
||||
print(f" ✓ {name}: OK")
|
||||
passed += 1
|
||||
|
||||
print("\n=== Regex Parser Tests ===")
|
||||
|
||||
# Signals
|
||||
check("RU LONG", parse_signal(SIGNAL_RU), Signal, {
|
||||
"direction": "long",
|
||||
"symbol": "BTC/USDT:USDT",
|
||||
"entry": 68314.5,
|
||||
"stop": 65923.5,
|
||||
"leverage": 20,
|
||||
})
|
||||
r = parse_signal(SIGNAL_RU)
|
||||
check("RU targets count", r, Signal)
|
||||
if r:
|
||||
assert len(r.targets) == 4, f"Expected 4 targets, got {len(r.targets)}"
|
||||
print(f" ✓ RU targets: {r.targets}")
|
||||
passed += 1
|
||||
|
||||
check("EN LONG", parse_signal(SIGNAL_EN), Signal, {
|
||||
"direction": "long",
|
||||
"symbol": "ETH/USDT:USDT",
|
||||
"entry": 3450.5,
|
||||
"stop": 3350.0,
|
||||
"leverage": 15,
|
||||
})
|
||||
|
||||
check("SHORT", parse_signal(SIGNAL_SHORT), Signal, {
|
||||
"direction": "short",
|
||||
"symbol": "SOL/USDT:USDT",
|
||||
"entry": 180.50,
|
||||
"stop": 190.00,
|
||||
"leverage": 10,
|
||||
})
|
||||
|
||||
# Close signals
|
||||
check("Close RU", parse_close(CLOSE_RU), CloseSignal, {
|
||||
"direction": "long",
|
||||
"symbol": "BTC/USDT:USDT",
|
||||
"price": 70880.1,
|
||||
})
|
||||
|
||||
check("Close EN", parse_close(CLOSE_EN), CloseSignal, {
|
||||
"direction": "short",
|
||||
"symbol": "ETH/USDT:USDT",
|
||||
"price": 3200.0,
|
||||
})
|
||||
|
||||
# Spam rejection
|
||||
for i, spam in enumerate(SPAM_MESSAGES):
|
||||
check(f"Spam #{i+1}", parse_signal(spam), None)
|
||||
check(f"Spam close #{i+1}", parse_close(spam), None)
|
||||
|
||||
# Unusual format (regex should fail)
|
||||
check("Unusual (regex miss)", parse_signal(SIGNAL_UNUSUAL), None)
|
||||
|
||||
print(f"\nRegex: {passed} passed, {failed} failed")
|
||||
return failed
|
||||
|
||||
|
||||
# ── LLM tests ────────────────────────────────────────────────────────
|
||||
|
||||
async def test_llm():
|
||||
llm = LLMParser(
|
||||
base_url="https://api.z.ai/api/anthropic",
|
||||
api_key="4d13fce5f9f247f18e2670ee00a369d7.PWbacOpikzPJ62Qu",
|
||||
model="glm-4.7",
|
||||
)
|
||||
passed = 0
|
||||
failed = 0
|
||||
|
||||
print("\n=== LLM Parser Tests ===")
|
||||
|
||||
# Test 1: Standard RU signal
|
||||
r = await llm.parse(SIGNAL_RU)
|
||||
if isinstance(r, Signal) and r.direction == "long" and r.entry == 68314.5:
|
||||
print(f" ✓ LLM RU signal: {r.direction} {r.symbol} entry={r.entry}")
|
||||
passed += 1
|
||||
else:
|
||||
print(f" ✗ LLM RU signal: {r}")
|
||||
failed += 1
|
||||
|
||||
# Test 2: Unusual format (regex can't parse, LLM should)
|
||||
r = await llm.parse(SIGNAL_UNUSUAL)
|
||||
if isinstance(r, Signal) and r.direction == "long" and abs(r.entry - 0.62) < 0.01:
|
||||
print(f" ✓ LLM unusual: {r.direction} {r.symbol} entry={r.entry} targets={r.targets}")
|
||||
passed += 1
|
||||
else:
|
||||
print(f" ✗ LLM unusual: {r}")
|
||||
failed += 1
|
||||
|
||||
# Test 3: Close signal
|
||||
r = await llm.parse(CLOSE_RU)
|
||||
if isinstance(r, CloseSignal) and r.direction == "long":
|
||||
print(f" ✓ LLM close: {r.direction} {r.symbol} price={r.price}")
|
||||
passed += 1
|
||||
else:
|
||||
print(f" ✗ LLM close: {r}")
|
||||
failed += 1
|
||||
|
||||
# Test 4: Spam rejection
|
||||
r = await llm.parse(SPAM_MESSAGES[0])
|
||||
if r is None:
|
||||
print(f" ✓ LLM spam: rejected")
|
||||
passed += 1
|
||||
else:
|
||||
print(f" ✗ LLM spam: should be None, got {r}")
|
||||
failed += 1
|
||||
|
||||
# Test 5: SHORT signal
|
||||
r = await llm.parse(SIGNAL_SHORT)
|
||||
if isinstance(r, Signal) and r.direction == "short":
|
||||
print(f" ✓ LLM short: {r.direction} {r.symbol} stop={r.stop}")
|
||||
passed += 1
|
||||
else:
|
||||
print(f" ✗ LLM short: {r}")
|
||||
failed += 1
|
||||
|
||||
print(f"\nLLM: {passed} passed, {failed} failed")
|
||||
return failed
|
||||
|
||||
|
||||
# ── Main ─────────────────────────────────────────────────────────────
|
||||
|
||||
if __name__ == "__main__":
|
||||
regex_fails = test_regex()
|
||||
llm_fails = asyncio.run(test_llm())
|
||||
total_fails = regex_fails + llm_fails
|
||||
print(f"\n{'='*40}")
|
||||
print(f"Total: {total_fails} failures")
|
||||
sys.exit(1 if total_fails else 0)
|
||||
Reference in New Issue
Block a user