feat: stop_scale=0.5, отключение time_exit, safety stop на бирже

- config: stop_scale (множитель стоп-дистанции), time_exit (вкл/выкл),
  safety_stop_pct (защитный стоп на бирже от flash crash)
- executor: применение stop_scale, условный time_exit, размещение и
  отмена safety stop при открытии/закрытии live позиции
- spot: place_safety_stop() и cancel_order() для Bybit
- state: миграция safety_stop_order_id в positions

Бэктест exp16e: stop_scale=0.5 + no time_exit → Sharpe 4.15 (vs 2.45),
DD 5.0% (vs 8.4%), +$13.20/мес (vs $4.15) — все 7 активов прибыльные.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-10 02:15:55 +10:00
co-authored by Claude Opus 4.6
parent 59496ac316
commit acdcdba9d0
5 changed files with 87 additions and 8 deletions
+4 -1
View File
@@ -12,6 +12,9 @@ risk:
max_position_pct: 0.40 # max 40% of equity (min $5 Bybit limit)
max_open_positions: 7 # 7 assets, one position per asset
leverage: 2 # 2x spot margin (exp12: DD ~14%, Sharpe stable)
stop_scale: 0.5 # exp16e: tighter stop = faster exit + cooldown (Sharpe 4.15)
time_exit: false # exp16e: no forced close, hold until stop (Sharpe +70%)
safety_stop_pct: 0.10 # 10% hard stop on exchange (flash crash protection)
assets:
- ticker: ETH-USD
@@ -82,7 +85,7 @@ exchange:
web:
host: 0.0.0.0
port: 8080
port: 8090
telegram:
enabled: false
+3
View File
@@ -42,6 +42,9 @@ class RiskConfig:
max_position_pct: float = 0.50
max_open_positions: int = 2
leverage: int = 1 # 1 = no leverage, 2-10 = spot margin
stop_scale: float = 1.0 # multiplier on ATR stop distance (0.5 = tighter)
time_exit: bool = True # close after shift-K bars; False = hold until stop
safety_stop_pct: float = 0.10 # exchange hard stop: 10% below entry
@dataclass
+23 -7
View File
@@ -209,10 +209,12 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
# Check stop
stopped = risk.is_stopped(last_price, stop_price, direction)
# Check time exit (use per-asset model config)
asset_model_cfg = cfg.model_for(asset_cfg)
max_hold = asset_model_cfg.shift - pos["k_used"]
time_exit = days_held >= max_hold
# Check time exit (use per-asset model config) — can be disabled via config
time_exit = False
if cfg.risk.time_exit:
asset_model_cfg = cfg.model_for(asset_cfg)
max_hold = asset_model_cfg.shift - pos["k_used"]
time_exit = days_held >= max_hold
if stopped or time_exit:
exit_price = stop_price if stopped else last_price
@@ -250,9 +252,13 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
msg = (f"CLOSED {dir_str} ${entry_price:,.2f}→${exit_price:,.2f} "
f"({exit_reason}) PnL ${pnl_net:+,.2f} [{win_str}]")
# Live execution: sell on exchange
# Live execution: cancel safety stop + sell on exchange
if cfg.mode == "live" and direction == 1:
spot = _get_spot(cfg)
# Cancel safety stop order if exists
safety_id = pos.get("safety_stop_order_id")
if safety_id and safety_id != "dry_run":
spot.cancel_order(asset_cfg.symbol, safety_id)
order = spot.sell(asset_cfg.symbol)
if order:
fee = order.get("fee") or {}
@@ -351,9 +357,9 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
entry_price = sw["last_price"]
# Stop with regime-adaptive multiplier
# Stop with regime-adaptive multiplier × stop_scale
atr = risk.compute_atr(prices, len(prices) - 1)
stop_dist = max(atr * stop_mult, entry_price * 0.005)
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)
@@ -420,6 +426,16 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
else:
fee_str = ""
msg += f" [LIVE BUY OK{fee_str}]"
# 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_order = spot.place_safety_stop(
asset_cfg.symbol, pos_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)
msg += f" [SAFETY STOP ${safety_price:,.2f}]"
else:
# Rollback paper position — no phantom positions
close_position(conn, pos_id,
+53
View File
@@ -160,6 +160,59 @@ class SpotExecutor:
log.error(f"BUY {symbol} FAILED: {e}")
return None
def place_safety_stop(self, symbol: str, amount: float,
stop_price: float) -> dict | None:
"""Place a stop-loss limit order as safety net against flash crashes.
This is a hard stop on the exchange that triggers independently of
the bot's trailing stop logic. Only fires if price drops below
safety_stop_pct (e.g., 10%) from entry.
Returns order dict or None on failure.
"""
self._ensure_markets()
coin = symbol.split("/")[0]
amount = float(self.exchange.amount_to_precision(symbol, amount))
stop_price = float(self.exchange.price_to_precision(symbol, stop_price))
ts = datetime.now(timezone.utc).isoformat()
if self.dry_run:
log.info(f"[DRY RUN] SAFETY STOP {amount} {coin} @ ${stop_price:,.2f} at {ts}")
return {"dry_run": True, "side": "sell", "type": "stop",
"symbol": symbol, "amount": amount, "stopPrice": stop_price}
try:
# Bybit spot stop-loss: trigger at stop_price, sell at market
order = self.exchange.create_order(
symbol, "market", "sell", amount,
params={
"triggerPrice": str(stop_price),
"triggerDirection": 2, # 2 = triggered when price falls below
"orderFilter": "StopOrder",
},
)
log.info(f"SAFETY STOP placed: {amount} {coin} trigger=${stop_price:,.2f} "
f"order={order.get('id')}")
return order
except Exception as e:
log.error(f"SAFETY STOP {symbol} FAILED: {e}")
return None
def cancel_order(self, symbol: str, order_id: str) -> bool:
"""Cancel an open order (e.g., safety stop on position close)."""
if self.dry_run:
log.info(f"[DRY RUN] CANCEL order {order_id} on {symbol}")
return True
try:
self.exchange.cancel_order(order_id, symbol, params={
"orderFilter": "StopOrder",
})
log.info(f"CANCEL OK: order {order_id} on {symbol}")
return True
except Exception as e:
log.error(f"CANCEL order {order_id} FAILED: {e}")
return False
def sell(self, symbol: str, amount: float | None = None) -> dict | None:
"""Market sell. If amount is None, sell entire balance.
+4
View File
@@ -106,6 +106,10 @@ def init_db(conn: sqlite3.Connection) -> None:
conn.execute("ALTER TABLE assets ADD COLUMN last_atr_regime TEXT")
if "last_stop_date" not in cols:
conn.execute("ALTER TABLE assets ADD COLUMN last_stop_date TEXT")
# Position migrations
pos_cols = {r[1] for r in conn.execute("PRAGMA table_info(positions)").fetchall()}
if "safety_stop_order_id" not in pos_cols:
conn.execute("ALTER TABLE positions ADD COLUMN safety_stop_order_id TEXT")
conn.commit()