feat: daemon mode (APScheduler) + Telegram alerts (A6-A7)

- `remizov-trader daemon` — auto-cycle по расписанию + web dashboard
- Telegram notify при каждом цикле (SIGNAL/CLOSE/CB events)
- Зависимости: apscheduler, httpx

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-08 23:24:17 +10:00
co-authored by Claude Opus 4.6
parent 8800ffb604
commit fedf2f3e37
3 changed files with 103 additions and 0 deletions
+2
View File
@@ -18,6 +18,8 @@ dependencies = [
"jinja2>=3.1",
"pyyaml>=6.0",
"click>=8.1",
"apscheduler>=3.10,<4",
"httpx>=0.27",
]
[project.optional-dependencies]
+50
View File
@@ -179,6 +179,56 @@ def web():
uvicorn.run(app, host=cfg.web.host, port=cfg.web.port)
@main.command()
def daemon():
"""Run as daemon — auto-cycle on schedule + web dashboard."""
from apscheduler.schedulers.background import BackgroundScheduler
from .core.executor import run_cycle
from .notify import format_cycle_report, send_telegram
from .web.app import create_app
cfg = load_config()
def scheduled_cycle():
conn = get_db()
init_db(conn)
logs = run_cycle(conn, cfg)
conn.close()
for msg in logs:
click.echo(f" [{cfg.timeframe}] {msg}")
if cfg.telegram.enabled:
report = format_cycle_report(logs)
send_telegram(cfg.telegram, report)
scheduler = BackgroundScheduler()
# Schedule based on timeframe
hour, minute = (int(x) for x in cfg.check_time.split(":"))
if cfg.timeframe == "1d":
scheduler.add_job(scheduled_cycle, "cron", hour=hour, minute=minute)
click.echo(f"Scheduled: daily at {cfg.check_time}")
elif cfg.timeframe == "4h":
scheduler.add_job(scheduled_cycle, "interval", hours=4)
click.echo("Scheduled: every 4 hours")
elif cfg.timeframe == "1h":
scheduler.add_job(scheduled_cycle, "interval", hours=1)
click.echo("Scheduled: every 1 hour")
scheduler.start()
click.echo("Daemon started. Web dashboard + scheduler running.")
# Run first cycle immediately
scheduled_cycle()
# Start web server (blocking)
import uvicorn
app = create_app(cfg)
uvicorn.run(app, host=cfg.web.host, port=cfg.web.port)
@main.command()
@click.argument("key")
@click.argument("value")
+51
View File
@@ -0,0 +1,51 @@
"""Telegram notifications — send trade alerts."""
from __future__ import annotations
import logging
import httpx
from .config import TelegramConfig
log = logging.getLogger(__name__)
def send_telegram(cfg: TelegramConfig, message: str) -> bool:
"""Send message via Telegram bot API. Returns True on success."""
if not cfg.enabled or not cfg.bot_token or not cfg.chat_id:
return False
url = f"https://api.telegram.org/bot{cfg.bot_token}/sendMessage"
try:
resp = httpx.post(url, json={
"chat_id": cfg.chat_id,
"text": message,
"parse_mode": "HTML",
}, timeout=10)
if resp.status_code != 200:
log.warning("Telegram API error: %s", resp.text)
return False
return True
except httpx.HTTPError as e:
log.warning("Telegram send failed: %s", e)
return False
def format_cycle_report(logs: list[str]) -> str:
"""Format cycle logs into a Telegram message."""
if not logs:
return "<b>RemizovTrader</b>\nCycle complete — no activity."
lines = ["<b>RemizovTrader</b>"]
for msg in logs:
if "SIGNAL" in msg or "CLOSED" in msg:
lines.append(f" {msg}")
elif "CB ON" in msg:
lines.append(f" {msg}")
elif "retrained" in msg:
lines.append(f" {msg}")
else:
lines.append(f" <i>{msg}</i>")
return "\n".join(lines)