"""Trade executor — replay approach for ORB+FVG+Engulfing strategy. Every 5 minutes during NYSE session, for each symbol: 1. Fetch all 5m candles from 9:30 to now 2. Call run_day() — same function as backtest 3. Reconcile exits with DB positions 4. Collect entry candidates across all symbols 5. Pick best candidate (widest risk %) → open on exchange + SL/TP """ from __future__ import annotations import logging import sqlite3 from dataclasses import dataclass, field from datetime import date, datetime, timezone from zoneinfo import ZoneInfo import pandas as pd from config import Config, StrategyConfig from exchange import FuturesExecutor from holidays import is_nyse_holiday from notify import notify_entry, notify_exit, notify_or from state import ( close_position, get_equity, get_open_positions, get_session, get_state_val, get_today_trade_keys, log_order, open_position, save_session, set_state_val, update_equity, ) from strategy import Trade, run_day log = logging.getLogger(__name__) NY = ZoneInfo("America/New_York") # Singleton executor (created once) _futures: FuturesExecutor | None = None def _get_futures(cfg: Config) -> FuturesExecutor: global _futures if _futures is None: _futures = FuturesExecutor(cfg.exchange, leverage=cfg.risk.leverage) return _futures @dataclass class SessionState: """In-memory state for current trading session (per symbol).""" or_high: float = 0.0 or_low: float = 0.0 or_computed: bool = False last_trade_ids: set[str] = field(default_factory=set) # Per-symbol session state, keyed by symbol string _sessions: dict[str, SessionState] = {} _session_date: date | None = None def _get_session(symbol: str) -> SessionState: if symbol not in _sessions: _sessions[symbol] = SessionState() return _sessions[symbol] def _is_nyse_hours(now_ny: datetime) -> bool: """Check if within NYSE trading window (9:25-16:05 NY, weekdays, not holidays).""" if now_ny.weekday() >= 5: # Sat, Sun return False if is_nyse_holiday(now_ny.date()): return False t = now_ny.hour * 60 + now_ny.minute return 9 * 60 + 25 <= t <= 16 * 60 + 5 def _is_eod(now_ny: datetime) -> bool: """Check if at/past end of day (16:00 NY).""" return now_ny.hour >= 16 def _trade_key(t: Trade) -> str: """Unique key for a strategy trade (for reconciliation).""" return f"{t.direction}_{t.entry:.2f}_{t.stop:.2f}" def _risk_pct(t: Trade) -> float: """Normalized risk distance — proxy for signal strength.""" return abs(t.entry - t.stop) / t.entry if t.entry > 0 else 0 def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]: """Run one trading cycle for all symbols. Returns list of log messages.""" global _sessions, _session_date logs: list[str] = [] now_utc = datetime.now(timezone.utc) now_ny = now_utc.astimezone(NY) today = now_ny.date() # Check NYSE hours if not _is_nyse_hours(now_ny): logs.append(f"Outside NYSE hours ({now_ny.strftime('%H:%M')} NY)") return logs # Init equity from config or exchange balance on first run equity = get_equity(conn) if equity <= 0: capital = cfg.capital if capital <= 0: futures = _get_futures(cfg) capital = futures.get_balance() if capital <= 0: logs.append("Cannot init equity: no config capital and exchange balance is 0") return logs update_equity(conn, capital) set_state_val(conn, "peak_equity", capital) equity = capital logs.append(f"Equity initialized: ${equity:,.2f}") # New day → reset all sessions if _session_date != today: _sessions = {} _session_date = today # Phase 1: for each symbol — exits, OR, collect entry candidates candidates: list[tuple[str, Trade]] = [] # (symbol, trade) for symbol, strat_cfg in cfg.symbols.items(): sym_logs, sym_candidates = _run_symbol_phase1( conn, cfg, symbol, strat_cfg, now_ny, today) if sym_logs: tag = symbol.split("/")[0] logs.append(f"[{tag}]") logs.extend(f" {msg}" for msg in sym_logs) candidates.extend(sym_candidates) # Phase 2: pick best entry candidate (if no open positions) if candidates: all_open = get_open_positions(conn) if not all_open: # Sort by risk_pct descending — widest breakout = strongest signal candidates.sort(key=lambda c: _risk_pct(c[1]), reverse=True) best_symbol, best_trade = candidates[0] tag = best_symbol.split("/")[0] if len(candidates) > 1: others = ", ".join( f"{s.split('/')[0]}({_risk_pct(t)*100:.3f}%)" for s, t in candidates[1:] ) logs.append(f" Candidates: {tag}({_risk_pct(best_trade)*100:.3f}%) > {others}") sess = _get_session(best_symbol) key = _trade_key(best_trade) if best_trade.exit_price > 0: # 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) 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) sess.last_trade_ids.add(key) else: logs.append(f" {len(candidates)} candidate(s) skipped — position already open") return logs def _run_symbol_phase1(conn: sqlite3.Connection, cfg: Config, symbol: str, strat_cfg: StrategyConfig, now_ny: datetime, today: date) -> tuple[list[str], list[tuple[str, Trade]]]: """Phase 1: exits + OR computation + collect new trade candidates. Returns (logs, candidates) where candidates are new trades not yet in DB. """ logs: list[str] = [] candidates: list[tuple[str, Trade]] = [] sess = _get_session(symbol) # Try restore state from DB on first cycle (crash recovery) if not sess.or_computed: saved = get_session(conn, today, symbol) if saved: sess.or_high = saved["or_high"] 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) nyse_open = now_ny.replace(hour=9, minute=30, second=0, microsecond=0) since_ms = int(nyse_open.astimezone(timezone.utc).timestamp() * 1000) raw_candles = futures.fetch_candles(symbol, cfg.timeframe, since_ms) if not raw_candles: logs.append("No candles fetched") return logs, candidates df = pd.DataFrame(raw_candles, columns=["timestamp", "open", "high", "low", "close", "volume"]) df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True) df.drop_duplicates(subset="timestamp", inplace=True) df.sort_values("timestamp", inplace=True) df.reset_index(drop=True, inplace=True) logs.append(f"Candles: {len(df)} ({df.iloc[0]['timestamp'].strftime('%H:%M')}" f"-{df.iloc[-1]['timestamp'].strftime('%H:%M')} UTC)") # Run strategy (replay) with per-symbol params params = strat_cfg.to_params() strategy_trades = run_day(df, params, strat_cfg.or_minutes) # Track OR computation (convert or_minutes to candle count) tf_minutes = {"1m": 1, "5m": 5, "15m": 15}.get(cfg.timeframe, 5) or_candles_needed = max(1, strat_cfg.or_minutes // tf_minutes) if not sess.or_computed and len(df) >= or_candles_needed: from strategy import get_opening_range rng = get_opening_range(df, strat_cfg.or_minutes) if rng: sess.or_high, sess.or_low = rng sess.or_computed = True save_session(conn, today, sess.or_high, sess.or_low, symbol) logs.append(f"OR computed: {sess.or_high:.2f}/{sess.or_low:.2f}") notify_or(cfg.telegram, f"{today} {symbol}", sess.or_high, sess.or_low) logs.append(f"Strategy signals: {len(strategy_trades)} trades") # Get DB open positions for this symbol db_positions = get_open_positions(conn, symbol) # Reconcile exits: check if DB positions are still valid for pos in db_positions: key = f"{pos['direction']}_{pos['entry_price']:.2f}_{pos['stop_price']:.2f}" # First: check if exchange position is gone (SL/TP fired between cycles) if cfg.mode == "live": ex_pos = futures.get_position(symbol) if ex_pos is None: price = futures.get_price(symbol) or pos["entry_price"] logs.append(f"Exchange position gone — SL/TP fired between cycles") _execute_exit(conn, cfg, pos, symbol, price, "sl_tp_exchange", logs) continue # Second: check if strategy replay says trade is closed matched_trade = None for t in strategy_trades: if _trade_key(t) == key and t.exit_price > 0: matched_trade = t break if matched_trade: _execute_exit(conn, cfg, pos, symbol, matched_trade.exit_price, matched_trade.result, logs) elif _is_eod(now_ny): price = futures.get_price(symbol) or pos["entry_price"] _execute_exit(conn, cfg, pos, symbol, price, "eod", logs) # Collect new trade candidates (not yet in DB, not seen before) db_keys = {f"{p['direction']}_{p['entry_price']:.2f}_{p['stop_price']:.2f}" for p in db_positions} for t in strategy_trades: key = _trade_key(t) if key in db_keys or key in sess.last_trade_ids: continue candidates.append((symbol, t)) return logs, candidates def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade, symbol: str, equity: float, logs: list[str]) -> None: """Open a new position on exchange and in DB.""" futures = _get_futures(cfg) # Position sizing risk_dollar = equity * cfg.risk.per_trade risk_dist = abs(trade.entry - trade.stop) if risk_dist <= 0: logs.append(f"SKIP entry: zero risk distance") return pos_size = risk_dollar / risk_dist pos_value = pos_size * trade.entry # Leverage cap max_pos = equity * cfg.risk.leverage if pos_value > max_pos: pos_size = max_pos / trade.entry pos_value = max_pos # Exchange order side = "buy" if trade.direction == "long" else "sell" if trade.direction == "long": order = futures.open_long(symbol, pos_value) else: order = futures.open_short(symbol, pos_value) if order is None: logs.append(f"ENTRY FAILED: {trade.direction} @ {trade.entry:.2f}") return # Actual fill filled_price = float(order.get("average") or order.get("price") or trade.entry) filled_qty = float(order.get("filled") or order.get("amount") or pos_size) # Place SL/TP on exchange sl_order, tp_order = futures.place_sl_tp( symbol, side, filled_qty, trade.stop, trade.tp, ) # DB pos_id = open_position( conn, date=str(datetime.now(timezone.utc).astimezone(NY).date()), symbol=symbol, direction=trade.direction, entry_price=filled_price, stop_price=trade.stop, tp_price=trade.tp, pos_size=filled_qty, pos_value=filled_qty * filled_price, entry_time=datetime.now(timezone.utc).isoformat(), sl_order_id=sl_order.get("id") if sl_order else None, tp_order_id=tp_order.get("id") if tp_order else None, ) log_order(conn, pos_id, side, symbol, trade.entry, order) tag = symbol.split("/")[0] logs.append(f"ENTRY {trade.direction.upper()} {tag} @ ${filled_price:,.2f} " f"SL=${trade.stop:,.2f} TP=${trade.tp:,.2f} " f"size={filled_qty:.4f} (${pos_value:,.2f})") notify_entry(cfg.telegram, symbol, trade.direction, filled_price, trade.stop, trade.tp) def _execute_exit(conn: sqlite3.Connection, cfg: Config, pos: dict, symbol: str, exit_price: float, reason: str, logs: list[str]) -> None: """Close a position on exchange and in DB.""" futures = _get_futures(cfg) side = "buy" if pos["direction"] == "long" else "sell" # If SL/TP already fired on exchange, skip close + cancel already_closed = reason == "sl_tp_exchange" if not already_closed: futures.cancel_orders(symbol, pos.get("sl_order_id", ""), pos.get("tp_order_id", "")) # Close on exchange (skip if already closed by exchange SL/TP) order = None if not already_closed: order = futures.close_position(symbol, side, pos["pos_size"]) # PnL if pos["direction"] == "long": gross = pos["pos_size"] * (exit_price - pos["entry_price"]) else: gross = pos["pos_size"] * (pos["entry_price"] - exit_price) # maker fee on entry, taker fee on exit (SL/TP) commission = pos["pos_value"] * (cfg.risk.maker_fee + cfg.risk.taker_fee) pnl_net = gross - commission # Update equity equity = get_equity(conn) new_equity = equity + pnl_net update_equity(conn, new_equity) # Update stats trades_count = get_state_val(conn, "trades_count") + 1 set_state_val(conn, "trades_count", trades_count) if pnl_net > 0: wins = get_state_val(conn, "wins") + 1 set_state_val(conn, "wins", wins) total_pnl = get_state_val(conn, "total_pnl") + pnl_net set_state_val(conn, "total_pnl", total_pnl) # DB close_position(conn, pos["id"], exit_price=exit_price, exit_reason=reason, pnl_net=round(pnl_net, 4), exit_time=datetime.now(timezone.utc).isoformat()) if order: close_side = "sell" if side == "buy" else "buy" log_order(conn, pos["id"], close_side, symbol, exit_price, order) tag = symbol.split("/")[0] result = "WIN" if pnl_net > 0 else "LOSS" logs.append(f"EXIT {pos['direction'].upper()} {tag} @ ${exit_price:,.2f} " f"({reason}) PnL ${pnl_net:+,.2f} [{result}]") notify_exit(cfg.telegram, symbol, pnl_net, reason)