diff --git a/backtest_wf.py b/backtest_wf.py index bf8fc60..915c934 100644 --- a/backtest_wf.py +++ b/backtest_wf.py @@ -23,7 +23,7 @@ NY = ZoneInfo("America/New_York") # ── Config ─────────────────────────────────────────────────────────── INITIAL_CAPITAL = 1_000.0 -RISK_PCT = 0.02 # 2% risk per trade +RISK_PCT = 0.05 # 5% risk per trade TAKER_FEE = 0.00055 # Bybit linear futures taker fee (0.055%) LEVERAGE = 10 # max leverage (caps position value) TRAIN_RATIO = 0.5 # first 50% days = in-sample @@ -32,7 +32,7 @@ OR_MINUTES = 15 # opening range duration (3 x 5m candles) GRID = { "rr_ratio": [2.0, 2.5, 3.0], - "max_trades": [1, 2, 3], + "max_trades": [99], "min_range_pct": [0.0, 0.1, 0.2], "min_fvg_pct": [0.0, 0.02, 0.05], "first_fvg_only": [False, True], diff --git a/cli.py b/cli.py index 0b841fc..a8e7af7 100644 --- a/cli.py +++ b/cli.py @@ -98,13 +98,14 @@ def history(limit): return click.echo() - click.echo(f" {'Date':<12s} {'Dir':>6s} {'Entry':>10s} {'Exit':>10s} " + click.echo(f" {'Date':<12s} {'Sym':>4s} {'Dir':>6s} {'Entry':>10s} {'Exit':>10s} " f"{'PnL':>10s} {'Reason':>6s}") - click.echo(f" {'─' * 58}") + click.echo(f" {'─' * 62}") for t in reversed(trades): pnl = t["pnl_net"] or 0 - click.echo(f" {t['date']:<12s} {t['direction'].upper():>6s} " + tag = (t.get("symbol") or "").split("/")[0] or "?" + click.echo(f" {t['date']:<12s} {tag:>4s} {t['direction'].upper():>6s} " f"${t['entry_price']:>9,.2f} ${(t['exit_price'] or 0):>9,.2f} " f"${pnl:>+9,.2f} {(t['exit_reason'] or ''):>6s}") @@ -122,8 +123,10 @@ def daemon(): symbols = ", ".join(s.split("/")[0] for s in cfg.symbols.keys()) click.echo(f"scalp-bot daemon starting ({cfg.mode} mode, {symbols})") - click.echo(f"Strategy: RR={cfg.strategy.rr_ratio} OR={cfg.strategy.or_minutes}m " - f"max_trades={cfg.strategy.max_trades}") + for sym, sc in cfg.symbols.items(): + tag = sym.split("/")[0] + click.echo(f" {tag}: RR={sc.rr_ratio} OR={sc.or_minutes}m max={sc.max_trades} " + f"fvg_exp={sc.fvg_expiry} fvg_only={sc.first_fvg_only}") click.echo(f"Risk: {cfg.risk.per_trade*100:.0f}% per trade, {cfg.risk.leverage}x leverage") def scheduled_cycle(): diff --git a/config.yaml b/config.yaml index cc6e0e0..97ec8c9 100644 --- a/config.yaml +++ b/config.yaml @@ -6,14 +6,14 @@ timeframe: "5m" symbols: BTC/USDT:USDT: rr_ratio: 3.0 - max_trades: 1 + max_trades: 99 fvg_expiry: 6 or_minutes: 15 session_end_h: 11 ETH/USDT:USDT: rr_ratio: 3.0 - max_trades: 1 + max_trades: 99 fvg_expiry: 6 or_minutes: 15 session_end_h: 11 @@ -21,7 +21,7 @@ symbols: SOL/USDT:USDT: rr_ratio: 3.0 - max_trades: 1 + max_trades: 99 fvg_expiry: 12 or_minutes: 15 session_end_h: 11 @@ -30,7 +30,7 @@ symbols: first_fvg_only: true risk: - per_trade: 0.02 + per_trade: 0.05 leverage: 10 taker_fee: 0.00055 diff --git a/exchange.py b/exchange.py index 2c54e92..885105b 100644 --- a/exchange.py +++ b/exchange.py @@ -31,7 +31,7 @@ class FuturesExecutor: self.dry_run = not exchange_cfg.api_key self.leverage = leverage self._markets_loaded = False - self._leverage_set = False + self._leverage_set: set[str] = set() if self.dry_run: log.info("FuturesExecutor: DRY RUN mode (no API key)") @@ -45,7 +45,7 @@ class FuturesExecutor: def setup(self, symbol: str) -> None: """Set leverage and position mode (call once per symbol).""" - if self._leverage_set or self.dry_run: + if symbol in self._leverage_set or self.dry_run: return self._ensure_markets() try: @@ -53,7 +53,7 @@ class FuturesExecutor: log.info(f"Leverage set to {self.leverage}x for {symbol}") except Exception as e: log.warning(f"Set leverage failed (may already be set): {e}") - self._leverage_set = True + self._leverage_set.add(symbol) def get_balance(self) -> float: """Get free USDT balance.""" diff --git a/executor.py b/executor.py index 71836a7..6b7b6b6 100644 --- a/executor.py +++ b/executor.py @@ -23,8 +23,8 @@ from exchange import FuturesExecutor from notify import notify_entry, notify_exit, notify_or from state import ( close_position, get_equity, get_open_positions, get_session, - get_state_val, log_order, open_position, save_session, - set_state_val, update_equity, + get_state_val, get_today_trade_keys, log_order, open_position, + save_session, set_state_val, update_equity, ) from strategy import Trade, run_day @@ -150,17 +150,15 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]: key = _trade_key(best_trade) if best_trade.exit_price > 0: - # Flash trade + # Flash trade — entry + exit in same cycle _execute_entry(conn, cfg, best_trade, best_symbol, get_equity(conn), logs) sess.last_trade_ids.add(key) + # Find the just-opened position (last open for this symbol) new_positions = get_open_positions(conn, best_symbol) - for pos in new_positions: - pos_key = f"{pos['direction']}_{pos['entry_price']:.2f}_{pos['stop_price']:.2f}" - if pos_key == key: - _execute_exit(conn, cfg, pos, best_symbol, - best_trade.exit_price, best_trade.result, logs) - break + if new_positions: + _execute_exit(conn, cfg, new_positions[-1], best_symbol, + best_trade.exit_price, best_trade.result, logs) else: _execute_entry(conn, cfg, best_trade, best_symbol, get_equity(conn), logs) @@ -182,7 +180,7 @@ def _run_symbol_phase1(conn: sqlite3.Connection, cfg: Config, symbol: str, candidates: list[tuple[str, Trade]] = [] sess = _get_session(symbol) - # Try restore OR from DB on first cycle + # Try restore state from DB on first cycle (crash recovery) if not sess.or_computed: saved = get_session(conn, today, symbol) if saved: @@ -190,6 +188,8 @@ def _run_symbol_phase1(conn: sqlite3.Connection, cfg: Config, symbol: str, sess.or_low = saved["or_low"] sess.or_computed = True logs.append(f"Session restored: OR {sess.or_high:.2f}/{sess.or_low:.2f}") + # Restore trade keys to prevent duplicates after restart + sess.last_trade_ids = get_today_trade_keys(conn, today, symbol) # Fetch 5m candles from 9:30 NY to now futures = _get_futures(cfg) diff --git a/state.py b/state.py index 19fdaeb..90f99f1 100644 --- a/state.py +++ b/state.py @@ -179,6 +179,17 @@ def get_today_trade_count(conn: sqlite3.Connection, dt: date) -> int: return row["cnt"] if row else 0 +def get_today_trade_keys(conn: sqlite3.Connection, dt: date, + symbol: str) -> set[str]: + """Get trade keys for today's positions (for crash recovery).""" + rows = conn.execute( + "SELECT direction, entry_price, stop_price FROM positions " + "WHERE date=? AND symbol=?", (str(dt), symbol) + ).fetchall() + return {f"{r['direction']}_{r['entry_price']:.2f}_{r['stop_price']:.2f}" + for r in rows} + + def get_trade_history(conn: sqlite3.Connection, limit: int = 50) -> list[dict]: rows = conn.execute( "SELECT * FROM positions WHERE status='closed' ORDER BY id DESC LIMIT ?", diff --git a/test_live.py b/test_live.py index da7b9c6..44dda3e 100644 --- a/test_live.py +++ b/test_live.py @@ -60,8 +60,10 @@ def test_or_computation(): def test_strategy_signals(day_df, or_high, or_low): """Test that run_day produces trades from cached data.""" - params = Params(rr_ratio=2.5, max_trades=2, fvg_expiry=12, session_end_h=11) - trades = run_day(day_df, params, or_minutes=15) + cfg = load_config() + strat_cfg = list(cfg.symbols.values())[0] # BTC params from config.yaml + params = strat_cfg.to_params() + trades = run_day(day_df, params, or_minutes=strat_cfg.or_minutes) print(f"\nStrategy trades ({len(trades)}):") for t in trades: @@ -78,7 +80,7 @@ def test_strategy_signals(day_df, or_high, or_low): def test_run_cycle_simulation(): """Simulate run_cycle by feeding cached candles as if live.""" - from executor import SessionState, _execute_entry, _execute_exit, _is_nyse_hours, _session + from executor import SessionState, _execute_entry, _execute_exit, _is_nyse_hours cfg = load_config() @@ -97,12 +99,16 @@ def test_run_cycle_simulation(): day_df = df[ny.dt.date == test_date].reset_index(drop=True) # Simulate incremental candle feed (as daemon would do every 5 min) - params = cfg.strategy.to_params() + # Use first symbol's strategy config for test + test_symbol = list(cfg.symbols.keys())[0] + strat_cfg = cfg.symbols[test_symbol] + params = strat_cfg.to_params() from state import save_session, update_equity, set_state_val - # Init equity - update_equity(conn, cfg.capital) - set_state_val(conn, "peak_equity", cfg.capital) + # Init equity (capital=0 means auto-fetch, use 1000 for test) + capital = cfg.capital if cfg.capital > 0 else 1000.0 + update_equity(conn, capital) + set_state_val(conn, "peak_equity", capital) ny_times = day_df["timestamp"].dt.tz_convert(NY) # Filter from 9:30 to 16:00 — matches real executor (fetches from 9:30) @@ -133,17 +139,17 @@ def test_run_cycle_simulation(): cycle_count += 1 # Run strategy on partial data - trades = run_day(partial, params, cfg.strategy.or_minutes) + trades = run_day(partial, params, strat_cfg.or_minutes) # Check OR tf_minutes = 5 - or_candles_needed = max(1, cfg.strategy.or_minutes // tf_minutes) + or_candles_needed = max(1, strat_cfg.or_minutes // tf_minutes) if not or_computed and i >= or_candles_needed: - rng = get_opening_range(partial, cfg.strategy.or_minutes) + rng = get_opening_range(partial, strat_cfg.or_minutes) if rng: or_h, or_l = rng or_computed = True - save_session(conn, test_date, or_h, or_l) + save_session(conn, test_date, or_h, or_l, test_symbol) print(f" [{now_ny.strftime('%H:%M')}] OR computed: " f"high={or_h:.2f} low={or_l:.2f}") @@ -192,7 +198,7 @@ def test_run_cycle_simulation(): opened_keys.discard(key) # Verify session was saved - saved = get_session(conn, test_date) + saved = get_session(conn, test_date, test_symbol) assert saved is not None, "Session should be saved" print(f"\nDB session: OR {saved['or_high']:.2f}/{saved['or_low']:.2f}") print(f"Cycles simulated: {cycle_count}")