engine/cross_fr/order.py:13-159mixes strategy logic, exchange connectivity, config loading, and console I/O, so it cannot be reused across strategies or tested in isolation. It also instantiates REST clients directly instead of relying on shared exchange adapters.engine/cross_fr/trading_signal.py:5-40depends on an unavailableCross_fr_arbitragepackage and writes JSON outputs in place, which makes signal generation brittle and hard to orchestrate in production.src/core/base.py:14-36sketches an exchange interface but does not enforce concrete implementations, and most high-level code bypasses it, leading to duplicated REST plumbing (for example inBinance_info).src/exchange/hyperliquid_sdk.py:1-18is a stub with incorrect imports, highlighting the lack of a consistent adapter layer for non-Binance venues.- Configuration is fragmented (
config/config.jsonis empty, whileparameter.jsonstores webhook secrets) and there is no environment-aware settings loader or validation.
Adopt a layered/event-driven design so strategy logic, execution, and infrastructure can evolve independently.
order_engine/
apps/
live_trader.py # composition root for prod trading sessions
backtester.py # reuse the same services for research/offline replay
config/
settings.py # pydantic BaseSettings or dynaconf backed by env vars
core/
events.py # domain events (SignalDetected, OrderFilled, etc.)
models.py # dataclasses for Candle, OrderRequest, Position
data_providers/
binance_ws.py # websocket + REST wrappers, reconnect logic
historical_store.py # pulls historical data for research/backfill
strategies/
cross_funding/
strategy.py # funding arbitrage signal generator
parameters.py # validated strategy config schema
risk/
exposure_limits.py # defines firm-level risk constraints
position_sizer.py # converts signals into target positions
execution/
order_router.py # routes orders across exchanges/connectors
metrics.py # slippage, fill ratio tracking
exchanges/
binance.py # implements UniversalExchange interface
hyperliquid.py # idem
portfolio/
position_service.py # maintains portfolio state, avg price, pnl
monitoring/
alerts.py # Discord/Slack/Email notifier abstractions
dashboards.py # optional Prometheus/Grafana exporters
storage/
repositories.py # persistence (Redis, Postgres, S3, etc.)
tests/
unit/
integration/
- Single responsibility services: split the current monolithic
OrderManagerintoSignalService,RiskManager,PositionManager, andExecutionServiceso each piece can be simulated or replaced independently. - Dependency inversion: high-level modules accept interfaces (e.g.,
ExchangeClientprotocol) and receive concrete exchange adapters via dependency injection. This keeps backtests and paper trading simple. - Event-driven orchestration: propagate
SignalDetected,OrderPlaced,OrderFilled, andRiskLimitBreachedevents through an internal bus (simple in-memory pub/sub, Redis streams, or Kafka for scale). Strategies publish intents; the execution engine acts as the sole component talking to exchanges. - Asynchronous market data: use websocket clients and background tasks to maintain order book snapshots, throttled REST fallbacks, and cached reference data. Surface normalized tick/level-2 feeds to strategies.
- Stateful portfolio layer: keep canonical positions, margins, realized/unrealized PnL, and capital usage in a single service backed by durable storage so restarts do not lose context.
data_providers: streaming candles, order books, funding rates, with resampling and throttling logic.strategies: pure functions/classes that transform normalized data into signals; no I/O side effects.risk: pre-trade checks (max notional, drawdown, volatility filters), circuit breakers, kill switches.portfolio: maintains account state and shares it with strategies and risk modules.execution: order routing, smart order placement (TWAP, iceberg), and post-trade reconciliation.monitoring: alerting when latency spikes, fills drop, or health checks fail; integrate with Discord via a notifier abstraction rather than direct webhook calls.
- Data ingestion: websocket workers push updates into an in-memory store; snapshot/heartbeat tasks ensure freshness.
- Signal evaluation: strategies consume normalized data plus portfolio context and emit intents (
TargetPositionevents). - Risk gating: risk engine validates intents against limits (exposure, leverage, drawdown). Failing checks emit alerts and block the order.
- Order sizing: position service converts target positions into incremental orders considering current fills.
- Execution: order router selects the proper exchange adapter, applies exchange-specific rules, and submits via unified REST/WebSocket clients.
- Post-trade: fills update portfolio state, trigger PnL calculations, and feed monitoring dashboards.
- Persistence & audit: all decisions (signals, risk decisions, orders, fills) append to an audit log for replay/backtesting.
- Configuration: leverage
pydantic.BaseSettingswith.envdefaults; split secrets from strategy parameters. Include schema validation so empty configs likeconfig/config.jsonare caught at startup. - Logging & metrics: standardize on
structlogorloggingwith JSON output, tagged by component. Export Prometheus metrics for latency, success rates, and capital usage. - Testing strategy logic: move notebooks (
research/research.ipynb) insights into parametrized tests and simulation harnesses. Provide fixtures that replay historical data through the strategy and risk layers. - Deployment modes: support
live,paper, andbacktestmodes via a runtime configuration object that swaps implementations (e.g., live Binance vs. simulator adapters). - Error handling & resilience: central retry/backoff policies, idempotent order submission, and state checkpointing so restarts recover gracefully.
- Foundation (Week 1-2)
- Introduce typed config loader, structured logging, and health checks.
- Refactor
BinanceFuturesClientinto theexchanges/adapter layer and delete the ad-hocBinance_infowrapper. - Extract funding signal calculation from notebooks into a pure strategy module with unit tests.
- Core services (Week 3-5)
- Build market data ingestion workers (REST bootstrap + websocket stream) and event bus primitives.
- Implement strategy -> risk -> execution orchestration with dependency injection.
- Stand up the portfolio service with persistence (start with SQLite or Redis, swap later).
- Execution hardening (Week 6-8)
- Add order state reconciliation against exchange reports, handle partial fills, and implement kill switch.
- Integrate risk alerting with Discord/Slack via notifier abstraction.
- Add monitoring dashboards/metrics.
- Backtesting & research integration (Week 9+)
- Create a replay engine that feeds historical data into the same services.
- Automate notebook-to-production workflow by versioning strategy notebooks and exporting parameters.
- Expand exchange adapters (Hyperliquid, OKX) using the shared interface.
- Normalize configuration and secrets management before wiring the live trading loop.
- Define clear data models (
dataclasses/pydantic) for signals, orders, and positions, and enforce them across modules. - Replace direct REST calls in
engine/cross_fr/order.pywith the unified execution pathway once the adapters are in place. - Backfill tests that assert signal quality against historical funding data before enabling auto-trading.