feat: hourly backtest + ccxt monitor + результаты сравнения

hourly_backtest.py: сравнение daily vs hourly stop мониторинга
  Результат: hourly ХУЖЕ на всех 4 активах (Sharpe -0.5...-1.0)
  Причина: intraday фитили срабатывают стопы на шуме

paper_trader.py: monitor mode через Binance (ccxt)
  --monitor показывает realtime цены и unrealized P&L
  Стопы проверяются только по daily close (доказано бэктестом)

requirements.txt: добавлен ccxt>=4.5

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-08 13:55:14 +10:00
co-authored by Claude Opus 4.6
parent 389a173611
commit 8fcd83d55e
3 changed files with 711 additions and 3 deletions
+242 -3
View File
@@ -1,14 +1,16 @@
"""
Paper trading system for RemizovNet.
Runs daily via cron. Uses best strategy: ATR stop + Trailing stop.
Uses best strategy: ATR stop + Trailing stop.
Maintains persistent state (model, positions, equity) between runs.
Usage:
python paper_trader.py # daily update (for cron)
Modes:
python paper_trader.py # daily update (signals + stops via yfinance)
python paper_trader.py --init # initialize: train models, create state
python paper_trader.py --status # show current positions and equity
python paper_trader.py --history # show trade history
python paper_trader.py --monitor # realtime stop monitor via Binance (ccxt)
python paper_trader.py --monitor --interval 240 # check every 4h (default)
State file: paper_state.json
Trade log: logs/paper_trades.jsonl (append-only)
@@ -26,6 +28,7 @@ import warnings
from datetime import date, datetime, timedelta
from pathlib import Path
import ccxt
import numpy as np
import torch
import torch.nn as nn
@@ -57,6 +60,14 @@ MODEL_DIR = Path(__file__).parent / "paper_models"
LOG_DIR = Path(__file__).parent / "logs"
TRADE_LOG = LOG_DIR / "paper_trades.jsonl"
# Yahoo Finance ticker -> Binance symbol mapping
BINANCE_SYMBOLS = {
"BTC-USD": "BTC/USDT",
"ETH-USD": "ETH/USDT",
"SOL-USD": "SOL/USDT",
"BNB-USD": "BNB/USDT",
}
# Best strategy per asset from A/B testing
ASSET_CONFIGS = {
"BTC-USD": {
@@ -693,6 +704,228 @@ def show_history():
f"({event['windows']} windows)")
# -- Realtime stop monitor via Binance (ccxt) --------------------------------
def _fetch_realtime_price(exchange, asset):
"""Get current price from Binance."""
symbol = BINANCE_SYMBOLS.get(asset)
if not symbol:
return None
try:
ticker = exchange.fetch_ticker(symbol)
return ticker["last"]
except Exception as e:
print(f" {asset}: fetch error ({e})")
return None
def _monitor_check_stops(state, exchange):
"""Check all open positions against realtime prices. Close if stopped."""
closed_any = False
now = datetime.now()
for asset in ASSET_CONFIGS:
asset_state = state["assets"].get(asset)
if asset_state is None:
continue
pos = asset_state.get("open_position")
if pos is None:
continue
price = _fetch_realtime_price(exchange, asset)
if price is None:
continue
direction = pos["direction"]
entry_price = pos["entry_price"]
stop_price = pos["stop_price"]
stop_dist = pos["stop_dist"]
best_price = pos["best_price"]
pos_size = pos["pos_size"]
pos_value = pos["pos_value"]
entry_date = date.fromisoformat(pos["entry_date"])
days_held = (date.today() - entry_date).days
# Update trailing stop
cfg = asset_state["config"]
if cfg.get("trailing_stop", False):
if direction == 1 and price > best_price:
pos["best_price"] = price
best_price = price
elif direction == -1 and price < best_price:
pos["best_price"] = price
best_price = price
if direction == 1:
new_stop = best_price - stop_dist
if new_stop > stop_price:
pos["stop_price"] = new_stop
stop_price = new_stop
else:
new_stop = best_price + stop_dist
if new_stop < stop_price:
pos["stop_price"] = new_stop
stop_price = new_stop
# Check stop
stopped = False
if direction == 1 and price <= stop_price:
stopped = True
elif direction == -1 and price >= stop_price:
stopped = True
# Check time exit
max_hold = SHIFT - pos.get("K_used", 2)
time_exit = days_held >= max_hold
dir_str = "LONG" if direction == 1 else "SHORT"
unrealized = pos_size * (price - entry_price) * direction
if stopped or time_exit:
exit_price = stop_price if stopped else price
exit_reason = "stop" if stopped else "time"
pnl_gross = pos_size * (exit_price - entry_price) * direction
commission_cost = pos_value * COMMISSION * 2
pnl_net = pnl_gross - commission_cost
pnl_pct = pnl_net / pos_value * 100 if pos_value > 0 else 0
asset_state["equity"] += pnl_net
asset_state["peak_equity"] = max(
asset_state["peak_equity"], asset_state["equity"]
)
asset_state["trades_count"] += 1
asset_state["total_pnl"] += pnl_net
win = pnl_net > 0
if win:
asset_state["wins"] += 1
else:
asset_state["losses"] += 1
asset_state["open_position"] = None
closed_any = True
win_str = "WIN" if win else "LOSS"
print(f" {now.strftime('%H:%M:%S')} {asset} CLOSED {dir_str}: "
f"${entry_price:,.2f} → ${exit_price:,.2f} ({exit_reason}) "
f"PnL ${pnl_net:+,.2f} ({pnl_pct:+.2f}%) [{win_str}]")
log_event({
"type": "close",
"asset": asset,
"direction": dir_str,
"entry_price": entry_price,
"exit_price": exit_price,
"entry_date": pos["entry_date"],
"exit_date": str(date.today()),
"days_held": days_held,
"exit_reason": exit_reason,
"pnl_net": round(pnl_net, 2),
"pnl_pct": round(pnl_pct, 4),
"equity_after": round(asset_state["equity"], 2),
"win": win,
"source": "monitor",
})
else:
print(f" {now.strftime('%H:%M:%S')} {asset} {dir_str}: "
f"${price:,.2f} (stop ${stop_price:,.2f}, "
f"unreal ${unrealized:+,.2f}, day {days_held})")
return closed_any
def run_monitor(interval_minutes=240):
"""Run continuous position monitor. Shows realtime prices from Binance.
NOTE: Hourly backtest proved that intraday stop monitoring HURTS results
(Sharpe drops by 0.5-1.0 across all assets due to noise stops on wicks).
Stops are only checked on DAILY close via daily_update().
This monitor shows unrealized P&L only — no stop execution.
"""
state = load_state()
if state is None:
print("ERROR: No state found. Run with --init first.")
sys.exit(1)
exchange = ccxt.binance({"enableRateLimit": True})
print(f"{'=' * 70}")
print(f"POSITION MONITOR (Binance, every {interval_minutes}min)")
print(f"{'=' * 70}")
print(f" NOTE: stops checked on DAILY close only (hourly hurts results)")
# Check which assets have open positions
open_assets = []
for asset in ASSET_CONFIGS:
a = state["assets"].get(asset)
if a and a.get("open_position"):
pos = a["open_position"]
d = "LONG" if pos["direction"] == 1 else "SHORT"
print(f" {asset}: {d} @ ${pos['entry_price']:,.2f}, "
f"stop ${pos['stop_price']:,.2f}")
open_assets.append(asset)
if not open_assets:
print("\n No open positions to monitor.")
print(" Run daily update first to generate signals.")
return
print(f"\n Monitoring {len(open_assets)} positions...")
print(f" Press Ctrl+C to stop.\n")
try:
while True:
state = load_state()
if state is None:
break
has_open = any(
state["assets"].get(a, {}).get("open_position")
for a in ASSET_CONFIGS
)
if not has_open:
print(f"\n All positions closed. Stopping monitor.")
break
# Show current prices and unrealized P&L (NO stop execution)
now = datetime.now()
for asset in ASSET_CONFIGS:
asset_state = state["assets"].get(asset)
if not asset_state:
continue
pos = asset_state.get("open_position")
if not pos:
continue
price = _fetch_realtime_price(exchange, asset)
if price is None:
continue
direction = pos["direction"]
entry_price = pos["entry_price"]
stop_price = pos["stop_price"]
pos_size = pos["pos_size"]
entry_date = date.fromisoformat(pos["entry_date"])
days_held = (date.today() - entry_date).days
unrealized = pos_size * (price - entry_price) * direction
dir_str = "LONG" if direction == 1 else "SHORT"
dist_to_stop = abs(price - stop_price)
print(f" {now.strftime('%H:%M:%S')} {asset} {dir_str}: "
f"${price:,.2f} (stop ${stop_price:,.2f}, "
f"dist ${dist_to_stop:,.2f}, "
f"unreal ${unrealized:+,.2f}, day {days_held})")
time.sleep(interval_minutes * 60)
except KeyboardInterrupt:
print(f"\n\n Monitor stopped.")
_print_portfolio_summary(state)
# -- Entry point -------------------------------------------------------------
def main():
@@ -703,6 +936,10 @@ def main():
help="Show current positions and equity")
parser.add_argument("--history", action="store_true",
help="Show trade history")
parser.add_argument("--monitor", action="store_true",
help="Realtime stop monitor via Binance")
parser.add_argument("--interval", type=int, default=240,
help="Monitor check interval in minutes (default: 240)")
args = parser.parse_args()
if args.init:
@@ -711,6 +948,8 @@ def main():
show_status()
elif args.history:
show_history()
elif args.monitor:
run_monitor(args.interval)
else:
daily_update()