fix: показывать реальный баланс с биржи вместо DB equity

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-09 15:17:43 +10:00
co-authored by Claude Opus 4.6
parent 2e36837e80
commit 1c375cc0b0
+38 -12
View File
@@ -48,6 +48,28 @@ def send_status(cfg: TelegramConfig, event: str, details: str = "") -> bool:
return send_telegram(cfg, msg)
def _get_exchange_balance(cfg) -> float | None:
"""Fetch total portfolio balance from exchange (mark-to-market)."""
try:
from .core.spot import SpotExecutor
spot = SpotExecutor(cfg.exchange, leverage=cfg.risk.leverage)
spot._ensure_markets()
b = spot.exchange.fetch_balance()
total = 0.0
for coin in ["USDC", "USDT", "BTC", "ETH", "SOL", "AVAX", "LINK", "XRP"]:
amt = float(b.get(coin, {}).get("total", 0) or 0)
if amt < 0.0001:
continue
if coin in ("USDC", "USDT"):
total += amt
else:
price = spot.get_price(f"{coin}/USDC")
total += amt * price if price else 0
return total
except Exception:
return None
def _get_current_price(cfg, ticker):
"""Fetch current price for ticker via exchange."""
try:
@@ -72,30 +94,31 @@ def format_status_report(cfg, conn) -> str:
assets = [get_asset(conn, t) for t in active_tickers]
assets = [a for a in assets if a is not None]
total_equity = sum(a["equity"] for a in assets)
total_initial = cfg.initial_capital * len(assets) if assets else cfg.initial_capital
# Collect open positions and calculate unrealized PnL
# Get real balance from exchange (mark-to-market)
exchange_balance = _get_exchange_balance(cfg)
if exchange_balance is None:
# Fallback to DB equity
exchange_balance = sum(a["equity"] for a in assets)
total_pnl = exchange_balance - total_initial
total_pct = (exchange_balance / total_initial - 1) * 100 if total_initial > 0 else 0
# Collect open positions with current prices
open_positions = []
total_unrealized = 0.0
for a in assets:
pos = get_open_position(conn, a["ticker"])
if pos:
cur_price = _get_current_price(cfg, a["ticker"])
open_positions.append((a, pos, cur_price))
if cur_price:
total_unrealized += pos["pos_size"] * (cur_price - pos["entry_price"]) * pos["direction"]
total_balance = total_equity + total_unrealized
total_pnl = total_balance - total_initial
total_pct = (total_balance / total_initial - 1) * 100 if total_initial > 0 else 0
lines = ["\U0001f4ca <b>RemizovTrader</b>"]
lines.append("")
# --- Portfolio ---
lines.append(f"\U0001f4b0 <b>Портфель</b>")
lines.append(f" Баланс: <b>${total_balance:,.2f}</b> ({total_pct:+.1f}%)")
lines.append(f" Баланс: <b>${exchange_balance:,.2f}</b> ({total_pct:+.1f}%)")
lines.append(f" PnL: ${total_pnl:+,.2f}")
lines.append("")
@@ -153,14 +176,17 @@ def format_startup_details(cfg, conn) -> str:
assets = [get_asset(conn, t) for t in active_tickers]
assets = [a for a in assets if a is not None]
open_count = sum(1 for a in assets if get_open_position(conn, a["ticker"]))
total_equity = sum(a["equity"] for a in assets)
total_trades = sum(a["trades_count"] for a in assets)
exchange_balance = _get_exchange_balance(cfg)
if exchange_balance is None:
exchange_balance = sum(a["equity"] for a in assets)
lines = [
f"Сервер: <code>{platform.node()}</code>",
f"Режим: {cfg.mode} | TF: {cfg.timeframe}",
f"Активов: {len(cfg.assets)} | Позиций: {open_count}/{cfg.risk.max_open_positions}",
f"Капитал: ${total_equity:,.2f} | Сделок: {total_trades}",
f"Капитал: ${exchange_balance:,.2f} | Сделок: {total_trades}",
"",
f"Риск/сделка: {cfg.risk.per_trade*100:.0f}%",
f"Макс. позиция: {cfg.risk.max_position_pct*100:.0f}% от equity",