fix: защита от API-ошибок + fee-aware pos_size + error notifications в Telegram

- get_balance() возвращает None при ошибке API (не 0.0)
- reconcile пропускает актив при balance API error (предотвращает ложное закрытие)
- pos_size в БД обновляется после BUY с учётом комиссии (actual balance)
- safety stop использует actual balance вместо pos_size из БД
- Telegram error notifications с throttle (1/час на источник)
- stop update по cron :00,:15,:30,:45 + немедленный запуск при старте
- comprehensive logging всех ключевых действий executor

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-13 23:36:55 +10:00
co-authored by Claude Opus 4.6
parent 17feec9be1
commit de689e6e0a
3 changed files with 130 additions and 42 deletions
+70 -29
View File
@@ -2,12 +2,31 @@
from __future__ import annotations
import logging
import sys
import click
import numpy as np
import torch
log = logging.getLogger(__name__)
# Throttle error notifications: max 1 per source per hour
_last_error_sent: dict[str, float] = {}
_ERROR_COOLDOWN = 3600 # seconds
def _should_send_error(source: str) -> bool:
"""Return True if enough time passed since last error for this source."""
import time
now = time.time()
last = _last_error_sent.get(source, 0)
if now - last < _ERROR_COOLDOWN:
return False
_last_error_sent[source] = now
return True
from .config import load_config
from .state import get_db, init_db, get_all_assets, get_open_position, get_trade_history, upsert_asset
@@ -215,17 +234,23 @@ def daemon():
conn.close()
def scheduled_cycle():
conn = get_db()
init_db(conn)
logs = run_cycle(conn, cfg)
conn.close()
try:
conn = get_db()
init_db(conn)
logs = run_cycle(conn, cfg)
conn.close()
for msg in logs:
click.echo(f" {msg}")
for msg in logs:
click.echo(f" {msg}")
if cfg.telegram.enabled:
report = format_cycle_report(logs, cfg)
send_telegram(cfg.telegram, report)
if cfg.telegram.enabled:
report = format_cycle_report(logs, cfg)
send_telegram(cfg.telegram, report)
except Exception as e:
log.exception("Cycle error")
if cfg.telegram.enabled and _should_send_error("cycle"):
send_status(cfg.telegram, "error",
f"Цикл упал: <code>{_escape_html_safe(str(e)[:200])}</code>")
scheduler = BackgroundScheduler()
@@ -250,15 +275,21 @@ def daemon():
# Morning report at 00:00 UTC (10:00 AEST)
if cfg.telegram.enabled:
def morning_report():
c = get_db()
init_db(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))
try:
c = get_db()
init_db(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))
except Exception as e:
log.exception("Morning report error")
if _should_send_error("morning"):
send_status(cfg.telegram, "error",
f"Утренний отчёт упал: <code>{_escape_html_safe(str(e)[:200])}</code>")
scheduler.add_job(morning_report, "cron", hour=0, minute=0)
click.echo("Morning report scheduled: daily at 00:00 UTC (10:00 AEST)")
@@ -267,18 +298,24 @@ def daemon():
# Runs every 15 min so stops track price between 4h main cycles
if cfg.mode == "live":
def stop_update_cycle():
c = get_db()
init_db(c)
stop_logs = update_stops(c, cfg)
c.close()
for msg in stop_logs:
click.echo(f" [stops] {msg}")
if cfg.telegram.enabled and any("trailing stop" in m for m in stop_logs):
send_telegram(cfg.telegram,
"🔄 " + "\n".join(m for m in stop_logs if "trailing" in m or "safety" in m))
try:
c = get_db()
init_db(c)
stop_logs = update_stops(c, cfg)
c.close()
for msg in stop_logs:
click.echo(f" [stops] {msg}")
if cfg.telegram.enabled and any("trailing stop" in m for m in stop_logs):
send_telegram(cfg.telegram,
"🔄 " + "\n".join(m for m in stop_logs if "trailing" in m or "safety" in m))
except Exception as e:
log.exception("Stop update error")
if cfg.telegram.enabled and _should_send_error("stops"):
send_status(cfg.telegram, "error",
f"Обновление стопов упало: <code>{_escape_html_safe(str(e)[:200])}</code>")
scheduler.add_job(stop_update_cycle, "interval", minutes=15)
click.echo("Stop updates scheduled: every 15 min")
scheduler.add_job(stop_update_cycle, "cron", minute="0,15,30,45")
click.echo("Stop updates scheduled: every 15 min at :00,:15,:30,:45")
scheduler.start()
click.echo("Daemon started. Web dashboard + scheduler running.")
@@ -286,6 +323,10 @@ def daemon():
# Run first cycle immediately
scheduled_cycle()
# Run stop update immediately after first cycle (don't wait for next :00/:15/:30/:45)
if cfg.mode == "live":
stop_update_cycle()
# Start web server (blocking)
import uvicorn
app = create_app(cfg)
+50 -9
View File
@@ -55,6 +55,10 @@ def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
# Check actual coin balance on exchange
coin = asset_cfg.symbol.split("/")[0]
coin_balance = spot.get_balance(coin)
if coin_balance is None:
log.warning(f"{ticker}: reconcile skipped — balance API error")
logs.append(f"{ticker}: RECONCILE skipped — balance API error")
continue
min_threshold = pos["pos_size"] * 0.1 # <10% of position = closed
if coin_balance < min_threshold:
@@ -92,6 +96,8 @@ def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
spot.cancel_order(asset_cfg.symbol, safety_id)
dir_str = "LONG" if pos["direction"] == 1 else "SHORT"
log.warning(f"{ticker}: reconcile — {dir_str} closed externally "
f"@ ~${current_price:,.3f} PnL ${pnl_net:+,.2f}")
logs.append(f"{ticker}: RECONCILE — {dir_str} closed externally "
f"@ ~${current_price:,.3f} PnL ${pnl_net:+,.2f}")
else:
@@ -252,6 +258,8 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
prev_bal = prev_snap["exchange_balance"] if prev_snap else 0
record_deposit(conn, deposit, prev_bal, exchange_bal)
action = "пополнение" if deposit > 0 else "вывод"
log.info(f"Deposit detected: {action} ${abs(deposit):,.2f} "
f"(${prev_bal:,.2f} -> ${exchange_bal:,.2f})")
logs.append(f"DEPOSIT: {action} ${abs(deposit):,.2f} "
f"(${prev_bal:,.2f} → ${exchange_bal:,.2f})")
@@ -342,11 +350,15 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
# Update trailing stop only if NOT stopped (matches backtest order)
if not stopped and asset_cfg.trailing_stop:
old_stop = stop_price
best_price, stop_price = risk.update_trailing_stop(
last_price, best_price, stop_price, stop_dist, direction,
)
update_position(conn, pos["id"],
best_price=best_price, stop_price=stop_price)
if stop_price != old_stop:
log.info(f"{asset_cfg.ticker}: trailing stop "
f"${old_stop:,.3f} -> ${stop_price:,.3f} (price ${last_price:,.3f})")
# Check time exit (use per-asset model config) — can be disabled via config
time_exit = False
@@ -388,6 +400,9 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
dir_str = "LONG" if direction == 1 else "SHORT"
win_str = "WIN" if win else "LOSS"
log.info(f"{asset_cfg.ticker}: CLOSED {dir_str} ${entry_price:,.2f}->"
f"${exit_price:,.2f} ({exit_reason}) PnL ${pnl_net:+,.2f} "
f"equity ${new_equity:,.2f}")
msg = (f"CLOSED {dir_str} ${entry_price:,.2f}→${exit_price:,.2f} "
f"({exit_reason}) PnL ${pnl_net:+,.2f} [{win_str}]")
@@ -538,6 +553,9 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
if cfg.mode == "live":
spot = _get_spot(cfg)
free_usdc = spot.get_balance("USDC")
if free_usdc is None:
log.warning(f"{ticker}: balance API error during position sizing")
return "margin skip: balance API error — SKIP"
# 15% buffer: Bybit deducts haircut (CVR) + spot IM from available
max_margin = free_usdc * 0.85
max_pos_value = max_margin * leverage
@@ -585,6 +603,9 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
correlation=corr, direction=direction, action="open")
dir_str = "LONG" if direction == 1 else "SHORT"
log.info(f"{ticker}: SIGNAL {dir_str} @ ${entry_price:,.2f} "
f"stop=${stop_price:,.2f} dist=${stop_dist:,.3f} "
f"corr={corr:.3f} size=${pos_value:,.2f} K={K}")
msg = (f"SIGNAL {dir_str} @ ${entry_price:,.2f} "
f"stop ${stop_price:,.2f} corr={corr:.3f} size=${pos_value:,.2f}")
@@ -620,11 +641,21 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
msg += f" [LIVE BUY OK{fee_str}]"
log_order(conn, pos_id, "buy", asset_cfg.symbol, entry_price, order)
# Update pos_size to actual balance (fee in coin reduces it)
coin = asset_cfg.symbol.split("/")[0]
actual_bal = spot.get_balance(coin)
if actual_bal and actual_bal < pos_size:
log.info(f"{ticker}: pos_size adjusted for fee: "
f"{pos_size:.4f} -> {actual_bal:.4f}")
update_position(conn, pos_id, pos_size=actual_bal)
pos_size = actual_bal
# Place safety stop on exchange (hard protection against flash crash)
if cfg.risk.safety_stop_pct > 0:
safety_price = entry_price * (1.0 - cfg.risk.safety_stop_pct)
safety_size = actual_bal if actual_bal else pos_size
safety_order = spot.place_safety_stop(
asset_cfg.symbol, pos_size, safety_price)
asset_cfg.symbol, safety_size, safety_price)
if safety_order:
safety_id = safety_order.get("id") or "dry_run"
update_position(conn, pos_id, safety_stop_order_id=safety_id)
@@ -741,7 +772,8 @@ def update_stops(conn: sqlite3.Connection, cfg: Config) -> list[str]:
stopped = risk.is_stopped(current_price, stop_price, direction)
if stopped:
# Don't close here — let main cycle handle closing with proper PnL
# But log the alert
log.warning(f"{ticker}: STOP HIT @ ${current_price:,.3f} "
f"(stop ${stop_price:,.3f}) — awaiting main cycle")
logs.append(f"{ticker}: STOP HIT @ ${current_price:,.3f} "
f"(stop ${stop_price:,.3f}) — will close on next cycle")
continue
@@ -751,24 +783,33 @@ def update_stops(conn: sqlite3.Connection, cfg: Config) -> list[str]:
new_best, new_stop = risk.update_trailing_stop(
current_price, best_price, stop_price, stop_dist, direction,
)
if new_stop != stop_price:
stop_changed = new_stop != stop_price
if stop_changed:
update_position(conn, pos["id"],
best_price=new_best, stop_price=new_stop)
logs.append(f"{ticker}: trailing stop ${stop_price:,.3f} → "
f"${new_stop:,.3f} (price ${current_price:,.3f})")
# Re-place safety stop: place NEW first, then cancel old
# (if new fails, old still protects the position)
# Re-place safety stop if it changed OR is missing on exchange
safety_id = pos.get("safety_stop_order_id")
safety_missing = not safety_id or safety_id == "dry_run"
if stop_changed or safety_missing:
active_stop = new_stop if stop_changed else stop_price
# Use actual coin balance for safety stop (fee reduces pos_size)
coin = asset_cfg.symbol.split("/")[0]
actual_size = spot.get_balance(coin)
safety_size = actual_size if actual_size else pos["pos_size"]
new_safety = spot.place_safety_stop(
asset_cfg.symbol, pos["pos_size"], new_stop)
asset_cfg.symbol, safety_size, active_stop)
if new_safety:
new_safety_id = new_safety.get("id") or "dry_run"
# Cancel old only after new is confirmed
safety_id = pos.get("safety_stop_order_id")
if safety_id and safety_id != "dry_run":
if not safety_missing:
spot.cancel_order(asset_cfg.symbol, safety_id)
update_position(conn, pos["id"],
safety_stop_order_id=new_safety_id)
logs.append(f"{ticker}: safety stop moved to ${new_stop:,.3f}")
action = "restored" if safety_missing else "moved"
log.info(f"{ticker}: safety stop {action} to ${active_stop:,.3f}")
logs.append(f"{ticker}: safety stop {action} to ${active_stop:,.3f}")
return logs
+10 -4
View File
@@ -51,14 +51,14 @@ class SpotExecutor:
# Bybit UTA: spot margin is auto-enabled, setLeverage not supported for spot
self._margin_enabled = True
def get_balance(self, coin: str) -> float:
"""Get free balance for a coin."""
def get_balance(self, coin: str) -> float | None:
"""Get free balance for a coin. Returns None on API error."""
try:
b = self.exchange.fetch_balance()
return float(b.get(coin, {}).get("free", 0) or 0)
except Exception as e:
log.error(f"Balance fetch failed: {e}")
return 0.0
return None
def _fetch_order_details(self, order: dict, symbol: str,
amount: float, price: float,
@@ -124,6 +124,9 @@ class SpotExecutor:
# 4. Check balance (strict)
quote_free = self.get_balance(quote)
if quote_free is None:
log.error(f"BUY {symbol}: balance API error, aborting")
return None
if quote_free < quote_amount:
# Try to buy what we can afford
if quote_free >= min_cost:
@@ -224,7 +227,7 @@ class SpotExecutor:
if amount is None:
amount = self.get_balance(coin)
if amount <= 0:
if amount is None or amount <= 0:
log.warning(f"SELL {symbol}: nothing to sell ({coin} balance=0)")
return None
@@ -241,6 +244,9 @@ class SpotExecutor:
# 4. Check balance
coin_free = self.get_balance(coin)
if coin_free is None:
log.error(f"SELL {symbol}: balance API error, aborting")
return None
if coin_free < amount:
log.warning(f"SELL {symbol}: balance {coin_free} < requested {amount}, "
f"selling available")