# Binance Spot Testnet Trading System Design

## Goal

Build a Python CLI quantitative trading system for Binance Spot Testnet. The first version must safely complete the loop from market data to strategy signal, risk check, order submission, and persistent audit records.

## Scope

The system supports Binance Spot Testnet only. It includes a dry-run mode and a Testnet live mode. Real-money trading, futures trading, grid trading, arbitrage, portfolio optimization, and a web dashboard are out of scope for the first version.

## External APIs

The exchange integration follows Binance official Spot API documentation:

- REST API for account, exchange metadata, and order submission.
- WebSocket Streams for market data.
- WebSocket API or REST-backed account checks where needed for Testnet compatibility.

Production base URLs are not used by default. Testnet URLs are configured explicitly and the CLI refuses to run live trading without Testnet credentials.

## Architecture

The system is organized as a small Python package with clear module boundaries:

- `config`: load environment variables and optional YAML settings into typed settings objects.
- `exchange`: sign REST requests, call Binance Spot Testnet endpoints, normalize exchange responses.
- `market_data`: stream or load market data and convert it into internal candle/ticker objects.
- `strategy`: convert market state into `BUY`, `SELL`, or `HOLD` signals.
- `risk`: validate signals against account, symbol, and system limits.
- `execution`: turn approved signals into dry-run records or Testnet market orders.
- `storage`: persist signals, order requests, order results, and runtime events in SQLite.
- `cli`: expose `backtest`, `trade`, `account`, and `orders` commands.

Each module communicates through typed data models rather than raw dictionaries where practical.

## Data Flow

In live Testnet mode, the CLI loads settings, initializes storage, fetches exchange metadata for the configured symbol, and opens a market data stream. New candles are passed to the strategy. The strategy emits a signal with side, symbol, confidence, and reason. The risk engine either rejects the signal with a reason or returns an approved order intent. The execution engine submits a market order to Binance Spot Testnet or records a dry-run order. Storage writes every signal, rejection, order request, and order result.

In backtest mode, historical candles are read from local CSV input. The same strategy and risk interfaces are used, but execution is simulated locally.

## Strategy

The first strategy is a simple moving average crossover strategy:

- Calculate a fast SMA and a slow SMA from candle closes.
- Emit `BUY` when the fast SMA crosses above the slow SMA.
- Emit `SELL` when the fast SMA crosses below the slow SMA.
- Emit `HOLD` when there is no crossover or not enough candle history.

The strategy is deliberately simple so the first version validates the system architecture rather than promising trading performance.

## Risk Controls

The first version includes these checks:

- Reject trading when mode is not explicitly `dry_run` or `testnet_live`.
- Reject unsupported symbols.
- Reject orders below symbol minimum notional where exchange metadata provides it.
- Reject orders above configured max quote amount per trade.
- Reject new trades during a configured cooldown window.
- Reject buy orders when quote balance is insufficient.
- Reject sell orders when base balance is insufficient.
- Reject duplicate same-side signals when configured to avoid repeated entries.

Risk decisions are persisted with the original signal and rejection reason.

## Execution

Only market orders are supported in the first version. Dry-run mode writes a simulated order result without sending a network request. Testnet live mode signs and sends a Binance Spot Testnet REST order request. All order requests include a client order id generated by the system for traceability.

## Configuration

Configuration comes from environment variables plus an optional YAML file. Required Testnet credentials are:

- `BINANCE_API_KEY`
- `BINANCE_API_SECRET`

Key runtime settings include:

- mode: `dry_run` or `testnet_live`
- symbol, such as `BTCUSDT`
- quote amount per trade
- max quote amount per trade
- fast and slow SMA windows
- cooldown seconds
- SQLite database path
- log level

Credentials are never written to logs or SQLite.

## Storage

SQLite stores:

- strategy signals
- risk decisions
- order intents
- exchange order responses
- account snapshots requested through the CLI
- runtime events

Tables are append-oriented so the user can audit what happened during a run.

## Error Handling

Network failures, Binance error responses, invalid signatures, insufficient balances, and malformed settings are surfaced as explicit errors with safe messages. API secrets are redacted. Live trading loops log recoverable market data errors and continue when possible. Order submission errors are persisted as failed order results.

## Testing

Implementation follows test-driven development. Unit tests cover:

- settings loading and validation
- Binance request signing
- SMA crossover signal generation
- risk approval and rejection cases
- dry-run execution behavior
- storage writes and reads
- CLI command wiring for non-network paths

Network calls are isolated behind exchange interfaces and replaced with fake clients in unit tests. Testnet connectivity is verified through explicit integration CLI commands rather than normal unit tests.

## Non-Goals

The first version does not include real-money production trading, futures, margin, leverage, advanced order types, strategy optimization, distributed workers, alerting integrations, or a web dashboard.

