config.yaml + config.py: конфигурация с YAML + env var overrides state.py: SQLite state (equity, sessions, positions, orders) exchange.py: Bybit linear futures executor (dry-run + live) executor.py: торговый цикл — fetch candles → run_day() → reconcile cli.py: Click CLI (run, status, history, daemon с APScheduler 5m) notify.py: Telegram alerts (entry, exit, OR) Существующие backtest-скрипты не затронуты. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
309 lines
10 KiB
Python
309 lines
10 KiB
Python
"""Trade executor — replay approach for ORB+FVG+Engulfing strategy.
|
|
|
|
Every 5 minutes during NYSE session:
|
|
1. Fetch all 5m candles from 9:30 to now
|
|
2. Call run_day() — same function as backtest
|
|
3. Reconcile with DB positions
|
|
4. New trades → open on exchange + SL/TP orders
|
|
5. EOD → close remaining positions
|
|
"""
|
|
|
|
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
|
|
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_today_trade_count, log_order, open_position, save_session,
|
|
set_state_val, update_equity,
|
|
)
|
|
from strategy import Params, 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."""
|
|
date: date | None = None
|
|
or_high: float = 0.0
|
|
or_low: float = 0.0
|
|
or_computed: bool = False
|
|
last_trade_ids: set[str] = field(default_factory=set)
|
|
|
|
|
|
_session = SessionState()
|
|
|
|
|
|
def _is_nyse_hours(now_ny: datetime) -> bool:
|
|
"""Check if within NYSE trading window (9:25-16:05 NY, weekdays)."""
|
|
if now_ny.weekday() >= 5: # Sat, Sun
|
|
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 run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
|
"""Run one trading cycle. Returns list of log messages."""
|
|
global _session
|
|
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 on first run
|
|
equity = get_equity(conn)
|
|
if equity <= 0:
|
|
update_equity(conn, cfg.capital)
|
|
set_state_val(conn, "peak_equity", cfg.capital)
|
|
equity = cfg.capital
|
|
logs.append(f"Equity initialized: ${equity:,.2f}")
|
|
|
|
# New day → reset session
|
|
if _session.date != today:
|
|
_session = SessionState(date=today)
|
|
# Try restore OR from DB
|
|
saved = get_session(conn, today)
|
|
if saved:
|
|
_session.or_high = saved["or_high"]
|
|
_session.or_low = saved["or_low"]
|
|
_session.or_computed = True
|
|
logs.append(f"Session restored: OR {_session.or_high:.2f}/{_session.or_low:.2f}")
|
|
|
|
# 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(cfg.symbol, cfg.timeframe, since_ms)
|
|
|
|
if not raw_candles:
|
|
logs.append("No candles fetched")
|
|
return logs
|
|
|
|
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)
|
|
params = cfg.strategy.to_params()
|
|
strategy_trades = run_day(df, params, cfg.strategy.or_minutes)
|
|
|
|
# Track OR computation
|
|
if not _session.or_computed and len(df) >= cfg.strategy.or_minutes:
|
|
from strategy import get_opening_range
|
|
rng = get_opening_range(df, cfg.strategy.or_minutes)
|
|
if rng:
|
|
_session.or_high, _session.or_low = rng
|
|
_session.or_computed = True
|
|
save_session(conn, today, _session.or_high, _session.or_low)
|
|
logs.append(f"OR computed: {_session.or_high:.2f}/{_session.or_low:.2f}")
|
|
notify_or(cfg.telegram, str(today), _session.or_high, _session.or_low)
|
|
|
|
# Build set of strategy trade keys
|
|
strat_keys = {_trade_key(t) for t in strategy_trades}
|
|
logs.append(f"Strategy signals: {len(strategy_trades)} trades")
|
|
|
|
# Get DB open positions
|
|
db_positions = get_open_positions(conn)
|
|
|
|
# Reconcile: check if DB positions are still valid
|
|
for pos in db_positions:
|
|
key = f"{pos['direction']}_{pos['entry_price']:.2f}_{pos['stop_price']:.2f}"
|
|
|
|
# Find matching strategy trade
|
|
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:
|
|
# Strategy says this trade is closed
|
|
_execute_exit(conn, cfg, pos, matched_trade.exit_price,
|
|
matched_trade.result, logs)
|
|
elif _is_eod(now_ny):
|
|
# EOD: close all remaining
|
|
price = futures.get_price(cfg.symbol) or pos["entry_price"]
|
|
_execute_exit(conn, cfg, pos, price, "eod", logs)
|
|
|
|
# Reconcile: new trades from strategy not yet in DB
|
|
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 _session.last_trade_ids:
|
|
continue
|
|
if t.exit_price > 0:
|
|
# Already closed in strategy — skip (historical trade)
|
|
continue
|
|
|
|
# New active trade → execute entry
|
|
_execute_entry(conn, cfg, t, equity, logs)
|
|
_session.last_trade_ids.add(key)
|
|
|
|
return logs
|
|
|
|
|
|
def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
|
equity: float, logs: list[str]) -> None:
|
|
"""Open a new position on exchange and in DB."""
|
|
futures = _get_futures(cfg)
|
|
symbol = cfg.symbol
|
|
|
|
# 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()),
|
|
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)
|
|
|
|
logs.append(f"ENTRY {trade.direction.upper()} @ ${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,
|
|
exit_price: float, reason: str, logs: list[str]) -> None:
|
|
"""Close a position on exchange and in DB."""
|
|
futures = _get_futures(cfg)
|
|
symbol = cfg.symbol
|
|
side = "buy" if pos["direction"] == "long" else "sell"
|
|
|
|
# Cancel SL/TP orders
|
|
futures.cancel_orders(symbol,
|
|
pos.get("sl_order_id", ""),
|
|
pos.get("tp_order_id", ""))
|
|
|
|
# Close on exchange
|
|
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)
|
|
|
|
commission = pos["pos_value"] * cfg.risk.taker_fee * 2
|
|
pnl_net = gross - commission
|
|
|
|
# Update equity
|
|
equity = get_equity(conn)
|
|
new_equity = equity + pnl_net
|
|
update_equity(conn, new_equity)
|
|
|
|
# Update stats
|
|
from state import get_state_val, set_state_val
|
|
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)
|
|
|
|
result = "WIN" if pnl_net > 0 else "LOSS"
|
|
logs.append(f"EXIT {pos['direction'].upper()} @ ${exit_price:,.2f} "
|
|
f"({reason}) PnL ${pnl_net:+,.2f} [{result}]")
|
|
|
|
notify_exit(cfg.telegram, symbol, pnl_net, reason)
|