feat: AI-аналитика дня через GLM (Z.AI proxy)
- gather_daily_data() собирает все данные дня в JSON - get_ai_daily_analytics() вызывает GLM с детальным промптом - Утренний отчёт + /report теперь отправляют AI-аналитику - Temperature=0, лимит 1500 символов, русский - Требует REMIZOV_LLM_TOKEN в env Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -189,7 +189,7 @@ def daemon():
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
|
||||
from .core.executor import run_cycle
|
||||
from .notify import (format_cycle_report, format_morning_report,
|
||||
from .notify import (format_cycle_report, format_morning_report_with_ai,
|
||||
format_startup_details,
|
||||
format_status_report, send_status, send_telegram)
|
||||
from .web.app import create_app
|
||||
@@ -247,9 +247,13 @@ def daemon():
|
||||
def morning_report():
|
||||
c = get_db()
|
||||
init_db(c)
|
||||
report = format_morning_report(cfg, c)
|
||||
report, ai_text = format_morning_report_with_ai(cfg, c)
|
||||
c.close()
|
||||
send_telegram(cfg.telegram, report)
|
||||
if ai_text:
|
||||
send_telegram(cfg.telegram,
|
||||
"\U0001f9e0 <b>AI-аналитика</b>\n\n"
|
||||
+ _escape_html_safe(ai_text))
|
||||
|
||||
scheduler.add_job(morning_report, "cron", hour=0, minute=0)
|
||||
click.echo("Morning report scheduled: daily at 00:00 UTC (10:00 AEST)")
|
||||
@@ -270,6 +274,11 @@ def daemon():
|
||||
send_status(cfg.telegram, "stop")
|
||||
|
||||
|
||||
def _escape_html_safe(text: str) -> str:
|
||||
"""Escape HTML special chars in AI response for Telegram."""
|
||||
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
|
||||
|
||||
def _send_with_keyboard(cfg, text: str, keyboard=None):
|
||||
"""Send Telegram message with optional inline keyboard."""
|
||||
import httpx
|
||||
@@ -366,7 +375,8 @@ def _start_telegram_listener(cfg, get_db_fn):
|
||||
|
||||
import httpx
|
||||
|
||||
from .notify import format_morning_report, format_status_report, send_telegram
|
||||
from .notify import (format_morning_report_with_ai, format_status_report,
|
||||
send_telegram)
|
||||
|
||||
# Map button text to commands
|
||||
_button_map = {
|
||||
@@ -388,9 +398,13 @@ def _start_telegram_listener(cfg, get_db_fn):
|
||||
send_telegram(cfg.telegram, report)
|
||||
elif cmd == "/report":
|
||||
conn = get_db_fn()
|
||||
report = format_morning_report(cfg, conn)
|
||||
report, ai_text = format_morning_report_with_ai(cfg, conn)
|
||||
conn.close()
|
||||
send_telegram(cfg.telegram, report)
|
||||
if ai_text:
|
||||
send_telegram(cfg.telegram,
|
||||
"\U0001f9e0 <b>AI-аналитика</b>\n\n"
|
||||
+ _escape_html_safe(ai_text))
|
||||
elif cmd == "/leverage":
|
||||
_handle_leverage(cfg, mapped, send_telegram)
|
||||
elif cmd == "/balance":
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"""Telegram notifications — send trade alerts."""
|
||||
"""Telegram notifications — send trade alerts + AI daily analytics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
from .config import TelegramConfig
|
||||
from .config import LLMConfig, TelegramConfig
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -373,6 +374,233 @@ def format_morning_report(cfg, conn) -> str:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def gather_daily_data(cfg, conn) -> dict:
|
||||
"""Collect all daily trading data for AI analytics."""
|
||||
from datetime import datetime, timedelta, timezone, date
|
||||
from .state import get_all_assets, get_open_position
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
since = (now - timedelta(hours=24)).isoformat()
|
||||
LIVE_START = date(2026, 3, 8)
|
||||
live_days = (now.date() - LIVE_START).days
|
||||
|
||||
active_tickers = {a.ticker for a in cfg.assets}
|
||||
assets = [a for a in get_all_assets(conn) if a["ticker"] in active_tickers]
|
||||
|
||||
# Exchange balance
|
||||
exchange_balance = _get_exchange_balance(cfg)
|
||||
if exchange_balance is None:
|
||||
snap = conn.execute(
|
||||
"SELECT exchange_balance FROM balance_snapshots "
|
||||
"WHERE exchange_balance IS NOT NULL ORDER BY id DESC LIMIT 1"
|
||||
).fetchone()
|
||||
exchange_balance = snap["exchange_balance"] if snap else sum(a["equity"] for a in assets)
|
||||
|
||||
total_initial = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets)
|
||||
|
||||
# Open positions
|
||||
open_positions = []
|
||||
for a in assets:
|
||||
pos = get_open_position(conn, a["ticker"])
|
||||
if pos:
|
||||
cur_price = _get_current_price(cfg, a["ticker"])
|
||||
upnl = 0.0
|
||||
if cur_price:
|
||||
upnl = pos["pos_size"] * (cur_price - pos["entry_price"]) * pos["direction"]
|
||||
open_positions.append({
|
||||
"ticker": a["ticker"],
|
||||
"direction": "LONG" if pos["direction"] == 1 else "SHORT",
|
||||
"entry_price": pos["entry_price"],
|
||||
"current_price": cur_price,
|
||||
"unrealized_pnl": round(upnl, 2),
|
||||
"stop_price": pos["stop_price"],
|
||||
"pos_value": pos["pos_value"],
|
||||
})
|
||||
|
||||
# Closed trades last 24h
|
||||
rows = conn.execute(
|
||||
"SELECT ticker, direction, entry_price, exit_price, exit_reason, pnl_net, pnl_pct "
|
||||
"FROM positions WHERE status='closed' AND exit_date >= ? "
|
||||
"AND exit_reason NOT IN ('live_buy_failed', 'manual_reset', 'phantom_cleanup', 'portfolio_rebalance') "
|
||||
"ORDER BY id DESC", (since[:10],)
|
||||
).fetchall()
|
||||
closed_trades = [{
|
||||
"ticker": r["ticker"],
|
||||
"direction": "LONG" if r["direction"] == 1 else "SHORT",
|
||||
"entry_price": r["entry_price"],
|
||||
"exit_price": r["exit_price"],
|
||||
"exit_reason": r["exit_reason"],
|
||||
"pnl": round(r["pnl_net"] or 0, 2),
|
||||
"pnl_pct": round(r["pnl_pct"] or 0, 2),
|
||||
} for r in rows]
|
||||
|
||||
# Per-asset stats
|
||||
asset_stats = []
|
||||
for a in sorted(assets, key=lambda x: x["ticker"]):
|
||||
tc = a["trades_count"]
|
||||
wr = a["wins"] / tc * 100 if tc > 0 else 0
|
||||
asset_stats.append({
|
||||
"ticker": a["ticker"],
|
||||
"trades": tc,
|
||||
"wins": a["wins"],
|
||||
"losses": a["losses"],
|
||||
"win_rate": round(wr, 1),
|
||||
"total_pnl": round(a["total_pnl"] or 0, 2),
|
||||
"equity": round(a["equity"], 2),
|
||||
"cb_active": bool(a["cb_active"]),
|
||||
"consecutive_losses": a.get("consecutive_losses") or 0,
|
||||
})
|
||||
|
||||
# Signals last 24h
|
||||
signals = conn.execute(
|
||||
"SELECT ticker, action, correlation, direction, details "
|
||||
"FROM signals WHERE created_at >= ? ORDER BY id DESC",
|
||||
(since,)
|
||||
).fetchall()
|
||||
signal_summary = [{"ticker": s["ticker"], "action": s["action"],
|
||||
"correlation": round(s["correlation"] or 0, 3),
|
||||
"details": s["details"]} for s in signals]
|
||||
|
||||
# CB events last 24h
|
||||
cb_events = conn.execute(
|
||||
"SELECT ticker, action, reason, details "
|
||||
"FROM cb_events WHERE created_at >= ? ORDER BY id DESC",
|
||||
(since,)
|
||||
).fetchall()
|
||||
cb_list = [{"ticker": c["ticker"], "action": c["action"],
|
||||
"reason": c["reason"]} for c in cb_events]
|
||||
|
||||
# Total real trades
|
||||
total_real = conn.execute(
|
||||
"SELECT COUNT(*) as cnt, SUM(CASE WHEN pnl_net > 0 THEN 1 ELSE 0 END) as wins "
|
||||
"FROM positions WHERE status='closed' "
|
||||
"AND exit_reason NOT IN ('live_buy_failed', 'manual_reset', 'phantom_cleanup', 'portfolio_rebalance')"
|
||||
).fetchone()
|
||||
|
||||
# Balance history (last 7 days)
|
||||
balance_history = conn.execute(
|
||||
"SELECT date, exchange_balance FROM balance_snapshots "
|
||||
"WHERE exchange_balance IS NOT NULL ORDER BY id DESC LIMIT 7"
|
||||
).fetchall()
|
||||
balance_hist = [{"date": b["date"], "balance": round(b["exchange_balance"], 2)}
|
||||
for b in balance_history]
|
||||
|
||||
return {
|
||||
"date": now.strftime("%Y-%m-%d"),
|
||||
"live_day": live_days,
|
||||
"mode": cfg.mode,
|
||||
"balance": round(exchange_balance, 2),
|
||||
"initial_capital": total_initial,
|
||||
"total_return_pct": round((exchange_balance / total_initial - 1) * 100, 2) if total_initial > 0 else 0,
|
||||
"leverage": cfg.risk.leverage,
|
||||
"open_positions": open_positions,
|
||||
"closed_trades_24h": closed_trades,
|
||||
"asset_stats": asset_stats,
|
||||
"signals_24h": signal_summary,
|
||||
"cb_events_24h": cb_list,
|
||||
"total_trades": total_real["cnt"] if total_real else 0,
|
||||
"total_wins": total_real["wins"] if total_real else 0,
|
||||
"balance_history_7d": balance_hist,
|
||||
"risk_per_trade": cfg.risk.per_trade,
|
||||
"stop_scale": cfg.risk.stop_scale,
|
||||
"safety_stop_pct": cfg.risk.safety_stop_pct,
|
||||
}
|
||||
|
||||
|
||||
_AI_ANALYTICS_PROMPT = """Ты — старший квант-аналитик с 15-летним опытом алгоритмической торговли криптовалютами.
|
||||
Проанализируй работу торгового бота RemizovTrader за прошедший день.
|
||||
|
||||
Бот использует модель RemizovNet (PDE/SDE solver) для предсказания цен. Стратегия:
|
||||
- Вход по shape confirmation (корреляция предсказания с реальностью > threshold)
|
||||
- Адаптивные параметры: K (горизонт), stop multiplier по ATR-режиму
|
||||
- 2x spot margin leverage на Bybit
|
||||
- Portfolio: 7 криптовалют с весами
|
||||
- Circuit breaker при ATR14/ATR50 > 3 или DD > 20%
|
||||
|
||||
ДАННЫЕ ЗА ДЕНЬ:
|
||||
{data_json}
|
||||
|
||||
ИНСТРУКЦИИ:
|
||||
1. Проанализируй общую производительность портфеля (баланс, PnL, return%)
|
||||
2. Оцени каждый открытый/закрытый трейд — был ли он обоснован?
|
||||
3. Обрати внимание на win rate и его тренд
|
||||
4. Оцени risk management (стопы, CB, drawdown)
|
||||
5. Найди паттерны: какие активы работают лучше/хуже, почему
|
||||
6. Дай конкретные рекомендации (НЕ общие фразы, а специфичные для этих данных)
|
||||
7. Если есть проблемы — укажи прямо, без приукрашивания
|
||||
|
||||
ФОРМАТ ОТВЕТА:
|
||||
Пиши на русском, кратко и по делу. Используй структуру:
|
||||
|
||||
ИТОГИ ДНЯ
|
||||
(2-3 предложения: баланс, PnL, ключевое событие)
|
||||
|
||||
ПОЗИЦИИ
|
||||
(анализ каждой открытой/закрытой позиции)
|
||||
|
||||
РИСКИ
|
||||
(оценка текущих рисков, CB, drawdown)
|
||||
|
||||
РЕКОМЕНДАЦИИ
|
||||
(2-3 конкретных действия)
|
||||
|
||||
ПРОГНОЗ
|
||||
(краткий взгляд на следующие 24ч на основе данных)
|
||||
|
||||
Максимум 1500 символов. Без markdown-разметки, без эмодзи, без HTML тегов."""
|
||||
|
||||
|
||||
def get_ai_daily_analytics(cfg, conn) -> str | None:
|
||||
"""Generate AI daily analytics via GLM. Returns analysis text or None."""
|
||||
if not cfg.llm.enabled or not cfg.llm.api_key:
|
||||
log.info("AI analytics skipped: LLM disabled or no API key")
|
||||
return None
|
||||
|
||||
data = gather_daily_data(cfg, conn)
|
||||
data_json = json.dumps(data, ensure_ascii=False, indent=2)
|
||||
prompt = _AI_ANALYTICS_PROMPT.format(data_json=data_json)
|
||||
|
||||
try:
|
||||
resp = httpx.post(
|
||||
f"{cfg.llm.base_url}/v1/messages",
|
||||
headers={
|
||||
"x-api-key": cfg.llm.api_key,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"content-type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": cfg.llm.model,
|
||||
"max_tokens": 1024,
|
||||
"temperature": 0,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
},
|
||||
timeout=60,
|
||||
)
|
||||
|
||||
if resp.status_code != 200:
|
||||
log.warning("AI analytics API error %d: %s", resp.status_code, resp.text[:200])
|
||||
return None
|
||||
|
||||
result = resp.json()
|
||||
text = result.get("content", [{}])[0].get("text", "")
|
||||
if not text:
|
||||
log.warning("AI analytics: empty response")
|
||||
return None
|
||||
|
||||
return text.strip()
|
||||
|
||||
except (httpx.HTTPError, KeyError, ValueError) as e:
|
||||
log.warning("AI analytics failed: %s", e)
|
||||
return None
|
||||
|
||||
|
||||
def format_morning_report_with_ai(cfg, conn) -> tuple[str, str | None]:
|
||||
"""Format morning report + AI analytics. Returns (report, ai_text)."""
|
||||
report = format_morning_report(cfg, conn)
|
||||
ai_text = get_ai_daily_analytics(cfg, conn)
|
||||
return report, ai_text
|
||||
|
||||
|
||||
def format_cycle_report(logs: list[str]) -> str:
|
||||
"""Format cycle logs into a Telegram message."""
|
||||
if not logs:
|
||||
|
||||
Reference in New Issue
Block a user