# Codex Exec AI Trader Design

## Purpose

Add a production Spot command that asks `codex exec` for a structured market direction prediction and then routes the result through existing local trading controls. The model may recommend `BUY`, `SELL`, or `HOLD`; local code remains responsible for validating the prediction, enforcing risk limits, and submitting any Binance order.

## Architecture

The feature is a one-shot live command, `binance-quant live-ai-trade-once`. It scans configured USDT symbols, fetches market summaries, invokes `codex exec` through a small predictor adapter, validates the structured JSON response, and then delegates execution to existing auto-buy and auto-sell engines. The predictor never receives API secrets and never calls Binance directly.

The implementation keeps three boundaries explicit:

- `config.py` owns AI trader settings: enable switch, symbols, model override, confidence threshold, timeout, buy quote size, and shared risk limits.
- `ai_trader.py` owns prediction prompt construction, subprocess invocation, response validation, and one-shot orchestration.
- `cli.py` and `scripts/run.ps1` expose the feature while preserving existing live-mode safety checks.

## Data Flow

For each symbol, the runner fetches symbol metadata, bid/ask ticker, recent hourly klines, open orders, and account balances. It builds a compact JSON market context with prices, spreads, momentum inputs, and current free balances. The predictor calls `codex exec --output-schema <schema> <prompt>` and expects one JSON object containing `symbol`, `action`, `confidence`, and `reason`.

If the response is invalid, below the confidence threshold, for an unrequested symbol, or `HOLD`, the run records a rejected/no-action outcome and submits no order. A `BUY` prediction creates an `AutoBuyCandidate` and uses `AutoBuyRiskEngine` plus `AutoBuyExecutionEngine`. A `SELL` prediction creates an `AutoSellCandidate` and uses `AutoSellRiskEngine` plus `AutoSellExecutionEngine`.

## Risk And Safety

The command is live-only and disabled unless `BINANCE_LIVE_AI_TRADER_ENABLED=true`. It performs at most one trade per run. The model cannot bypass daily limits, cooldowns, exchange filters, minimum notional checks, balance checks, spread checks, existing open-order checks, or the auto-buy protective stop flow. Model output is treated as untrusted data; malformed output becomes `HOLD`.

The `codex exec` subprocess runs with a timeout. The prompt instructs Codex to return JSON only and not to place trades or use tools. The model receives market data only, not API keys or secrets.

## Testing

Tests cover configuration defaults and environment overrides, predictor JSON parsing and invalid-output fallback, command construction for `codex exec`, orchestration for BUY/SELL/HOLD decisions, and CLI output/exit-code behavior. Exchange and predictor dependencies are injected in tests so no real Binance or Codex calls are made.
