fix: sizing по free balance + Bybit UTA margin бэктест (exp19)
executor: cap pos_value по свободному USDC (× 0.85 буфер на haircut/IM), синхронизация DB с реальным fill после исполнения ордера. exp19: реалистичная модель маржи Bybit — CVR, spot IM, IMR threshold. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -410,15 +410,30 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
stop_dist = max(atr * stop_mult * cfg.risk.stop_scale, entry_price * 0.005)
|
||||
stop_price = entry_price - direction * stop_dist
|
||||
|
||||
# Position sizing: weight-based (total_equity × weight × leverage)
|
||||
# Position sizing: weight-based with free balance check
|
||||
leverage = cfg.leverage_for(asset_cfg)
|
||||
if asset_cfg.weight > 0:
|
||||
# Weight-based: use exchange balance or total_capital
|
||||
from ..notify import _get_exchange_balance
|
||||
total_equity = _get_exchange_balance(cfg)
|
||||
if total_equity is None or total_equity < 1.0:
|
||||
total_equity = cfg.total_capital if cfg.total_capital > 0 else asset["equity"]
|
||||
pos_value = total_equity * asset_cfg.weight * leverage
|
||||
|
||||
# Cap by free USDC (Bybit available balance < free due to haircut + IM)
|
||||
if cfg.mode == "live":
|
||||
spot = _get_spot(cfg)
|
||||
free_usdc = spot.get_balance("USDC")
|
||||
# 15% buffer: Bybit deducts haircut (CVR) + spot IM from available
|
||||
max_margin = free_usdc * 0.85
|
||||
max_pos_value = max_margin * leverage
|
||||
if pos_value > max_pos_value:
|
||||
if max_pos_value < 5.0:
|
||||
return (f"margin skip: free ${free_usdc:.2f}, "
|
||||
f"max pos ${max_pos_value:.2f} < $5 — SKIP")
|
||||
log.info(f"{ticker}: capped pos_value ${pos_value:.2f} → "
|
||||
f"${max_pos_value:.2f} (free USDC: ${free_usdc:.2f})")
|
||||
pos_value = max_pos_value
|
||||
|
||||
if pos_value < 5.0: # Bybit min order
|
||||
return f"pos_value ${pos_value:.2f} < $5 min — SKIP"
|
||||
pos_size = pos_value / entry_price
|
||||
@@ -473,6 +488,20 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
fee_str = f" fee=${float(fee_cost):.2f}"
|
||||
else:
|
||||
fee_str = ""
|
||||
|
||||
# Update DB with actual fill (Bybit may have reduced the order)
|
||||
actual_cost = float(order.get("cost") or pos_value)
|
||||
actual_filled = float(order.get("filled") or pos_size)
|
||||
actual_price = float(order.get("average") or entry_price)
|
||||
if abs(actual_cost - pos_value) > 0.01:
|
||||
update_position(conn, pos_id,
|
||||
pos_value=actual_cost, pos_size=actual_filled,
|
||||
entry_price=actual_price)
|
||||
pos_value = actual_cost
|
||||
pos_size = actual_filled
|
||||
entry_price = actual_price
|
||||
fee_str += f" adjusted=${actual_cost:.2f}"
|
||||
|
||||
msg += f" [LIVE BUY OK{fee_str}]"
|
||||
log_order(conn, pos_id, "buy", asset_cfg.symbol, entry_price, order)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user