feat: мультисимвольный daemon — per-symbol params, выбор лучшего сигнала
- 3 монеты (BTC/ETH/SOL) с индивидуальными параметрами из OOS бэктеста - При одновременных сигналах — одна позиция, выбор по risk_pct (ширина breakout) - dotenv для загрузки API ключей из .env - capital: 0 = авто-баланс с биржи - DB schema: symbol в positions и sessions Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+143
-73
@@ -1,11 +1,11 @@
|
||||
"""Trade executor — replay approach for ORB+FVG+Engulfing strategy.
|
||||
|
||||
Every 5 minutes during NYSE session:
|
||||
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 with DB positions
|
||||
4. New trades → open on exchange + SL/TP orders
|
||||
5. EOD → close remaining positions
|
||||
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
|
||||
@@ -18,7 +18,7 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from config import Config
|
||||
from config import Config, StrategyConfig
|
||||
from exchange import FuturesExecutor
|
||||
from notify import notify_entry, notify_exit, notify_or
|
||||
from state import (
|
||||
@@ -44,15 +44,22 @@ def _get_futures(cfg: Config) -> FuturesExecutor:
|
||||
|
||||
@dataclass
|
||||
class SessionState:
|
||||
"""In-memory state for current trading session."""
|
||||
date: date | None = None
|
||||
"""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)
|
||||
|
||||
|
||||
_session = SessionState()
|
||||
# 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:
|
||||
@@ -73,9 +80,14 @@ def _trade_key(t: Trade) -> str:
|
||||
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. Returns list of log messages."""
|
||||
global _session
|
||||
"""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)
|
||||
@@ -86,34 +98,108 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
logs.append(f"Outside NYSE hours ({now_ny.strftime('%H:%M')} NY)")
|
||||
return logs
|
||||
|
||||
# Init equity from config on first run
|
||||
# Init equity from config or exchange balance 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
|
||||
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 session
|
||||
if _session.date != today:
|
||||
_session = SessionState(date=today)
|
||||
# Try restore OR from DB
|
||||
saved = get_session(conn, today)
|
||||
# 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
|
||||
_execute_entry(conn, cfg, best_trade, best_symbol,
|
||||
get_equity(conn), logs)
|
||||
sess.last_trade_ids.add(key)
|
||||
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
|
||||
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 OR from DB on first cycle
|
||||
if not sess.or_computed:
|
||||
saved = get_session(conn, today, symbol)
|
||||
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}")
|
||||
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}")
|
||||
|
||||
# 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)
|
||||
raw_candles = futures.fetch_candles(symbol, cfg.timeframe, since_ms)
|
||||
|
||||
if not raw_candles:
|
||||
logs.append("No candles fetched")
|
||||
return logs
|
||||
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)
|
||||
@@ -124,40 +210,39 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
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)
|
||||
# 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, cfg.strategy.or_minutes // tf_minutes)
|
||||
if not _session.or_computed and len(df) >= or_candles_needed:
|
||||
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, cfg.strategy.or_minutes)
|
||||
rng = get_opening_range(df, strat_cfg.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)
|
||||
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
|
||||
db_positions = get_open_positions(conn)
|
||||
# Get DB open positions for this symbol
|
||||
db_positions = get_open_positions(conn, symbol)
|
||||
|
||||
# Reconcile: check if DB positions are still valid
|
||||
# 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(cfg.symbol)
|
||||
ex_pos = futures.get_position(symbol)
|
||||
if ex_pos is None:
|
||||
# Exchange has no position — SL/TP fired
|
||||
price = futures.get_price(cfg.symbol) or pos["entry_price"]
|
||||
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, price, "sl_tp_exchange", logs)
|
||||
_execute_exit(conn, cfg, pos, symbol, price, "sl_tp_exchange", logs)
|
||||
continue
|
||||
|
||||
# Second: check if strategy replay says trade is closed
|
||||
@@ -168,47 +253,29 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
break
|
||||
|
||||
if matched_trade:
|
||||
_execute_exit(conn, cfg, pos, matched_trade.exit_price,
|
||||
_execute_exit(conn, cfg, pos, symbol, matched_trade.exit_price,
|
||||
matched_trade.result, logs)
|
||||
elif _is_eod(now_ny):
|
||||
price = futures.get_price(cfg.symbol) or pos["entry_price"]
|
||||
_execute_exit(conn, cfg, pos, price, "eod", logs)
|
||||
price = futures.get_price(symbol) or pos["entry_price"]
|
||||
_execute_exit(conn, cfg, pos, symbol, price, "eod", logs)
|
||||
|
||||
# Reconcile: new trades from strategy not yet in DB
|
||||
# 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 _session.last_trade_ids:
|
||||
if key in db_keys or key in sess.last_trade_ids:
|
||||
continue
|
||||
candidates.append((symbol, t))
|
||||
|
||||
if t.exit_price > 0:
|
||||
# "Flash trade": entered and exited within this cycle's candle window.
|
||||
# Execute both entry and exit on exchange.
|
||||
_execute_entry(conn, cfg, t, get_equity(conn), logs)
|
||||
_session.last_trade_ids.add(key)
|
||||
# Now close the just-opened position
|
||||
new_positions = get_open_positions(conn)
|
||||
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, t.exit_price, t.result, logs)
|
||||
break
|
||||
continue
|
||||
|
||||
# New active trade → execute entry (re-read equity for fresh value)
|
||||
_execute_entry(conn, cfg, t, get_equity(conn), logs)
|
||||
_session.last_trade_ids.add(key)
|
||||
|
||||
return logs
|
||||
return logs, candidates
|
||||
|
||||
|
||||
def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
equity: float, logs: list[str]) -> None:
|
||||
symbol: str, 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
|
||||
@@ -250,6 +317,7 @@ def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
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,
|
||||
@@ -262,7 +330,8 @@ def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
)
|
||||
log_order(conn, pos_id, side, symbol, trade.entry, order)
|
||||
|
||||
logs.append(f"ENTRY {trade.direction.upper()} @ ${filled_price:,.2f} "
|
||||
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})")
|
||||
|
||||
@@ -271,10 +340,10 @@ def _execute_entry(conn: sqlite3.Connection, cfg: Config, trade: Trade,
|
||||
|
||||
|
||||
def _execute_exit(conn: sqlite3.Connection, cfg: Config, pos: dict,
|
||||
exit_price: float, reason: str, logs: list[str]) -> None:
|
||||
symbol: str, 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"
|
||||
|
||||
# If SL/TP already fired on exchange, skip close + cancel
|
||||
@@ -324,8 +393,9 @@ def _execute_exit(conn: sqlite3.Connection, cfg: Config, pos: dict,
|
||||
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()} @ ${exit_price:,.2f} "
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user