# AI Futures Trading Design

## Goal

Add an AI-driven Binance USDT-M perpetual futures trading workflow alongside the existing Spot AI trader. The first version supports dry-run, futures testnet live, and production live with explicit production enablement. It targets one-way position mode, isolated margin, AI-suggested leverage and protection prices, local risk enforcement, and batch execution.

## Scope

Implement USDT-M perpetual futures only. Do not support COIN-M futures, options, hedge mode, cross margin, automatic reverse trading, or arbitrary close percentages in this version.

The workflow supports:

- `OPEN_LONG`
- `OPEN_SHORT`
- `CLOSE`
- `HOLD`

Reverse signals should not flip a position in one step. If the account has a long and the AI predicts a short, the local system may only close the existing long. A new short requires a later run after the position is flat.

## Architecture

Add a separate futures subsystem instead of extending the existing Spot AI execution path:

- `futures_exchange.py`: Binance USDT-M futures REST client for `/fapi` account, position, order, algo order, cancel, leverage, margin mode, exchangeInfo, mark price, funding, open interest, and long/short data.
- `futures_models.py`: futures-specific enums and dataclasses for actions, one-way positions, protection orders, predictions, risk decisions, and execution results.
- `futures_risk.py`: local futures risk engine for fixed margin sizing, AI leverage clipping, total margin budget, daily realized loss limit, stop/take-profit validation, close percentage validation, isolated margin, and one-way mode.
- `futures_execution.py`: dry-run/testnet/live execution for opening positions, placing stop-loss and take-profit protection through USD-M Futures algo orders, rolling back unprotected opens, closing by allowed percentages, and recreating protection after partial closes.
- `futures_ai_trader.py`: futures AI batch runner, prompt/schema handling, market context construction, prediction recording, sorting, and per-candidate execution orchestration.
- `cli.py`: add `live-futures-ai-trade-batch-once`.
- `scripts/run.ps1`: add `-Action live-futures-ai-trade-batch-once`.
- `storage.py`: add futures-specific audit tables and helpers.

The existing Spot modules stay behaviorally unchanged. Shared indicator or market-feature helpers can be extracted only when the implementation can do so with low regression risk; otherwise the first futures version may duplicate small deterministic helpers.

## Configuration

Add futures-specific settings so Spot and Futures controls are not confused:

- `BINANCE_FUTURES_AI_SYMBOLS`
- `BINANCE_LIVE_FUTURES_AI_TRADER_ENABLED`
- `BINANCE_LIVE_FUTURES_CONFIRM_PRODUCTION`
- `BINANCE_FUTURES_MARGIN_AMOUNT`
- `BINANCE_FUTURES_DEFAULT_LEVERAGE`
- `BINANCE_FUTURES_MAX_LEVERAGE`
- `BINANCE_FUTURES_MAX_TOTAL_MARGIN`
- `BINANCE_FUTURES_AI_MIN_CONFIDENCE`
- `BINANCE_FUTURES_AI_MAX_ACTIONS_PER_RUN`
- `BINANCE_FUTURES_DAILY_REALIZED_LOSS_LIMIT`
- `BINANCE_FUTURES_MAX_MARGIN_LOSS_PERCENT`
- `BINANCE_FUTURES_MIN_LIQUIDATION_BUFFER_PERCENT`
- `BINANCE_FUTURES_MIN_STOP_DISTANCE_PERCENT`
- `BINANCE_FUTURES_MAX_STOP_DISTANCE_PERCENT`
- `BINANCE_FUTURES_MIN_TAKE_PROFIT_DISTANCE_PERCENT`
- `BINANCE_FUTURES_MAX_TAKE_PROFIT_DISTANCE_PERCENT`

Production live mode must require all existing live credential and host validation plus both futures live enablement settings. Development defaults should stay conservative: dry-run mode, low margin amount, low default leverage, and a bounded max action count.

## Market And Account Context

The futures runner should call the model once per batch with one prediction per configured symbol. For each symbol, include compact futures market context:

- warmed kline indicator features using the current Spot AI methodology,
- order book and spread features,
- 24h ticker features,
- aggregate trade features,
- mark price,
- funding rate and next funding time when available,
- open interest,
- long/short ratio,
- taker long/short ratio.

The model may also receive a compact current-position summary for each symbol: side, quantity, entry price, mark price, unrealized PnL, liquidation price, isolated margin, and local protection-order summary. This context helps it decide `CLOSE`, but execution eligibility remains local. The model must not receive secrets or signed URLs and must not be allowed to place orders or call tools.

## AI Prediction Schema

The predictor returns one JSON object:

```json
{
  "predictions": [
    {
      "symbol": "BTCUSDT",
      "action": "OPEN_LONG",
      "confidence": "0.82",
      "leverage": 3,
      "stop_loss_price": "62000.0",
      "take_profit_price": "66000.0",
      "close_percent": 100,
      "reason": "..."
    }
  ]
}
```

Rules:

- `action` is one of `OPEN_LONG`, `OPEN_SHORT`, `CLOSE`, or `HOLD`.
- `confidence` is a decimal string from `0` to `1`.
- `leverage` applies only to `OPEN_LONG` and `OPEN_SHORT`; if missing or invalid, local code uses the configured default, then clips to `BINANCE_FUTURES_MAX_LEVERAGE`.
- `stop_loss_price` and `take_profit_price` are required for open actions.
- `close_percent` is required for `CLOSE` and must be one of `25`, `50`, or `100`.
- `HOLD` requires only `symbol`, `action`, `confidence`, and `reason`.

Invalid predictions become HOLD or rejected outcomes with explicit reasons, matching the existing AI trader's defensive parsing style.

## Data Flow

The batch command flow:

1. Load settings and validate futures mode, hosts, credentials, and production confirmation.
2. Initialize the futures client for dry-run, testnet, or production.
3. Fetch futures market context for configured symbols.
4. Fetch account, one-way position mode, positions, open regular orders, open algo orders, and daily realized PnL.
5. Call `codex exec` once with a futures-specific schema and prompt.
6. Record every prediction before attempting orders.
7. Sort actionable predictions by confidence descending, with configured symbol order as tie-breaker.
8. For each candidate, refresh account, positions, open regular orders, open algo orders, exchange filters, mark price, and daily realized PnL before risk evaluation.
9. Execute approved candidates until `BINANCE_FUTURES_AI_MAX_ACTIONS_PER_RUN` is reached.
10. Mark remaining actionable predictions as `skipped`.

Rejected candidates do not consume the action limit. Any submitted open, close, or rollback order consumes the action limit.

## Risk Model

Risk is split into run-level preflight and per-candidate checks.

Run-level preflight:

- Production live requires `BINANCE_MODE=live`, `BINANCE_LIVE_FUTURES_AI_TRADER_ENABLED=true`, `BINANCE_LIVE_FUTURES_CONFIRM_PRODUCTION=true`, valid credentials, and production futures hosts.
- Account position mode must be one-way. Hedge mode rejects the run.
- Symbols must be tradable USDT-M perpetual futures.
- Live/testnet execution must use isolated margin and leverage within the configured local max.
- If daily realized loss is at or beyond the configured limit, new opens are rejected while closes remain allowed.

Per-candidate risk:

- Confidence must meet `BINANCE_FUTURES_AI_MIN_CONFIDENCE`.
- Open notional is `BINANCE_FUTURES_MARGIN_AMOUNT * clipped_leverage`.
- Current isolated margin usage plus the new margin amount must not exceed `BINANCE_FUTURES_MAX_TOTAL_MARGIN`.
- Existing same-symbol same-direction positions reject further adds.
- Existing opposite positions reject open actions; only `CLOSE` is allowed.
- Stop loss and take profit are both required for open actions.
- For longs: `stop_loss < reference_price < take_profit`.
- For shorts: `take_profit < reference_price < stop_loss`.
- Stop and take-profit distances must fall inside local configured min/max percentages.
- Estimated stop-loss loss must fit `BINANCE_FUTURES_MAX_MARGIN_LOSS_PERCENT`.
- If the liquidation price is closer to mark price than `BINANCE_FUTURES_MIN_LIQUIDATION_BUFFER_PERCENT`, reject opens.
- Close actions require an existing position and an allowed close percentage.
- Close quantities are rounded down to the exchange step size. If the remaining position after a partial close would be below exchange minimum quantity or notional, execute a full close or reject with an explicit reason.

Every candidate in a batch must be evaluated against freshly fetched state.

## Execution Model

Open execution:

1. Calculate quantity from fixed margin, clipped leverage, and reference price.
2. Round quantity down to futures step size and validate minimum quantity and notional.
3. In dry-run, record the intended open and protection orders without Binance side effects.
4. In testnet/live, ensure isolated margin and leverage settings before order submission.
5. Submit the market open order.
6. Refresh the position and derive actual quantity and entry price.
7. Submit reduce-only conditional algo orders for protection:
   - `POST /fapi/v1/algoOrder` with `algoType=CONDITIONAL`, `type=STOP_MARKET`, `triggerPrice`, `quantity`, `reduceOnly=true`, `workingType=MARK_PRICE`, and a bot `clientAlgoId`.
   - `POST /fapi/v1/algoOrder` with `algoType=CONDITIONAL`, `type=TAKE_PROFIT_MARKET`, `triggerPrice`, `quantity`, `reduceOnly=true`, `workingType=MARK_PRICE`, and a bot `clientAlgoId`.
8. Mark the result `protected` only if the position and both protection orders are accepted.
9. If protection fails after an open, immediately submit a reduce-only market close. Mark `rollback_completed` or `rollback_failed`.

Close execution:

1. Locate the current one-way position.
2. Cancel this system's protection algo orders for the symbol through `DELETE /fapi/v1/algoOrder`.
3. Calculate the close quantity from `25`, `50`, or `100` percent.
4. Round down and validate quantity. If a partial close would leave a dust position, close fully or reject with a clear reason.
5. Submit a reduce-only market close.
6. Refresh the position.
7. If a position remains, recreate stop-loss and take-profit protection as algo orders for the remaining quantity.
8. Mark `closed`, `partially_closed`, `close_failed`, or `close_protection_failed`.

Suggested statuses:

- `predicted`
- `rejected`
- `skipped`
- `dry_run`
- `protected`
- `closed`
- `partially_closed`
- `rollback_completed`
- `rollback_failed`
- `close_failed`
- `close_protection_failed`

Failure statuses that indicate live order risk should exit non-zero.

## Storage And Audit

Add futures-specific tables or table families:

- `futures_ai_trade_runs`: one row per prediction with action, confidence, leverage, stop/take-profit, close percent, status, reason, and raw prediction.
- `futures_order_events`: open, stop algo, take-profit algo, close, cancel algo, and rollback order event summaries, with raw exchange payloads sanitized.
- `futures_position_snapshots`: before/after snapshots containing symbol, side, quantity, entry price, mark price, liquidation price, isolated margin, unrealized PnL, and timestamp.
- Daily PnL helper/cache: initially derive realized PnL from Binance futures income/history plus local execution windows; cache only if needed for rate-limit control.

Audit logs must avoid API secrets, signed query strings, and request signatures. They should include formulas and input values used for risk decisions where practical.

## CLI And Script Behavior

Add:

```text
binance-quant live-futures-ai-trade-batch-once
```

CLI output should include:

- overall status,
- reason,
- prediction count,
- max actions,
- executed actions,
- daily realized PnL,
- total isolated margin usage,
- per-action table with run ID, symbol, action, confidence, status, leverage, margin, close percent, and reason.

`scripts/run.ps1` should support:

```powershell
.\scripts\run.ps1 -Action live-futures-ai-trade-batch-once
```

The script should apply the same live production safety posture as existing live commands, with futures-specific confirmation.

## Error Handling

Best-effort market data failures should degrade that symbol's context and lower confidence guidance rather than aborting the whole run, unless required execution data is missing. Missing account state, positions, exchange filters, or mark price must reject the affected candidate or fail the preflight because those values are required for safe order sizing.

If the predictor times out, returns invalid JSON, or omits symbols, record HOLD/rejected results for the affected symbols. If a live/testnet API request fails after order activity has started, record the failure state and return a non-zero CLI exit code.

## Testing

Use test-first implementation. Add focused tests for:

- futures config defaults, parsing, and invalid values,
- futures host validation for testnet and production,
- futures signed requests and endpoint parameters,
- AI prediction parsing and schema validation,
- invalid action handling and missing protection prices,
- leverage clipping and default leverage fallback,
- confidence threshold rejection,
- total margin cap enforcement,
- daily realized loss limit blocking opens while allowing closes,
- one-way mode preflight rejection when hedge mode is active,
- same-direction add rejection and opposite-position open rejection,
- stop-loss and take-profit direction/distance validation,
- dry-run open and close behavior,
- open plus two protection orders success,
- protection failure rollback success and failure,
- partial close quantity rounding and remaining-position protection recreation,
- batch sorting, max actions, skipped remaining actions, and state refresh before each candidate,
- CLI output and exit codes,
- PowerShell runner action coverage,
- Spot regression tests proving existing AI/auto-buy/auto-sell behavior is unchanged.

## Non-Goals

- Do not support COIN-M futures.
- Do not support hedge mode.
- Do not use cross margin.
- Do not allow automatic reverse trading in one run.
- Do not allow arbitrary close percentages.
- Do not let the model place orders, call tools, or decide execution eligibility.
- Do not rewrite the existing Spot AI trader as part of this feature.
