From acdcdba9d02f0a356035b45c751d1e8a8a73b3c3 Mon Sep 17 00:00:00 2001 From: anor Date: Tue, 10 Mar 2026 02:15:55 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20stop=5Fscale=3D0.5,=20=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20time=5Fexit,?= =?UTF-8?q?=20safety=20stop=20=D0=BD=D0=B0=20=D0=B1=D0=B8=D1=80=D0=B6?= =?UTF-8?q?=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- config.yaml | 5 ++- src/remizov_trader/config.py | 3 ++ src/remizov_trader/core/executor.py | 30 ++++++++++++---- src/remizov_trader/core/spot.py | 53 +++++++++++++++++++++++++++++ src/remizov_trader/state.py | 4 +++ 5 files changed, 87 insertions(+), 8 deletions(-) diff --git a/config.yaml b/config.yaml index 5b0e4b9..c7abd2b 100644 --- a/config.yaml +++ b/config.yaml @@ -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 diff --git a/src/remizov_trader/config.py b/src/remizov_trader/config.py index 48cc353..790e567 100644 --- a/src/remizov_trader/config.py +++ b/src/remizov_trader/config.py @@ -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 diff --git a/src/remizov_trader/core/executor.py b/src/remizov_trader/core/executor.py index 807fc0f..395a485 100644 --- a/src/remizov_trader/core/executor.py +++ b/src/remizov_trader/core/executor.py @@ -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, diff --git a/src/remizov_trader/core/spot.py b/src/remizov_trader/core/spot.py index cd34c3f..4999a47 100644 --- a/src/remizov_trader/core/spot.py +++ b/src/remizov_trader/core/spot.py @@ -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. diff --git a/src/remizov_trader/state.py b/src/remizov_trader/state.py index 45423f3..b26d7e5 100644 --- a/src/remizov_trader/state.py +++ b/src/remizov_trader/state.py @@ -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()