# Runbook: onboard a Binance spot account Binance is the desk's crypto venue. The connector is a **fenced spot reader first**: it will hold a key that can read and (optionally) spot-trade, and it will refuse a key that can withdraw. The read surface is usable today; trading needs an explicit switch, a notional cap and a symbol allowlist, and has only been proven against a fake and the operator-run testnet walk below. Everything here is HTTP against `https://api.binance.com` (mainnet) or `https://testnet.binance.vision` (spot testnet). The testnet serves **only `/api/*`**; `/sapi/*`, including the key-permission check and deposit/withdrawal history, does not exist there. ## 0. What you need | Thing | Why | |---|---| | A Binance account with spot balances | The read surface reads its balances and fills | | A **new** API key created for this connector | Never reuse a key from another tool | | The key secret, shown once at creation | It is not retrievable later; if lost, create another key | | This host's public IP | For the key's IP whitelist (or a fixed-IP egress host) | | A `.env` the repository ignores | The key must never be committed, pasted into chat, or printed | ## 1. What to do in the Binance UI before the connector will load Do these in order; the connector's own checks are the backstop, not the first line. 1. **Profile → API Management → Create API → System generated.** Give it a name that says "tapebook read-only" or "tapebook spot", never a personal one. 2. **Enable Reading.** Leave **Enable Withdrawals OFF**. This is the refusal the connector enforces: a key with `enableWithdrawals` true cannot be loaded at all. 3. **Enable Spot & Margin Trading only if this sleeve will trade.** The connector refuses to arm trading on a key without it; it never uses the margin half of that permission (spot only). 4. **Restrict access to trusted IPs** and add this host's address. Record the resulting `ipRestrict` state; `describe()` prints it beside the other permissions. 5. **Copy the API key and secret into `.env`** (never into the repository, a shell argument, or a commit): ```bash chmod 600 .env # append, do not echo the values into a terminal that keeps history BINANCE_API_KEY=... BINANCE_API_SECRET=... ``` `BINANCE_API_KEY` and `BINANCE_API_SECRET` are read by `BinanceCredentials.from_env()` / `BinanceBroker.read_only_from_env()`. No CLI command wires the connector yet (GAP-103), so the first run is a short library script. `TAPEBOOK_BINANCE_TRADING=1` is **not** set yet. It is the second switch, after the key permission, and it stays off until the testnet walk passes and the operator has decided to trade. ## 2. What the connector refuses, and why | Situation | Result | |---|---| | Key has `enableWithdrawals=true` | `WithdrawalPermissionRefusedError` on `authenticate()`, naming reading/spot/IP state, before any balance read | | `for_trading` without `TAPEBOOK_BINANCE_TRADING=1` | `TradingNotEnabledError` at construction; zero requests | | `for_trading` on a key without `enableSpotAndMarginTrading` | `TradingPermissionRefusedError` on `authenticate()` | | `place_order` on a read-only object | `TradingNotEnabledError`; zero requests | | Quantity not a whole number of `stepSize` | `FilterViolationError` naming `LOT_SIZE.stepSize` or `MARKET_LOT_SIZE.stepSize` | | Notional below the venue minimum | `FilterViolationError` naming `NOTIONAL.minNotional`/`MIN_NOTIONAL.minNotional` | | Notional above the venue ceiling (live `NOTIONAL.maxNotional`, e.g. 9,000,000 USDT) | `FilterViolationError` naming `NOTIONAL.maxNotional` | | Buy that would breach the account's `MAX_ASSET` | `FilterViolationError` naming `MAX_ASSET.limit`/`marketLimit` (advisory; the venue enforces it) | | Limit price outside the side's band | `FilterViolationError` naming `PERCENT_PRICE_BY_SIDE.*` | | Symbol not in `exchangeInfo` | `UnknownSymbolError`; base/quote are never guessed | | Path under `/fapi`, `/dapi`, `/papi`, `/sapi/v1/margin`, … | `SpotOnlyError` before the request is built | | Timed-out placement | `OrderOutcomeUnknownError`; the intent stays unresolved and the order is **not** resent | ## 3. The five-step testnet walk Use . Sign in with GitHub, generate an HMAC key, and export it in a shell whose environment will not persist to the repository: ```bash export BINANCE_API_KEY='the testnet key' export BINANCE_API_SECRET='the testnet secret' export TAPEBOOK_BINANCE_TRADING=1 # the testnet only; unset again afterwards ``` The testnet key cannot move real funds, and the testnet has no `/sapi` permission endpoint, so the connector's `authenticate()` uses a signed `GET /api/v3/account` there and `describe()` says `TESTNET`. On mainnet the withdrawal refusal is unconditional. Run this from the repository root. It performs the five steps in order and prints statuses only — never a key, a secret, or a signature. ```bash uv run python - <<'PY' import asyncio, os, time from decimal import Decimal import httpx from tapebook.adapters.brokers.binance import ( TESTNET_BASE_URL, BinanceBroker, SpotTimeInForce, TradingPolicy, CryptoOrderRequest, Side, ) from tapebook.domain.money import Currency, Money SYMBOL = "BTCUSDT" CLIENT_ID = f"tb-testnet-{int(time.time())}" async def main() -> None: async with httpx.AsyncClient(timeout=30.0) as http: # STEP 1 — authenticate and read. A bad key or signature fails here. trader = BinanceBroker.for_trading( api_key=os.environ["BINANCE_API_KEY"], api_secret=os.environ["BINANCE_API_SECRET"], client=http, base_url=TESTNET_BASE_URL, policy=TradingPolicy( max_notional_per_order=Money.of_major("100", Currency.USDT), symbols=frozenset({SYMBOL}), ), ) await trader.authenticate() print(trader.describe()) account = await trader.account() print("balances:", [(b.asset, str(b.total)) for b in account.balances]) print("price:", await trader.price(SYMBOL)) # STEP 2 — size from the symbol's own filters; no hardcoded precision. info = (await trader.exchange_info())[SYMBOL] tick = info.price_filter.tick_size step = info.lot_size.step_size market = await trader.price(SYMBOL) limit = (market * Decimal("0.5") // tick) * tick # far below market quantity = (Decimal("40") // limit // step) * step # <= 40 USDT notional print("sized:", quantity, "@", limit, "tick", tick, "step", step) # STEP 3 — one limit order, one POST. Expect NEW (it is away from the market). placed = await trader.place_order( CryptoOrderRequest( client_order_id=CLIENT_ID, symbol=SYMBOL, side=Side.BUY, quantity=quantity, order_type="LIMIT", limit_price=limit, time_in_force=SpotTimeInForce.GTC, ) ) print("placed:", placed.status, placed.venue_status, "orderId", placed.broker_order_id) # STEP 4 — reconcile by client id (GET /api/v3/order?origClientOrderId=…). found = await trader.reconcile(CLIENT_ID, SYMBOL) assert found.order is not None assert found.order.broker_order_id == placed.broker_order_id print("reconciled:", found.order.status, found.order.venue_status, "via", found.source) # STEP 5 — cancel and read it back. Expect CANCELLED. cancelled = await trader.cancel_order(CLIENT_ID, SYMBOL) print("cancelled:", cancelled.status, cancelled.venue_status) asyncio.run(main()) PY ``` What each step proves: 1. The key, the signature construction and the canonical query string are accepted. 2. The order is sized from `LOT_SIZE.stepSize` and `PRICE_FILTER.tickSize`, not from a guess. 3. A placement happens exactly once and the status vocabulary maps onto the desk's. 4. Reconciliation reaches the same order by `origClientOrderId` — the path a timeout relies on. That lookup expires (3 days for a cancelled/no-fill order, 90 days archived spot), so `reconcile()` falls back to `allOrders` over a window and `myTrades?orderId=` for fills. Its `order is None` means "not found in the searched window", never "never placed". 5. Cancellation works by client id, and the order reaches a terminal state. **Client order ids are write-once.** `newClientOrderId` is unique only among *open* orders: Binance may accept the same id again after the previous order fills. The adapter's journal refuses a reused id after a resolution or rejection, so mint a fresh id per order (the script uses a timestamp; add a counter if you loop). Never reuse an id to "retry" — reconcile instead. If step 3 or 4 raises `FilterViolationError`, the message names the filter; correct the size and rerun with a **new** client id. If step 3 times out, do **not** rerun the placement: call `reconcile(CLIENT_ID, SYMBOL)` first (the intent is left `PENDING`), and cancel if it landed. The testnet cannot exercise `deposits()`, `withdrawals()`, `my_filters()`/`MAX_ASSET` or the withdrawal refusal — none of `/sapi/*` exists there. Those are covered by the unit tests with a fake and by the mainnet read below. ## 4. Mainnet: read-only first Unset `TAPEBOOK_BINANCE_TRADING`, then in a shell with the real `.env` loaded: ```bash uv run python - <<'PY' import asyncio import httpx from tapebook.adapters.brokers.binance import BinanceBroker async def main() -> None: async with httpx.AsyncClient(timeout=30.0) as http: broker = BinanceBroker.read_only_from_env(client=http) await broker.authenticate() print(broker.describe()) # withdrawals=False, ipRestrict=True account = await broker.account() print([(b.asset, str(b.total)) for b in account.balances]) print(await broker.price("BTCUSDT")) asyncio.run(main()) PY ``` Check three things before going further: - `describe()` says `withdrawals=False` and `ipRestrict=True` (or that the key has no restriction, which is a deliberate choice, not an accident). - The non-zero balances match what the Binance UI shows. - `account()` returned without `AuthError` / `IPNotWhitelistedError`. The first live order is a separate decision, made after the testnet walk, with `TAPEBOOK_BINANCE_TRADING=1`, a `TradingPolicy` whose cap is above the symbol's `minNotional` and below the amount the operator is willing to lose, and an allowlist of exactly the symbols meant to trade. ## 5. TDS evidence: every fill is a legal record Binance does **not** withhold the 1% Indian TDS. **The operator is the withholding agent** and files Schedule VDA; the exchange only supplies the trade. That makes the per-fill record load-bearing, not a report: - each fill needs **date, asset, quantity, unit price, consideration, side and commission** — for both buys (cost basis) and sells (the TDS-triggering transfer); - it must be captured **when the fill happens**, not reconstructed at year end from a windowed API that will have moved on; - it must be immutable: an evidence row that can be edited is not evidence. The connector exposes that record directly: ```python from pathlib import Path from tapebook.adapters.brokers.binance import VdaFillLog log = VdaFillLog(Path.home() / ".config/tapebook/vda/binance.jsonl") new = await broker.capture_vda_fills("BTCUSDT", log) # reads myTrades, appends new rows once print(f"{len(new)} new VDA fill(s) recorded") ``` `VdaFillRecord.as_json()` carries `symbol`, `base_asset`, `quote_asset`, `trade_id`, `order_id`, `side`, `price`, `quantity`, `consideration`, `commission`, `commission_asset` and `executed_at`. The JSONL log ignores a replay of the same `(symbol, trade_id)` and refuses a changed row under the same key. Keep it outside the repository (the snippet uses `~/.config/tapebook/vda/`), back it up, and never delete or rewrite it. The adapter does **not** compute the 1% or the 30% flat rate: those are tax parameters and the operator's adviser determines the liability. The log is a local file, not the desk database yet (GAP-106), so a cycle must call `capture_vda_fills` after fills. ## 6. Revoke Any one of these ends access: - **Binance UI → API Management → the key → Delete.** This is immediate and permanent. - **Delete the `BINANCE_API_KEY`/`BINANCE_API_SECRET` lines from `.env`** and restart. This only removes the local copy; do the UI deletion as well. - **Rotate** by creating a new key, updating `.env`, restarting, and then deleting the old key. Deleting a key is irreversible; a new key is a new credential, not a recovered one. ## 7. What this does not prove - No live mainnet read or order has been made in this repository. `SUPPORTED` stays `False`, the adapter is not in the conformance registry, and GAP-103 records the closing condition. - The testnet walk proves the wire shape and the order lifecycle, not mainnet liquidity, fees or the exact `PERCENT_PRICE_BY_SIDE` average (the check uses the current ticker as a declared proxy; GAP-105). - The write-ahead intent journal is in memory; a process death between the POST and the response loses the local record (GAP-104). Reconcile by client id before retrying, and do not run two processes with the same trading key. `newClientOrderId` itself is only unique among open orders, so it is not a substitute for the journal. - VDA evidence is a local append-only JSONL file and nothing schedules `capture_vda_fills` (GAP-106). A fill not captured before the file is lost is not recoverable from the venue's windowed reads alone. - The connector is spot-only by path and parameter. Margin, futures, leverage and portfolio margin are refusals, not untested features. ## 8. Verification you can run without a key ```bash uv run pytest tests/adapters/test_binance.py tests/adapters/test_binance_trade.py \ -o addopts="" -q uv run ruff check . && uv run ruff format --check . && uv run mypy ``` No live call is made by any of these, and none needs a Binance account.