> **"I want to build the following trading engine. Don't cod...
Prompt
> **"I want to build the following trading engine. Don't code yet, and don't even talk about coding or the programming language that will be used. Think carefully, deeply, and from first principles about the system. While you are thinking, search for clever, elegant ways of executing this design, and write a very, very long, exhaustive document that will serve as my master architectural blueprint when I eventually sit down to build it.** > > **Focus heavily on:** > 1. **Elegance & Simplicity:** How to achieve maximum reliability with the fewest moving parts. > 2. **Redundancy Without New Failure Modes:** How to add self-healing and safety backups in an elegant way where the backup mechanism itself cannot cause double-execution, state corruption, or new failure modes. > 3. **Adversarial Red-Teaming of My Spec:** Do not just politely agree with my spec. Try to break it. Hunt for subtle state-machine deadlocks, partial-fill traps, race conditions inside the FIFO queue, and edge cases where user commands, fills, `:14` `snail_chaser` repegs, `:23` patrols, and `:37` hourly file updates collide. > 4. **Real-World Binance USD-M Futures Traps:** Factor in real-world Binance USD-M Futures mechanics—such as silent WebSocket staleness, REST vs. stream lag, network timeouts where it is unknown whether an order reached Binance (`-1007`), clock drift (`-1021`), post-only bounces (`-5022`), immediate stop-loss triggers (`-2021`), mark-price vs. book-price divergence during wicks, and how `closePosition: true` stop-losses interact with `reduceOnly` limit orders. > 5. **Crash, Reboot, and Disconnect Recovery:** How the local `.txt` files and deterministic `CID`s should be structured and reconciled on boot so a PC crash, power blink, or internet outage is recovered from cleanly and automatically. > 6. **Single-Operator Ergonomics:** This system will be used by one person and only one person alone, running locally on a single personal machine with `.txt` file persistence and a terminal interface (`viewing_terminal` + `pending_instruction`). Do NOT suggest enterprise bloat (no cloud clusters, no databases, no microservices, no multi-user features). Instead, think deeply about human-machine ergonomics: how the command grammar, `pending_instruction` state, and `viewing_terminal` should work so the operator has zero cognitive friction and can never accidentally corrupt a mission under stress. > > **Write as thoroughly and exhaustively as possible in plain English—walk through concrete scenarios, failure timelines, and design trade-offs in full detail without summarizing or cutting corners."** # Personal Trading Engine Specifications ### (1) Mandatory Mission Parameters, Grammar & `pending_instruction` Workflow - **Mandatory Parameters:** Every mission requires: 1. **Instrument & Side** (`b <symbol>` for Long / Buy, `s <symbol>` for Short / Sell) 2. **Blocked Risk (`$USD`)** (total dollar risk reserved under Section `5.1`) 3. **`stoploss_price`** (`sl_<val>p` or `sl_<val>f`) 4. **`trade_duration`** (converted by the engine into `exit_time = current_time + trade_duration`) - **Optional Parameters:** - **Entry `open_order` Price** (`<val>p` or `<val>f`). If omitted, defaults to **2 ticks away from `c1` (`counterparty_1`) in the allowed maker direction**: - Buying (`b`): $\text{Best\_Ask} - 2 \times \text{tickSize}$ - Selling (`s`): $\text{Best\_Bid} + 2 \times \text{tickSize}$ - **`take_profit_price`** (`tp_<val>p` or `tp_<val>f`) - **Price Grammar (`p` and `f`):** - **`<val>p` (Continuous Logarithmic Percentage Offset):** Computes price via continuous exponential offset ($P \cdot e^{\mp p/100}$) and quantizes to `tickSize`. - **`<val>f` (Fixed Price):** Literal price quantized to `tickSize` (`f` is used instead of `h` because `h` denotes hours). - **Duration Grammar (`d`, `h`, `m`):** - `<D>.<H>.<M>d` $\to$ Days, Hours, Minutes (e.g., `1.2.3d` = 1 day, 2 hours, 3 minutes). - `<H>.<M>h` $\to$ Hours, Minutes (e.g., `5.1h` = 5 hours, 1 minute). - `<M>m` $\to$ Minutes. - **`pending_instruction` Stateful Builder:** - If the operator omits any mandatory parameter (`Blocked Risk`, `stoploss_price`, or `trade_duration`), the engine **never discards** the input. - It holds the partial command as a **`pending_instruction`** (persisted to `.txt`) and prints on the viewing terminal: `update [missing fields]` (e.g., `update [stoploss_price, trade_duration]`). - Once the operator types the missing field(s), the mission launches immediately. --- ### (2) The Two-Order Mission Lifecycle (`ACCUMULATING` $\to$ `UNWINDING`) - **Banned Exchange Templates:** - **NEVER** use Binance's native `TAKE_PROFIT` / `TAKE_PROFIT_MARKET` orders. - **NEVER** use Binance's native trailing/chaser templates. - **Phase 1: `ACCUMULATING` (Mission Launch at `t = 0`):** The engine saves the mission parameters (`exit_time`, `stoploss_price`, optional `take_profit_price`, and `Blocked Risk`) to the `.txt` state file and places **only two orders** on Binance: 1. **`stop_loss` (`STOP_MARKET`):** Placed immediately at `stoploss_price` with `"closePosition": "true"` and `"workingType": "MARK_PRICE"`. Server-side downside protection is active from millisecond zero. 2. **`open_order` (`LIMIT`, `post_only` / `GTX`, `reduceOnly: false`):** Placed for 100% of the mission quantity $Q_{\text{total}}$ at the entry price (clamped per order to `LOT_SIZE.maxQty` if needed). - **The Unwind Tripwire (Transition from `ACCUMULATING` to `UNWINDING`):** The mission transitions from `ACCUMULATING` to `UNWINDING` the moment **either** condition is met: 1. **Time Tripwire:** `current_time >= exit_time`. 2. **Price Tripwire (if `take_profit_price` is set):** Market price reaches or crosses `take_profit_price` ($\ge \text{take\_profit\_price}$ for a Long; $\le \text{take\_profit\_price}$ for a Short). - **Phase 2: `UNWINDING`:** When the Unwind Tripwire triggers: - **Case A (`live_position_size == 0` — Entry Never Filled):** - Send `DELETE /fapi/v1/allOpenOrders` to wipe the unfilled `open_order` and `stop_loss`, and end the mission. - **Case B (`live_position_size > 0` — Position Is Live):** 1. Send `DELETE /fapi/v1/allOpenOrders` to wipe any remaining unfilled `open_order`s. 2. Immediately re-place the `stop_loss` order (`STOP_MARKET`, `closePosition: true`, `workingType: MARK_PRICE`). *(If Binance rejects the re-placed `stop_loss` with `-2021 Order would immediately trigger`, immediately market-close the position under `13.a`.)* 3. Launch **`snail_chaser`** to unwind the position via maker orders. --- ### (3) Serialized FIFO Event Queue, Patrols (`:23`), `snail_chaser` (`:14`), and Hourly Updates (`:37`) - **Single Serialized FIFO Event Queue:** - All background timers (`:14`, `:23`, `:37`), user commands, and stream events push their requests into a single sequential FIFO queue so there are zero race conditions or concurrent conflicts. - **`:23` Patrol (23rd Second of Every Minute):** - Audits all active missions against live Binance state: 1. Checks if the **Unwind Tripwire** (`current_time >= exit_time` or price reached `take_profit_price`) has been crossed, triggering the transition to `UNWINDING` if not already triggered via live stream. 2. Verifies that any live position still has its active `stop_loss` on Binance (re-placing it if missing) and cleans up completed missions (`11.a`). - **`:14` `snail_chaser` (14th Second of Every Minute):** - For every mission in the `UNWINDING` state, places/repegs a `post_only` (`GTX`), `reduce_only` limit order for `min(current_live_position_size, LOT_SIZE.maxQty)` at **2 ticks away from `c1` (`counterparty_1`) in the allowed maker direction**: - **Closing a Long (Selling):** $\text{Best\_Bid} + 2 \times \text{tickSize}$ - **Closing a Short (Buying):** $\text{Best\_Ask} - 2 \times \text{tickSize}$ - **Queue Priority Preservation:** At `:14`, if `snail_chaser` is already resting at the exact target price and `current_live_position_size`, leave it untouched. - **`-5022` Bounce Handling:** If `snail_chaser` bounces on `post_only` (`-5022`), do nothing and wait until the next `:14` cycle. - **Dust Extinguishment:** - **Sub-Notional Dust (`minQty <= size` and notional `< MIN_NOTIONAL`, ~$5.00):** Close immediately via a `reduce_only` `MARKET` order under `(13.b)`. - **Sub-Step Dust (`size < stepSize` or `size < minQty`):** Print warning `small_dust found, close manually using web UI`, sanitize open orders (`11.a`), and close out the local mission. - **`:37` Hourly File Update (37th Minute of Every Hour):** - Never reboot for exchange drift; hot-reload symbol filter and margin bracket `.txt` files every hour at minute `:37`. --- ### (4) Persistence (`.txt` Files) & Client Order ID (`CID`) Architecture - **Local `.txt` Persistence & Crash Recovery:** - Active missions (`MissionID`, symbol, side, phase `ACCUMULATING` / `UNWINDING`, `Blocked Risk`, `stoploss_price`, `take_profit_price`, `exit_time`), `pending_instruction` state, and exchange tables are saved to local `.txt` files and reconciled on boot. - **Deterministic `CID` Schema:** - `S2_<MissionID>_<Role>_<ExitEpoch>_<Seq>` (where `<Role>` is `ENT` for `open_order`, `TRM` for manual trim, `SNL` for `snail_chaser`, `STP` for `stop_loss`, and `DST` for dust market-close). --- ### (5) Mandate to Avoid Liquidation at All Costs - **(5.1) Blocked Risk Sizing & Pre-Trade Reservation:** - The `$USD` input is **Total Blocked Risk ($B$)**: $$B = 1.25 \times \left( \frac{Q_{\text{total}} \times P_{\text{entry}}}{L_{\max}} + Q_{\text{total}} \times |P_{\text{entry}} - P_{\text{sl}}| + \Delta\text{Margin}_{\text{stepdown}} \right)$$ - For a new mission ($\Delta\text{Margin}_{\text{stepdown}} = 0$), the engine solves for $Q_{\text{total}}$: $$Q_{\text{total}} = \text{FLOOR}_{\text{stepSize}}\left( \frac{B / 1.25}{\frac{P_{\text{entry}}}{L_{\max}} + |P_{\text{entry}} - P_{\text{sl}}|} \right)$$ - Reject the trade locally if $B$ exceeds unreserved account equity or if $Q_{\text{total}}$ is below Binance's `MIN_NOTIONAL` (`~$5.00`). - **(5.2) `80%` Margin Ratio Circuit Breaker (Pending Orders Only):** - When account Margin Ratio reaches `80%`, immediately cancel all `pending_orders` that are **NOT** `reduce_only`. - **NEVER** close any live positions for margin ratio reasons; live positions exit strictly via `stoploss`, `take_profit` / `snail_chaser`, or expiry. --- ### (6) – (14) Core Operational Invariants - **(6) Eligible Instruments:** Only USD-M perpetual futures denominated in `USDT`. - **(7) Boot Initialization:** Download and cache margin brackets and symbol filters in `.txt` files on boot. - **(8) Minimum Pledged Margin Mandate:** Always select the highest allowed leverage tier ($L_{\max}$) for the mission's total exposure. - **(9) Blind Account Assumptions & Reversal Guard:** - Assume One-Way mode (`9.a`), Cross-Margin mode (`9.b`—fail fast if Isolated is ever encountered), Classic mode (`9.c`), and Single-Asset mode (`9.d`). - **One-Way Reversal Guard:** Block `b` if a Short mission/position/order is active on that symbol; block `s` if a Long mission/position/order is active. - **(10) Order Flags:** All entry `open_order`s are `post_only` (`GTX`) and `reduceOnly: false`; all closing limit orders (`snail_chaser` / trims) are `post_only` (`GTX`) and `reduceOnly: true`. - **(11) Double Sanitization Protocol:** Send `DELETE /fapi/v1/allOpenOrders` after any position closes (`11.a`) and before starting any `new_position` on an instrument with no active mission (`11.b`). - **(12) Position Size Floor:** Position size can be decreased down to `0`, never below `0`. - **(13) Pure Maker-Only Mandate:** Never pay taker fees, except: - **(13.a)** When `stoploss` (`STOP_MARKET`) is hit. - **(13.b)** To extinguish sub-notional dust (`< MIN_NOTIONAL`, ~$5.00) via a `reduce_only` market order. - **(14) Stop-Loss Parameters:** Always use `"closePosition": "true"` (`14.a`) and `"workingType": "MARK_PRICE"` (`14.b`).
Response not available
Response not available