# AI Trader Market Feature Enrichment Design

## Goal

Add richer Binance Spot market features to the `live-ai-trade-once` and `live-ai-trade-batch-once` model context so the LLM can judge market direction using structured OHLCV, trend, momentum, volatility, volume, breakout, ticker, average-price, and order-book liquidity signals.

## External Data Sources

Use Binance Spot market-data REST endpoints only. Do not expose API keys, secrets, order placement permissions, or private order details to the model.

- `/api/v3/klines`: existing source for candle data. Binance klines include open time, open, high, low, close, base volume, close time, quote asset volume, number of trades, taker buy base volume, and taker buy quote volume.
- `/api/v3/ticker/bookTicker`: existing best bid/ask source. Extend usage to include `bidQty` and `askQty` when present.
- `/api/v3/depth?limit=20`: new public order-book source for top-of-book depth. Use 20 levels per symbol to keep weight and payload bounded.
- `/api/v3/ticker/24hr`: new public 24-hour ticker source for weighted average price, 24h price change, 24h high/low, volume, quote volume, and trade count.
- `/api/v3/avgPrice`: new public current average price source.

## Feature Set

For each configured AI trader symbol, include the existing fields plus the following additional fields.

### OHLCV

For every configured interval in `BINANCE_AI_TRADER_KLINES`, include:

- `opens`
- `highs`
- `lows`
- `closes`
- `volumes`
- `quote_volumes`
- `trade_counts`
- `taker_buy_base_volumes`
- `taker_buy_quote_volumes`

If older tests or mock data provide only the first six kline fields, missing optional kline fields default to zero so existing fixtures remain simple.

### Indicators

Compute indicators per timeframe from the candles available in that timeframe:

- `sma_7`, `sma_20`
- `ema_12`, `ema_26`
- `rsi_14`
- `macd`, `macd_signal`, `macd_histogram` using 12/26/9 EMA settings
- `atr_14`

Indicator values are serialized as strings or `null` when there is insufficient data. With the current default `1h:24,4h:30,1d:14`, daily `sma_20`, MACD, and ATR may be `null`; that is preferable to inventing values.

### Volume

Compute:

- `latest_volume`
- `average_volume_20`
- `volume_ratio_20`: latest base volume divided by average base volume over up to the last 20 candles excluding the latest candle when possible.
- `latest_quote_volume`
- `average_quote_volume_20`
- `quote_volume_ratio_20`

If the denominator is zero or unavailable, ratio fields are `null`.

### Range And Breakout

Compute over up to the last 20 candles:

- `high_20`
- `low_20`
- `distance_from_high_20_bps`: `(latest_close - high_20) / high_20 * 10000`
- `distance_from_low_20_bps`: `(latest_close - low_20) / low_20 * 10000`
- `breakout_up_20`: latest close is greater than the highest high before the latest candle.
- `breakdown_down_20`: latest close is lower than the lowest low before the latest candle.

When fewer than two candles exist, breakout flags are false and distance fields are `null` if the needed denominator is zero.

### 24h Ticker And Average Price

Include:

- `price_change`
- `price_change_percent`
- `weighted_avg_price`
- `high_price`
- `low_price`
- `volume`
- `quote_volume`
- `trade_count`
- `current_average_price`
- `average_price_mins`

All fields come directly from Binance responses and are serialized as strings except trade counts/minutes as integers where practical.

### Liquidity And Spread Rating

Include:

- Existing `bid`, `ask`, and `spread_bps`.
- `best_bid_qty`, `best_ask_qty`, `best_bid_notional`, `best_ask_notional` from bookTicker when quantities are present.
- `depth_limit`: 20.
- `depth_bid_notional`, `depth_ask_notional`: sum of price * quantity over depth levels.
- `depth_bid_qty`, `depth_ask_qty`.
- `depth_imbalance`: `(depth_bid_notional - depth_ask_notional) / (depth_bid_notional + depth_ask_notional)`.
- `liquidity_rating`: `excellent`, `good`, `fair`, or `poor`.
- `spread_rating`: `tight`, `normal`, `wide`, or `very_wide`.

Ratings are deterministic and local. Initial thresholds:

- Spread rating: `tight` <= 2 bps, `normal` <= 5 bps, `wide` <= 10 bps, otherwise `very_wide`.
- Liquidity rating uses the smaller of 20-level bid and ask notional: `excellent` >= 100000 USDT, `good` >= 25000 USDT, `fair` >= 5000 USDT, otherwise `poor`.

These ratings are advisory context for the model only. Existing local risk checks remain authoritative.

## Architecture

Keep the AI trader enrichment inside `src/binance_quant/ai_trader.py` and `src/binance_quant/exchange.py` to match the existing structure. The exchange client will add small public market-data methods for `depth`, `ticker_24hr`, and `avg_price`. The AI trader will parse richer candle fields into the existing `Candle` model extended with optional quote-volume/trade fields.

No new third-party technical-analysis dependency is required. Indicator formulas are small, deterministic, and testable with `Decimal` arithmetic. This avoids dependency drift in a live trading command.

## Data Flow

1. The live AI runner loads account data as it does today.
2. For each configured symbol, `_load_symbol_context` fetches exchange metadata, bookTicker, depth, 24h ticker, avgPrice, open orders, and configured klines.
3. Kline rows are parsed into `Candle` objects.
4. `_model_context` builds a compact JSON object with raw arrays and calculated feature summaries per timeframe.
5. The Codex prompt passes that enriched context to the model.
6. Model predictions still flow through existing validation, confidence thresholds, local risk checks, and execution code.

## Error Handling

The current AI trader treats pre-model data-loading failures as a rejected AI trade run. Preserve that behavior. If one of the new public market-data calls fails, the whole pre-model load fails instead of sending partial context that might mislead the model.

Optional fields inside otherwise valid Binance payloads default to zero or `null` as described above. Malformed numeric fields should raise during parsing so the run fails closed.

## Prompt Update

Keep the output schema unchanged. Add a concise instruction that the model should consider trend, momentum, volatility, volume confirmation, 24h context, breakout state, spread, and liquidity when assigning action and confidence.

Do not instruct the model to inflate confidence. The goal is better-calibrated confidence, not higher numbers by prompt pressure.

## Testing

Add focused tests before implementation:

- Exchange client sends the correct `/v3/depth`, `/v3/ticker/24hr`, and `/v3/avgPrice` requests.
- Kline parsing captures quote volume, trade count, and taker-buy volumes.
- `_model_context` includes OHLCV arrays, indicators, volume ratios, range distances, breakout flags, ticker, average price, and liquidity ratings.
- Indicator helpers return expected values on small deterministic sequences and return `None` when insufficient data exists.
- Existing AI trader batch behavior still rejects low-confidence predictions and still preserves HOLD rows.

Run at least:

- `py -3 -m pytest tests/test_ai_trader.py tests/test_exchange.py -q`
- `py -3 -m pytest -q`

## Non-Goals

- Do not add Futures, Margin, leverage, news, social media, or external non-Binance data.
- Do not let the model place trades or bypass local risk checks.
- Do not change the prediction JSON schema or confidence threshold semantics.
- Do not change order sizing, stop-loss, cooldown, daily limit, or batch limit behavior.
