"""Exp19: Realistic Bybit UTA spot margin model. Adds to exp16: - Collateral Value Ratio (CVR) per asset — haircut when converting USDC → crypto - Spot Initial Margin (IM) on borrowed amount - Available Balance = free_usdc - total_haircut - total_spot_IM - IMR threshold blocking (when account IMR >= (lev-1)/lev) - Market order buffer (slippage reserve) CVR values are conservative estimates based on Bybit docs: - BTC: 0.95 (confirmed via API), ETH: 0.925, SOL: 0.85 - ADA/DOT/XRP: 0.80, DOGE: 0.75 - USDC/USDT: 1.00 Spot IM Rate: ~10-15% of borrowed amount (asset-dependent). """ import sys from pathlib import Path from dataclasses import dataclass, field sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) sys.path.insert(0, str(Path(__file__).parent.parent)) import numpy as np import torch from remizov_trader.core import model as model_mod, signals, risk from remizov_trader.config import ModelConfig from common.metrics import compute_metrics, save_results from common.dataset import load_or_fetch, load_cached_model, save_cached_model TOTAL_CAPITAL = 114.0 K = 2 CORR_THRESH = 0.5 TRAILING_STOP = True TRAIN_RATIO = 0.3 SHIFT = 7 # Bybit spot margin costs INTEREST_RATE_DAILY = 0.0002 # 0.02%/day on borrowed amount COMMISSION = 0.001 # 0.1% per side MARKET_ORDER_BUFFER = 0.02 # 2% extra reserved for market order slippage # Bybit UTA: Collateral Value Ratio per asset # USDC spent → crypto bought at lower collateral value = haircut COLLATERAL_VALUE_RATIO = { "BTC-USD": 0.95, # confirmed from Bybit API "ETH-USD": 0.925, "SOL-USD": 0.85, "XRP-USD": 0.80, "ADA-USD": 0.80, "DOT-USD": 0.80, "DOGE-USD": 0.75, } # Spot Initial Margin Rate on borrowed amount (per asset) SPOT_IM_RATE = { "BTC-USD": 0.10, "ETH-USD": 0.10, "SOL-USD": 0.15, "XRP-USD": 0.15, "ADA-USD": 0.15, "DOT-USD": 0.15, "DOGE-USD": 0.20, } # Spot Maintenance Margin Rate (typically ~50% of IM) SPOT_MM_RATE = {k: v * 0.5 for k, v in SPOT_IM_RATE.items()} # Correlation groups — same as production CORRELATED_GROUPS = [ {"BTC-USD", "ETH-USD"}, {"ADA-USD", "DOT-USD", "XRP-USD"}, ] # Sharpe-optimal config from exp15, with per-asset K from exp18 ASSETS = [ {"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241, "K": 3}, {"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158, "K": 2}, {"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137, "K": 3}, {"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137, "K": 2}, {"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127, "K": 2}, {"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108, "K": 2}, {"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092, "K": 2}, ] @dataclass class Position: ticker: str direction: int entry_price: float entry_date: str stop_price: float stop_dist: float best_price: float pos_size: float pos_value: float margin_locked: float # USDC locked as collateral borrowed: float # amount borrowed from exchange haircut_loss: float # collateral value reduction (1 - CVR) * pos_value spot_im: float # initial margin frozen on borrowed amount k_used: int entry_bar: int def check_correlation_conflict(open_positions: dict, ticker: str, direction: int) -> str | None: for g in CORRELATED_GROUPS: if ticker not in g: continue for other in g: if other == ticker: continue if other in open_positions and open_positions[other].direction == direction: return f"correlated with {other}" return None def calc_available_balance(free_usdc: float, open_positions: dict) -> float: """Bybit Available Balance = free_usdc - total_haircut - total_spot_IM. This is what Bybit actually checks when you place an order. free_usdc already has margin_locked subtracted. But haircut and spot_IM are ADDITIONAL freezes on top. """ total_haircut = sum(p.haircut_loss for p in open_positions.values()) total_spot_im = sum(p.spot_im for p in open_positions.values()) return free_usdc - total_haircut - total_spot_im def calc_account_imr(free_usdc: float, open_positions: dict) -> float: """Account Initial Margin Rate = totalInitialMargin / totalEquity.""" total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values()) if total_equity <= 0: return 1.0 total_im = sum(p.margin_locked + p.spot_im for p in open_positions.values()) return total_im / total_equity def calc_required_capital(pos_value: float, leverage: int, ticker: str) -> dict: """Calculate all capital requirements for a new position. Returns dict with margin_needed, haircut, spot_im, total_frozen, borrowed. """ margin_needed = pos_value / leverage borrowed = pos_value - margin_needed cvr = COLLATERAL_VALUE_RATIO.get(ticker, 0.80) haircut = (1.0 - cvr) * pos_value # loss when USDC → crypto spot_im = borrowed * SPOT_IM_RATE.get(ticker, 0.15) buffer = pos_value * MARKET_ORDER_BUFFER # slippage reserve return { "margin_needed": margin_needed, "borrowed": borrowed, "haircut": haircut, "spot_im": spot_im, "buffer": buffer, "total_frozen": margin_needed + haircut + spot_im + buffer, } def main(): results_dir = Path(__file__).parent / "results" # ══════════════════════════════════════════════════ # FETCH DATA + TRAIN MODELS # ══════════════════════════════════════════════════ print(f"{'='*80}") print("EXP19: REALISTIC BYBIT UTA MARGIN MODEL") print(f"{'='*80}") print(f"Capital: ${TOTAL_CAPITAL} | Interest: {INTEREST_RATE_DAILY*100:.3f}%/day | " f"Commission: {COMMISSION*100:.1f}%/side") print(f"Haircut: CVR-based | Spot IM: per-asset | Market buffer: {MARKET_ORDER_BUFFER*100:.0f}%") print() dataset = load_or_fetch("default") asset_data = {} for a in ASSETS: ticker, tf = a["ticker"], a["tf"] ws, leverage, weight = a["ws"], a["leverage"], a["weight"] asset_k = a.get("K", K) print(f" {ticker} ({tf}, ws={ws}, K={asset_k})...", end=" ", flush=True) if ticker not in dataset: print("not in dataset") continue prices = dataset[ticker]["prices"] dates = dataset[ticker]["dates"] if len(prices) < ws + asset_k + SHIFT + 30: print("not enough data") continue data = signals.prepare_windows(prices, ws, SHIFT) if len(data) < 30: print(f"only {len(data)} windows") continue n_train = max(int(len(data) * TRAIN_RATIO), 20) train_data = data[:n_train] test_data = data[n_train:] model_cfg = ModelConfig( window_size=ws, n_steps=20, total_time=0.5, shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003, ) # Try loading cached model (same dataset + params = same result) mdl = load_cached_model(model_cfg, ticker, ws, SHIFT, TRAIN_RATIO) if mdl is not None: print(f"(cached) ", end="") else: torch.manual_seed(42) np.random.seed(42) mdl = model_mod.create_model(model_cfg) windows_arr = np.array([d["norm_input"] for d in train_data]) targets_arr = np.array([d["norm_target"] for d in train_data]) model_mod.train(mdl, windows_arr, targets_arr, 200, 0.003) save_cached_model(mdl, ticker, ws, SHIFT, TRAIN_RATIO) asset_data[ticker] = { "prices": prices, "dates": dates, "tf": tf, "model": mdl, "test_data": test_data, "ws": ws, "leverage": leverage, "weight": weight, "K": asset_k, } cvr = COLLATERAL_VALUE_RATIO.get(ticker, 0.80) im_rate = SPOT_IM_RATE.get(ticker, 0.15) print(f"{len(prices)} bars, {len(test_data)} test | CVR={cvr} IM={im_rate*100:.0f}%") if not asset_data: print("No data!") return # ══════════════════════════════════════════════════ # BUILD CHRONOLOGICAL EVENT TIMELINE # ══════════════════════════════════════════════════ events = [] for ticker, ad in asset_data.items(): for d in ad["test_data"]: price_idx = d["price_idx"] date = str(ad["dates"][price_idx]) events.append((date, ticker, d)) events.sort(key=lambda x: x[0]) print(f"\n Total events: {len(events)} across {len(asset_data)} assets") print(f" Date range: {events[0][0]} → {events[-1][0]}") # ══════════════════════════════════════════════════ # SIMULATE WITH BYBIT UTA MARGIN MODEL # ══════════════════════════════════════════════════ print(f"\n{'='*80}") print("SIMULATION (Bybit UTA model)") print(f"{'='*80}\n") free_usdc = TOTAL_CAPITAL open_positions: dict[str, Position] = {} all_trades = [] per_asset_trades: dict[str, list] = {t: [] for t in asset_data} last_stop_date: dict[str, str] = {} skipped_no_margin = 0 skipped_cooldown = 0 skipped_correlation = 0 skipped_spot_short = 0 skipped_imr_limit = 0 peak_equity = TOTAL_CAPITAL max_drawdown = 0.0 total_interest_paid = 0.0 tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24} for date, ticker, window in events: ad = asset_data[ticker] prices = ad["prices"] price_idx = window["price_idx"] current_price = float(prices[price_idx]) ws = ad["ws"] leverage = ad["leverage"] weight = ad["weight"] asset_k = ad["K"] # --- Check open position --- if ticker in open_positions: pos = open_positions[ticker] bar_hours = tf_hours.get(ad["tf"], 4) check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1) for bar_idx in range(check_from, price_idx + 1): if bar_idx >= len(prices): break bar_price = float(prices[bar_idx]) if TRAILING_STOP: pos.best_price, pos.stop_price = risk.update_trailing_stop( bar_price, pos.best_price, pos.stop_price, pos.stop_dist, pos.direction) stopped = risk.is_stopped(bar_price, pos.stop_price, pos.direction) bars_held = bar_idx - pos.entry_bar time_exit = bars_held >= (SHIFT - pos.k_used) if stopped or time_exit: exit_price = pos.stop_price if stopped else bar_price exit_bar_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction commission_cost = pos.pos_value * COMMISSION * 2 hold_hours = bars_held * bar_hours trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24 total_interest_paid += trade_interest pnl_net = pnl_gross - commission_cost - trade_interest # Release: margin + haircut + spot_IM all go back free_usdc += pos.margin_locked + pnl_net del open_positions[ticker] trade = { "ticker": ticker, "pnl_net": pnl_net, "pnl_gross": pnl_gross, "commission": commission_cost, "interest": trade_interest, "equity_at_entry": pos.margin_locked, "haircut": pos.haircut_loss, "spot_im": pos.spot_im, "exit_reason": "stop" if stopped else "time", "bars_held": bars_held, "date": exit_bar_date, "entry_price": pos.entry_price, "exit_price": exit_price, "direction": pos.direction, } all_trades.append(trade) per_asset_trades[ticker].append(trade) if stopped: last_stop_date[ticker] = exit_bar_date total_equity = free_usdc + sum( p.margin_locked for p in open_positions.values()) peak_equity = max(peak_equity, total_equity) dd = (peak_equity - total_equity) / peak_equity if peak_equity > 0 else 0 max_drawdown = max(max_drawdown, dd) break # --- Check for new signal --- if ticker not in open_positions and price_idx >= ws + asset_k: # Cooldown after stop if ticker in last_stop_date: from datetime import date as d days_since = (d.fromisoformat(date[:10]) - d.fromisoformat(last_stop_date[ticker][:10])).days bar_h = tf_hours.get(ad["tf"], 4) candles_since = days_since * 24 // bar_h if candles_since < SHIFT: skipped_cooldown += 1 continue # Signal generation w = prices[price_idx - ws - asset_k:price_idx - asset_k].copy() confirm = prices[price_idx - asset_k:price_idx].copy() mu, std = w.mean(), w.std() if std < 1e-10: continue norm_input = (w - mu) / std pred = model_mod.predict(ad["model"], norm_input) pred_new = pred[-SHIFT:] corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, mu, std, asset_k, CORR_THRESH) if not confirmed: continue direction = signals.get_direction(pred_new, asset_k) if direction is None: continue if direction == -1: skipped_spot_short += 1 continue conflict = check_correlation_conflict(open_positions, ticker, direction) if conflict: skipped_correlation += 1 continue # === BYBIT UTA MARGIN MODEL === # 1. Check IMR threshold: block if >= (lev-1)/lev imr = calc_account_imr(free_usdc, open_positions) imr_threshold = (leverage - 1) / leverage # 0.5 for 2x if imr >= imr_threshold: skipped_imr_limit += 1 continue # 2. Calculate position value total_equity = free_usdc + sum( p.margin_locked for p in open_positions.values()) pos_value = total_equity * weight * leverage if pos_value < 5.0: continue # 3. Calculate all capital requirements (Bybit model) req = calc_required_capital(pos_value, leverage, ticker) available = calc_available_balance(free_usdc, open_positions) # 4. Check if available balance covers total frozen amount if available < req["total_frozen"]: # Try reduced position # max pos_value where total_frozen <= available cvr = COLLATERAL_VALUE_RATIO.get(ticker, 0.80) im_rate = SPOT_IM_RATE.get(ticker, 0.15) # total_frozen = pv/lev + (1-cvr)*pv + (pv - pv/lev)*im_rate + pv*buffer # = pv * (1/lev + (1-cvr) + (1 - 1/lev)*im_rate + buffer) freeze_per_dollar = (1/leverage + (1 - cvr) + (1 - 1/leverage) * im_rate + MARKET_ORDER_BUFFER) max_pv = available / freeze_per_dollar if max_pv < 5.0: skipped_no_margin += 1 continue pos_value = max_pv req = calc_required_capital(pos_value, leverage, ticker) pos_size = pos_value / current_price k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, asset_k) atr = risk.compute_atr(prices, price_idx) stop_dist = max(atr * stop_mult, current_price * 0.005) # Lock margin (only margin_needed from free_usdc, haircut+IM tracked separately) free_usdc -= req["margin_needed"] open_positions[ticker] = Position( ticker=ticker, direction=direction, entry_price=current_price, entry_date=date, stop_price=current_price - direction * stop_dist, stop_dist=stop_dist, best_price=current_price, pos_size=pos_size, pos_value=pos_value, margin_locked=req["margin_needed"], borrowed=req["borrowed"], haircut_loss=req["haircut"], spot_im=req["spot_im"], k_used=k_adj, entry_bar=price_idx, ) # Close remaining positions for ticker, pos in list(open_positions.items()): ad = asset_data[ticker] last_price = float(ad["prices"][-1]) pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction commission_cost = pos.pos_value * COMMISSION * 2 last_bar = ad["test_data"][-1]["price_idx"] bars_held = last_bar - pos.entry_bar bar_hours = tf_hours.get(ad["tf"], 4) trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24 pnl_net = pnl_gross - commission_cost - trade_interest free_usdc += pos.margin_locked + pnl_net trade = { "ticker": ticker, "pnl_net": pnl_net, "pnl_gross": pnl_gross, "commission": commission_cost, "interest": trade_interest, "equity_at_entry": pos.margin_locked, "haircut": pos.haircut_loss, "spot_im": pos.spot_im, "exit_reason": "end", "bars_held": bars_held, "date": str(ad["dates"][-1]), "entry_price": pos.entry_price, "exit_price": last_price, "direction": pos.direction, } all_trades.append(trade) per_asset_trades[ticker].append(trade) final_equity = free_usdc # ══════════════════════════════════════════════════ # RESULTS # ══════════════════════════════════════════════════ total_pnl = final_equity - TOTAL_CAPITAL total_ret = total_pnl / TOTAL_CAPITAL * 100 total_commission = sum(t["commission"] for t in all_trades) total_haircut = sum(t.get("haircut", 0) for t in all_trades) total_spot_im_cost = sum(t.get("spot_im", 0) for t in all_trades) if events: from datetime import date as d first = d.fromisoformat(events[0][0][:10]) last = d.fromisoformat(events[-1][0][:10]) years = (last - first).days / 365.25 else: years = 1.0 wins = [t for t in all_trades if t["pnl_net"] > 0] losses = [t for t in all_trades if t["pnl_net"] <= 0] print(f"\n{'='*80}") print("RESULTS: BYBIT UTA MARGIN MODEL") print(f"{'='*80}") print(f"\n Capital: ${TOTAL_CAPITAL:.0f} → ${final_equity:.2f} " f"(PnL: ${total_pnl:+.2f}, {total_ret:+.1f}%)") print(f" Max Drawdown: {max_drawdown*100:.1f}%") print(f" Trades: {len(all_trades)} ({len(wins)} wins, {len(losses)} losses)") if all_trades: wr = len(wins) / len(all_trades) * 100 print(f" Win Rate: {wr:.1f}%") print(f"\n Costs breakdown:") print(f" Commission: ${total_commission:.2f}") print(f" Interest: ${total_interest_paid:.2f}") print(f" Haircut: ${total_haircut:.2f} (collateral value loss)") print(f" Spot IM: ${total_spot_im_cost:.2f} (frozen on borrows)") print() print(f" Skipped (no margin): {skipped_no_margin}") print(f" Skipped (IMR limit): {skipped_imr_limit}") print(f" Skipped (cooldown): {skipped_cooldown}") print(f" Skipped (correlation): {skipped_correlation}") print(f" Skipped (spot short): {skipped_spot_short}") if len(all_trades) > 1 and years > 0: returns = np.array([t["pnl_net"] / t["equity_at_entry"] for t in all_trades if t["equity_at_entry"] > 0]) tpy = len(all_trades) / years sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0 months = years * 12 monthly_pnl = total_pnl / months if months > 0 else 0 print(f"\n Sharpe: {sharpe:.2f}") print(f" Monthly PnL: ${monthly_pnl:.2f}") print(f" Period: {years:.1f} years") # Per-asset breakdown print(f"\n {'Asset':<10s} {'TF':>3s} {'K':>2s} {'CVR':>5s} {'IM%':>4s} " f"{'Trds':>5s} {'Wins':>5s} {'WR%':>5s} {'PnL':>10s}") print(f" {'-'*55}") for a in ASSETS: ticker = a["ticker"] trades = per_asset_trades.get(ticker, []) cvr = COLLATERAL_VALUE_RATIO.get(ticker, 0.80) im_rate = SPOT_IM_RATE.get(ticker, 0.15) if not trades: print(f" {ticker:<10s} {a['tf']:>3s} {a.get('K', K):>2d} {cvr:>5.2f} " f"{im_rate*100:>3.0f}% {'':>5s} {'':>5s} {'':>5s} {'no trades':>10s}") continue w = [t for t in trades if t["pnl_net"] > 0] pnl = sum(t["pnl_net"] for t in trades) wr_val = len(w) / len(trades) * 100 print(f" {ticker:<10s} {a['tf']:>3s} {a.get('K', K):>2d} {cvr:>5.2f} " f"{im_rate*100:>3.0f}% {len(trades):>5d} {len(w):>5d} {wr_val:>4.1f}% " f"${pnl:>+9.2f}") # ══════════════════════════════════════════════════ # COMPARISON: exp16 (simple) vs exp19 (Bybit UTA) # ══════════════════════════════════════════════════ print(f"\n{'='*80}") print("IMPACT OF BYBIT UTA MARGIN MODEL") print(f"{'='*80}") print(f"\n {'Factor':<30s} {'exp16 (simple)':>15s} {'exp19 (Bybit)':>15s}") print(f" {'-'*60}") print(f" {'Margin model':<30s} {'pos/lev':>15s} {'pos/lev+CVR+IM':>15s}") print(f" {'Haircut (CVR)':<30s} {'none':>15s} {'per-asset':>15s}") print(f" {'Spot IM on borrows':<30s} {'none':>15s} {'10-20%':>15s}") print(f" {'Market order buffer':<30s} {'none':>15s} {f'{MARKET_ORDER_BUFFER*100:.0f}%':>15s}") print(f" {'IMR threshold check':<30s} {'none':>15s} {'(lev-1)/lev':>15s}") print(f" {'Skipped (no margin)':<30s} {'':>15s} {skipped_no_margin:>15d}") print(f" {'Skipped (IMR limit)':<30s} {'0':>15s} {skipped_imr_limit:>15d}") print(f" {'Final equity':<30s} {'':>15s} ${final_equity:>14.2f}") # Effective capital per trade if all_trades: avg_margin = np.mean([t["equity_at_entry"] for t in all_trades]) avg_haircut = np.mean([t.get("haircut", 0) for t in all_trades]) avg_im = np.mean([t.get("spot_im", 0) for t in all_trades]) print(f"\n Average per trade:") print(f" Margin locked: ${avg_margin:.2f}") print(f" + Haircut: ${avg_haircut:.2f}") print(f" + Spot IM: ${avg_im:.2f}") print(f" = Total frozen: ${avg_margin + avg_haircut + avg_im:.2f} " f"(+{(avg_haircut + avg_im) / avg_margin * 100:.0f}% vs simple model)") # Save save_data = { "config": { "total_capital": TOTAL_CAPITAL, "interest_rate": INTEREST_RATE_DAILY, "commission": COMMISSION, "market_order_buffer": MARKET_ORDER_BUFFER, "cvr": COLLATERAL_VALUE_RATIO, "spot_im_rate": SPOT_IM_RATE, "assets": ASSETS, }, "results": { "final_equity": round(final_equity, 2), "total_pnl": round(total_pnl, 2), "total_ret": round(total_ret, 1), "max_drawdown": round(max_drawdown * 100, 1), "total_trades": len(all_trades), "wins": len(wins), "wr": round(len(wins) / len(all_trades) * 100, 1) if all_trades else 0, "total_commission": round(total_commission, 2), "total_interest": round(total_interest_paid, 2), "total_haircut": round(total_haircut, 2), "skipped_no_margin": skipped_no_margin, "skipped_imr_limit": skipped_imr_limit, "skipped_cooldown": skipped_cooldown, "skipped_correlation": skipped_correlation, "skipped_spot_short": skipped_spot_short, "years": round(years, 2), }, "trades": all_trades, } path = save_results(save_data, results_dir, "exp19_bybit_margin") print(f"\nSaved: {path}") if __name__ == "__main__": main()