# Binance Live Auto Buyer Design

## Goal

Add a tightly bounded real-money Binance Spot automation that can buy a high-liquidity USDT pair without manual confirmation when objective market rules pass. The system must immediately attempt to protect each filled buy with a fixed 2% stop loss and must unwind the position if protection cannot be placed.

This feature is intentionally conservative. It is not a discretionary AI trader and does not let a language model choose trades.

## Scope

The first live auto-buyer supports only Binance Spot production mode with these fixed operating limits:

- Trading pool: `BTCUSDT`, `ETHUSDT`, `BNBUSDT`, `SOLUSDT`.
- Buy notional: `5 USDT` per trade.
- Daily cap: at most `5` successful buy attempts per local calendar day.
- Stop loss: fixed 2% below the actual average fill price.
- Execution cadence: intended for an hourly automation run.

The automation skips a run instead of increasing size when `5 USDT` is below the exchange minimum notional for the selected symbol.

## Non-Goals

The first version does not include all-market scanning, futures, margin, leverage, shorting, pyramiding, averaging down, take-profit orders, OCO order lists, portfolio optimization, news or social-media signals, AI-generated discretionary trade decisions, or automatic size escalation.

## External API Requirements

The implementation uses Binance Spot REST endpoints:

- Public market data for ticker, order book, exchange metadata, and klines.
- Signed account reads for balances and open-order checks.
- Signed market buy order submission.
- Signed stop-loss protection through a Spot `STOP_LOSS_LIMIT` sell order.
- Signed market sell order submission for rollback when protection fails.

Before live order support is enabled, the implementation must use Binance test endpoints where available, including `/api/v3/order/test` for market-order shape validation. Runtime still relies on exchange responses because Spot symbol rules differ by symbol and can change.

## Architecture

The existing modules remain the base:

- `config`: add explicit auto-buyer settings for symbol pool, notional, daily cap, stop percentage, strategy thresholds, and live enablement.
- `exchange`: add Spot methods for market data, quantity-based market sells, open orders, order tests, and protective stop placement.
- `strategy`: add a deterministic multi-symbol momentum scanner that scores only the configured pool.
- `risk`: add live auto-buyer checks for daily cap, min notional, USDT balance, existing exposure, spread, liquidity, and live enablement.
- `execution`: add a two-phase live buy workflow: buy first, protect immediately, rollback on protection failure.
- `storage`: persist scanner candidates, risk decisions, buy orders, protection orders, rollback orders, and failures.
- `cli`: expose a single-run command intended for cron automation.

The cron automation should call the CLI command. It should not embed trading logic in the automation prompt.

## Data Flow

On each run, the command loads settings and verifies `BINANCE_MODE=live` plus a separate explicit live-auto-buyer enable flag. It fetches exchange metadata, balances, current ticker/order-book data, and recent klines for every configured symbol.

The scanner scores each symbol. The risk engine filters the highest-scoring candidate through account and symbol checks. If no candidate passes, the run records the reason and exits without submitting orders.

If a candidate passes, execution submits a market buy for `5 USDT`. After the buy response, execution derives actual average fill price and executed base quantity from the exchange response. It then computes a stop trigger at 98% of the average fill price and a stop limit price slightly below the trigger according to configured slippage, rounded to symbol tick-size rules.

If the protective `STOP_LOSS_LIMIT` order is accepted, the run records the protected position and exits successfully. If the protective order fails or cannot be confirmed, execution immediately submits a market sell for the actual executed base quantity, records the rollback, and marks the run as protection failed.

## Entry Strategy

The scanner is deterministic and must be testable. It should use only market data and fixed thresholds. A candidate is eligible only when all of these are true:

- The symbol is in the configured high-liquidity pool.
- Recent momentum is positive on both a short and medium window, for example 1-hour and 4-hour returns.
- A short moving average is above a longer moving average.
- Recent volume is not below its baseline.
- Current bid/ask spread is below the configured maximum.
- The score is above a configured minimum threshold.

The scanner selects at most one symbol per run: the eligible symbol with the highest score. If scores tie, it uses a deterministic order from the configured pool.

## Risk Controls

The risk engine must reject trading when any of these is true:

- `BINANCE_MODE` is not `live`.
- The explicit auto-buyer enable flag is not set.
- The system has already reached `5` live buy attempts for the local calendar day.
- The requested `5 USDT` notional is below the selected symbol's exchange minimum notional.
- Free USDT balance is below the requested notional plus a small configurable reserve.
- The account already has an unprotected position or open protective order for the selected base asset.
- Current spread exceeds the configured maximum.
- A previous run for the same symbol was submitted recently enough to violate the cooldown.
- Exchange metadata lacks required filters for safe rounding.

Daily cap accounting is based on stored live buy attempts, not only successful protected positions. This prevents repeated retries from exceeding the intended budget.

## Protective Stop Loss

The stop loss is fixed at 2% below actual average fill price. The implementation rounds stop price, limit price, and quantity using exchange filters. The limit price should be below the trigger price by a small configured buffer to improve the chance of execution after trigger.

The stop order quantity must not exceed the actual executed base quantity after rounding. If the rounded quantity is below the symbol minimum quantity or cannot satisfy exchange filters, protection is considered failed and rollback starts immediately.

## Protection Failure Rollback

If market buy succeeds but protection fails, execution must immediately submit a market sell for the executed base quantity rounded down to the allowed step size. The system records:

- Original candidate and score.
- Market buy request and response.
- Protection request attempt and sanitized error.
- Rollback sell request and response.
- Final run status.

If rollback also fails, the run records a critical unprotected-position failure and exits non-zero. It must not keep retrying indefinitely inside one cron run.

## Error Handling

Network failures before order submission cause the run to exit without trading. Failures after a buy are handled through the protection/rollback path. Binance error responses are recorded with code and message when available, but API keys and signatures are never logged.

Every live order uses a unique client order id with a feature-specific prefix. Re-running after a crash must inspect storage and open orders before submitting another buy so the command does not duplicate exposure blindly.

## Configuration

New settings should include:

- `BINANCE_LIVE_AUTO_BUYER_ENABLED=false` by default.
- `BINANCE_AUTO_BUY_SYMBOLS=BTCUSDT,ETHUSDT,BNBUSDT,SOLUSDT`.
- `BINANCE_AUTO_BUY_QUOTE_AMOUNT=5`.
- `BINANCE_AUTO_BUY_DAILY_LIMIT=5`.
- `BINANCE_AUTO_BUY_STOP_LOSS_PERCENT=2`.
- `BINANCE_AUTO_BUY_STOP_LIMIT_BUFFER_PERCENT=0.2`, meaning the stop-limit price is 0.2% below the stop trigger.
- `BINANCE_AUTO_BUY_MAX_SPREAD_BPS=10`.
- `BINANCE_AUTO_BUY_COOLDOWN_SECONDS=3600`.
- Scanner threshold settings with conservative defaults: positive 1-hour return, positive 4-hour return, short moving average above long moving average, and current volume not below its recent baseline.

The feature must not use existing `BINANCE_QUOTE_AMOUNT` implicitly. Live auto-buy sizing is separate so existing trade-loop behavior does not accidentally change.

## CLI And Automation

Add a command such as:

```powershell
binance-quant live-auto-buy-once
```

The command performs exactly one scan and at most one buy attempt. The Codex automation should run this command hourly in `E:\GitStore\binance`. The automation prompt should only instruct it to run and report the CLI result, not to choose trades itself.

## Testing

Tests must cover:

- Settings defaults keep live auto-buyer disabled.
- Symbol pool parsing and validation.
- Scanner scoring and deterministic tie-breaking.
- Risk rejection for daily cap, insufficient balance, min notional, spread, existing exposure, and disabled live flag.
- Market buy followed by successful protective stop.
- Market buy followed by protection failure and rollback sell.
- Rollback failure records critical unprotected-position status.
- No duplicate buy when storage or open orders indicate existing exposure.
- CLI single-run behavior for no candidate, rejected candidate, protected buy, and rollback.

Network calls must stay behind fake exchange clients in unit tests. Live integration checks require explicit user action and must not run in the normal test suite.

## Operational Safety

The first live run should be preceded by a dry-run or test-order validation path. API credentials must be kept out of source control and logs. If an API key has been exposed in local output or chat context, it should be revoked and replaced before enabling this feature.
