### Render background worker build and start commands Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Build and start commands for the Render background worker. The start command spawns and guards collect_ticks. ```bash pip install -r requirements.txt ``` ```bash python -m scripts.collector_watchdog ``` -------------------------------- ### Run tick collector with options (PowerShell) Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/operations.md Runs the collector from the project directory. Options include --once for a single poll, --days 1 to stop at next UTC midnight, --out to set output directory, and --gzip for .jsonl.gz rotation. Requires pip install -r requirements.txt first. ```powershell cd "C:\Users\Tiger\Agents\Projects\AI Trading\crypto-spread" pip install -r requirements.txt python -m scripts.collect_ticks # continuous python -m scripts.collect_ticks --once # one poll (smoke) python -m scripts.collect_ticks --days 1 # stop at next UTC midnight python -m scripts.collect_ticks --out E:\ticks # custom output python -m scripts.collect_ticks --gzip # .jsonl.gz rotation ``` -------------------------------- ### Sample Output of Latency Audit Summary Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/rtds-clob-latency-audit.md Shows an example of the terminal output from the live stream monitor, displaying spot prices, UP/DN token prices, CLOB mid prices, and latency (Δt) for each tick. It also includes the empirical latency audit summary with statistics such as total spot price shocks, CLOB reactions, reaction rate, lead reaction times, and spot drift metrics. ```text ================================================================================ CROSS-VENUE STREAM MONITOR: RTDS Spot vs. CLOB Books | Series: btc-up-or-down-5m ================================================================================ [01:47:39] | Spot: $ 79764.00 (+0.00%) | UP: 0.38/0.39 (0.385) | DN: 0.61/0.62 (0.615) | CLOB Mid: 0.385 | Δt: 855ms [01:47:40] | Spot: $ 79764.00 (+0.00%) | UP: 0.38/0.39 (0.385) | DN: 0.61/0.62 (0.615) | CLOB Mid: 0.385 | Δt: 273ms [01:47:41] | Spot: $ 79845.50 (+0.00%) | UP: 0.38/0.39 (0.385) | DN: 0.61/0.62 (0.615) | CLOB Mid: 0.385 | Δt: 190ms [01:47:43] | Spot: $ 79850.00 (+0.11%) | UP: 0.40/0.41 (0.405) | DN: 0.59/0.60 (0.595) | CLOB Mid: 0.405 | Δt: 210ms ================================================================================ EMPIRICAL LATENCY AUDIT SUMMARY (RTDS Spot -> CLOB Book Response) ================================================================================ Total Spot Price Shocks: 1 CLOB Reactions Detected: 1 Reaction Rate: 100.0% Min Lead Reaction Time: 2000.0 ms Median Reaction Time: 2000.0 ms Mean Reaction Time: 2000.0 ms P95 Reaction Time: 2000.0 ms Min Spot Drift: 0.11% Median Spot Drift: 0.11% Mean Spot Drift: 0.11% P95 Spot Drift: 0.11% ================================================================================ ``` -------------------------------- ### Interactive Demo: Before/After Views and Trading Simulation Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issues/148-presentation-unify-execution-entrypoints.html This JavaScript code powers an interactive demo. It defines functions to render the 'before' (old, misleading setup) and 'after' (unified cockpit) views, and includes event handlers for buttons that simulate fake live trading, bankroll alerts, engine alerts, mode switching, and test trades. The code uses DOM manipulation to update the interface and console output. ```javascript const stage = document.getElementById('stageContainer'); const beforeBtn = document.getElementById('viewBeforeBtn'); const afterBtn = document.getElementById('viewAfterBtn'); let currentMode = 'paper'; function renderBefore() { beforeBtn.setAttribute('aria-pressed', 'true'); afterBtn.setAttribute('aria-pressed', 'false'); stage.innerHTML = `

Old Paper Bot Misleading

Had a "--live" switch that did nothing. Operators thought real orders were going through.

Bankroll Scripts Dead Code

10 abandoned subfolders from old research. Confusing to anyone setting up trading.

Live Trader Engine Buried

The actual production engine, but lost in a sea of duplicate and conflicting files.

Select any script above to test what happened in the old setup.
`; } function renderAfter() { beforeBtn.setAttribute('aria-pressed', 'false'); afterBtn.setAttribute('aria-pressed', 'true'); stage.innerHTML = `
Live Trader Engine Sole Official Engine

Unified Trading Cockpit Active

One verified engine handles all market listening, price checks, and order flow cleanly.

System Health 100% Clean

Dead bot directory: Deleted
Bankroll clutter: Deleted
Ambiguity: Zero

Ready in ${currentMode.toUpperCase()} mode. All trades route through the official engine.
`; } window.triggerFakeLive = function() { const out = document.getElementById('consoleOutput'); out.style.color = 'var(--red)'; out.innerHTML = '⚠️ WARNING: You pressed "--live" on the old script! It executed an empty "pass" block — zero orders were ever placed!'; }; window.triggerBankrollAlert = function() { const out = document.getElementById('consoleOutput'); out.style.color = 'var(--amber)'; out.innerHTML = '⚠️ Clutter: 10 stale experimental folders found. Which one has the real logic? Nobody knows.'; }; window.triggerEngineAlert = function() { const out = document.getElementById('consoleOutput'); out.style.color = 'var(--cyan)'; out.innerHTML = 'ℹ️ The real engine was working, but operators had no idea which file to launch.'; }; window.setTradingMode = function(mode) { currentMode = mode; renderAfter(); const out = document.getElementById('consoleOutput'); out.style.color = mode === 'live' ? 'var(--amber)' : 'var(--cyan)'; out.innerHTML = `Mode switched to ${mode.toUpperCase()}. Single engine adjusted with safety controls intact.`; }; window.simulateTrade = function() { const out = document.getElementById('consoleOutput'); if (currentMode === 'paper') { out.style.color = 'var(--cyan)'; out.innerHTML = '✓ PRACTICE TRADE: Logged virtual order cleanly in paper session. Zero real risk.'; } else { out.style.color = 'var(--green)'; out.innerHTML = '✓ LIVE TRADE: Routed securely through official exchange connection with real-time tracking.'; } }; beforeBtn.addEventListener('click', renderBefore); afterBtn.addEventListener('click', renderAfter); // Initial render renderAfter(); ``` -------------------------------- ### Fly.io fallback fly.toml sketch Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Fly.io configuration sketch for the collector watchdog. Requires a Dockerfile (python:3.12-slim, pip install -r requirements.txt, CMD ["python", "-m", "scripts.collector_watchdog"]) not yet in repo. Mounts a tickdata volume at /data and sets COLLECT_OUT=/data. ```toml # fly.toml sketch [processes] app = 'python -m scripts.collector_watchdog' [[restart]] policy = "always" [[mounts]] source = "tickdata" destination = "/data" # + COLLECT_OUT=/data (same redirect convention as Render §1) ``` -------------------------------- ### Backtest result output Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/operations.md Example output from a backtest run, showing overall metrics and per-series breakdown. pair_rate is the fraction of windows where both sides filled and merged; exit_rate is the fraction where the exit rule fired; osc/mono counts oscillating vs monotonic windows. ```text Overall (640 windows): pair_rate 0.0% exit_rate 0.0% total_pnl +0.00c avg_pnl +0.00c/win Per series: btc-up-or-down-5m n=98 pair=0.0% exit=0.0% pnl=+0.00c osc=72 mono=26 ``` -------------------------------- ### Example price_change frame with best_bid and best_ask metadata Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issue-359-socket-divergence-attribution.md This JSON frame shows a price_change event for a new level (0.38 BUY) with explicit best_bid and best_ask metadata. The venue may not emit a size-zero frame for the old level, causing the local book to retain stale levels and compute incorrect best ask. ```json { "price": "0.38", "size": "174", "side": "BUY", "best_bid": "0.42", "best_ask": "0.44" } ``` -------------------------------- ### Run watchdog and collector scripts Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/golden-tick-dataset.md Starts the watchdog and collector processes. The watchdog restarts a dead or wedged collector and logs events to run/watchdog.log. ```powershell python -m scripts.collector_watchdog # detached; restarts a dead or wedged collector python -m scripts.collect_ticks # the collector the watchdog keeps alive ``` -------------------------------- ### Fly.io volume creation and deployment commands Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Commands to create a Fly.io volume, deploy, and view logs. The logs should show the same healthy signs as in section 2. ```bash fly volumes create tickdata --size 10 --region iad fly deploy fly logs # same healthy signs as §2 ``` -------------------------------- ### Run build plan for next task Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issue-workflow.md Executes the single next open task, commits, marks it done in tasks/plan.md, then stops for inspection. Invoked as `/iii-build-plan`. ```text /iii-build-plan ``` -------------------------------- ### Expected output files and manifest contents Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/operations.md Shows the output files produced by the collector: a JSONL file with raw tick data and a manifest.json with line count, series seen, last update timestamp, tape/socket health, and cadence metrics. The manifest includes sampling_interval_s, tick_ms_last/_max, and tick_ms_first. ```text run/ticks/ticks_2026-08-29.jsonl # ~150MB raw, ~20MB gz run/ticks/manifest.json # line count, series seen, last update ts, # tape/socket health, and cadence: # sampling_interval_s real gap between snaps # tick_ms_last/_max round duration # tick_ms_first cold opening round ``` -------------------------------- ### Check sampling interval via Python Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Use this command to verify the sampling interval from the manifest file. It respects the COLLECT_OUT environment variable for locating the data directory. ```shell python -c "import json,os;print(json.load(open(os.path.join(os.environ.get('COLLECT_OUT','run/ticks'),'manifest.json')))['sampling_interval_s'])" ``` -------------------------------- ### Run a sweep on the Backtest tab Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issues/258-presentation-gil-contention.html Open the dashboard at http://127.0.0.1:8802, go to the Backtest tab, and run a sweep on any tick file. This sweep represents the 'testing cook' load that was measured. ```text http://127.0.0.1:8802 → Backtest tab → Run sweep ``` -------------------------------- ### Run backtest sweep via CLI Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/operations.md Run a backtest sweep from the command line. The first command runs with defaults; the second adds flags for offset, queue, and exit; the third writes output to a file. Flags map 1:1 to BacktestParams fields. ```powershell python -m scripts.backtest run/ticks python -m scripts.backtest run/ticks --offset 0.02 --queue 50 --exit btc-up-or-down-5m=0.09 python -m scripts.backtest run/ticks/ticks_2026-08-29.jsonl --out run\backtest\baseline.json ``` -------------------------------- ### Run the GIL contention measurement script Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issues/258-presentation-gil-contention.html Run the Python script to reproduce the three delays: quiet heartbeat, heartbeat under load, and the printed delays with verdict. This is terminal-only because there is no screen for it. ```bash python scripts/measure_gil_contention.py --report docs/measurements/my-run.json ``` -------------------------------- ### Certify golden dataset with verify_tick_data and backtest Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/golden-tick-dataset.md Run the full certification sequence for the golden dataset. Steps 1-2 verify per-day and set-level gates, step 3 rebuilds and checks replay indexes, and step 4 enforces the replay-speed budget (T/W <= 1.0 seconds per window). This sequence is also used for re-certification whenever a day is added or replaced, the policy version changes, or a verify/index tool changes. ```powershell # 1. Every golden day passes its per-day gate (§1.1) # is the actual day filename — golden days may be .jsonl or .jsonl.gz (§1) python -m scripts.verify_tick_data run/ticks/golden/ticks_.jsonl[.gz] # 2. The set as a whole meets the §1.2 bar # (only golden days are in the directory — quarantined files live in run/ticks/quarantine/) python -m scripts.verify_tick_data run/ticks/golden # 3. Fresh replay index for every golden day (index newer than its source file) python -c "from pathlib import Path; from backtest.index import build_index, is_fresh; p=Path('run/ticks/golden/'); build_index(p); assert is_fresh(p, p.with_suffix(p.suffix+'.idx'))" # 4. Replay-speed budget holds (§4): read the printed total replay time T and the window # count W from the output; certification FAILS if T / W > 1.0 seconds per window. python -m scripts.backtest run/ticks/golden --offset 0.02 --queue 50 ``` -------------------------------- ### Run build plan automatically Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issue-workflow.md Executes all tasks in sequence, stopping only on a stuck test or dangerous action. Invoked as `/iii-build-plan auto`. ```text /iii-build-plan auto ``` -------------------------------- ### Post-fix Replay Command and Output Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issue-359-socket-divergence-attribution.md The command to replay the fixture after the fix and its output showing zero divergences, confirming the fix works for the captured event. ```text python scripts/replay_socket_reconciliation.py tests/fixtures/socket_divergence_smoking_gun.json Replaying extracted fixture object from tests\fixtures\socket_divergence_smoking_gun.json (Issue #362) Total WS events: 1 Total divergences recorded: 0 price_change | 1 | 0 | 0 | 0 | N/A | $0.0000 No divergences detected across the dataset (all books agreed within tolerance). ``` -------------------------------- ### Rebuild pristine dataset command Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issues/298-pristine-manifest-delta-findings.md Exact rebuild command with default thresholds, run as a background process logging to run/rebuild_298.log. ```bash python -m scripts.build_pristine_dataset run/ticks --out run/ticks/pristine ``` -------------------------------- ### entry_anchor: resting prices from mid and offset Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/engine-decision-rules.md Determines the price of two opening buy orders when the entry delay elapses)Skip placement until both sides of the book are pricd; the price is recomputed every tick until an order is live. ```plaintext resting_up = clamp(round(mid - offset, 3), 0.01, 0.99) resting_down = clamp(round((1 - mid) - offset, 3), 0.01, 0.99) ``` -------------------------------- ### Pull and verify a day's tick data Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Pull a day's data into run/ticks/ (remote first, local second). Copy the .jsonl.gz file and its .sha256 sidecar, verify with sha256sum -c, then run the verification script. ```bash rclone copyto gdrive:crypto-ticks/ticks_.jsonl.gz run/ticks/ ``` ```bash sha256sum -c ``` ```bash python -m scripts.verify_tick_data run/ticks/ticks_.jsonl.gz ``` -------------------------------- ### Run backtest sweep via Dash API Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/operations.md Run a backtest sweep by hitting the Dash API endpoints. The first URL triggers a backtest with parameters; the second fetches the ticks manifest. ```text http://127.0.0.1:5515/api/backtest?offset=0.02&queue=50&pair_cost=0.99"e_lo=0.10"e_hi=0.90 http://127.0.0.1:5515/api/ticks/manifest ``` -------------------------------- ### Run pytest test suite Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/operations.md Run the full test suite with pytest. The suite includes 49 tests covering classification thresholds, fill rule, queue gating, monotonic exit, replay determinism, gzip roundtrip, per-file cid sidecars, and CLI smoke tests. ```powershell python -m pytest tests/ -v ``` -------------------------------- ### Optional collector environment variables Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Optional environment variables for the collector. COLLECT_OUT is only needed if the disk is mounted elsewhere; COLLECT_EXTRA_ARGS=--gzip is only if disk is tight. ```bash COLLECT_OUT=/data ``` ```bash COLLECT_EXTRA_ARGS=--gzip ``` -------------------------------- ### Run Full Multi-Market Latency Audit Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/rtds-clob-latency-audit.md Executes a comprehensive latency audit across all 10 crypto series (BTC, ETH, BNB, SOL, XRP on 5m and 15m) using the audit_all_markets script. The first command runs a 60-second audit with a threshold of 0.001. The second command audits a subset of tokens (BTC, ETH, SOL) with custom durations and threshold, and quiet per-tick printing. The third command saves audit results to a specific JSON artifact path. ```powershell # Run full empirical latency audit across all 10 crypto series (BTC, ETH, BNB, SOL, XRP on 5m and 15m) python -m scripts.audit_all_markets --duration 60 --threshold 0.001 # Run audit on a specific subset of tokens with custom threshold and quiet per-tick printing python -m scripts.audit_all_markets --tokens BTC ETH SOL --durations 300 --duration 45 --threshold 0.0005 --quiet # Save audit results to a specific JSON artifact path python -m scripts.audit_all_markets --duration 30 -o run/latency_benchmark.json ``` -------------------------------- ### Run shipper manually Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Manual shipper run on the host with the same environment as the service. Uploads finished days to Drive. ```bash python -m scripts.ship_to_drive --out /data ``` -------------------------------- ### Generate day file checksum with sha256sum Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Generates a checksum file for a day's tick data. Run from the service Shell tab (or equivalent) for each closed UTC day. The resulting .sha256 file is downloaded alongside the day file and later used in the golden manifest. ```bash sha256sum run/ticks/ticks_.jsonl* > ticks_.sha256 ``` -------------------------------- ### Run Single-Series Live Inspection Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/rtds-clob-latency-audit.md Provides commands for continuous side-by-side terminal monitoring of a single series (e.g., BTC 5m), running an automated 60-second empirical latency audit, and outputting a machine-readable single-line JSON stream. These commands use the monitor_stream_latency script with different flags to control the monitoring mode, duration, and output format. ```powershell # Continuous side-by-side terminal monitor (BTC 5m) python -m scripts.monitor_stream_latency --series btc-up-or-down-5m # Automated 60-second empirical latency audit python -m scripts.monitor_stream_latency --series btc-up-or-down-5m --audit --duration 60 # Machine-readable single-line JSON stream python -m scripts.monitor_stream_latency --series eth-up-or-down-5m --ticks 10 --json ``` -------------------------------- ### Verify tick data integrity Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Run this script to compare day file SHA-256 hashes against recorded values. It identifies unexplained rewrites and validates data consistency. ```shell python -m scripts.verify_tick_data ``` -------------------------------- ### Verify tick data with scripts.verify_tick_data Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md Verifies a downloaded day file for structural errors. Run locally after downloading the day file and its .sha256. The gate is no structural errors; the recorded sha256 goes into the golden manifest later. ```powershell python -m scripts.verify_tick_data run/ticks/ticks_.jsonl ``` -------------------------------- ### Authenticate rclone with Google Drive Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/collector-hosting-runbook.md One-time Drive authentication on a PC: create a new remote named 'gdrive' with rclone config, then print the token with rclone config show gdrive. Paste the token JSON into the RCLONE_CONFIG_GDRIVE_TOKEN variable in Railway. ```bash rclone config ``` ```bash rclone config show gdrive ``` -------------------------------- ### Verify tick data for a day Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/golden-tick-dataset.md Runs the verification script on a day's tick file. A failing day is quarantined and recorded in the golden manifest. ```powershell python -m scripts.verify_tick_data run/ticks/ticks_.jsonl ``` -------------------------------- ### Subscribe to Binance spot price feed with CryptoPricesSpec Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/live-dashboard-streaming-spec.md Subscribe to the Binance spot price feed via the CryptoPricesSpec topic. The payload contains symbol, timestamp (EpochMilliseconds), and value as a DecimalString. BNB is not supported on this topic and requires REST fallback. ```python from polymarket import AsyncPublicClient from polymarket.streams import CryptoPricesSpec async with AsyncPublicClient() as client: async with await client.subscribe( CryptoPricesSpec( topic="prices.crypto.binance", symbols=["btcusdt", "ethusdt", "solusdt", "xrpusdt"], ) ) as stream: async for event in stream: # event.payload.symbol, event.payload.value, event.payload.timestamp handle_spot_tick(event.payload) ``` -------------------------------- ### Window clock definition Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/engine-decision-rules.md Defines the window length and elapsed time for live and backtest modes. Requires start_ts and end_ts to be present and sane; otherwise the window is not traded. ```python window_length = end_ts - start_ts # from the market's own metadata elapsed = now - start_ts # live elapsed = snapshot_ts - start_ts # backtest ``` -------------------------------- ### Mermaid data flow diagram for dashboard integration Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/live-dashboard-streaming-spec.md Architecture diagram showing data flow from Polymarket RTDS, CLOB WebSocket, and UserSpec streams into the Live Trader Engine, which updates the in-memory state store broadcast to the SPA dashboard. Use to understand the overall integration topology. ```mermaid graph TD RTDS[Polymarket RTDS
prices.crypto.binance] -->|1s Spot Ticks| Engine[Live Trader Engine
strategy/live_trader.py] CLOB[CLOB WebSocket
wss://.../ws/market] -->|Books & BBO| Engine USER[UserSpec Stream
Orders & Trades] -->|Fill Lifecycle| Engine REST[CLOB REST API] -->|Boot / Reconnect Seed| StateStore[In-Memory State Store] Engine --> StateStore StateStore -->|SSE / WS Broadcast| Dash[SPA Dashboard Tab 1
server/osc_dash.py] Engine -->|Trigger Stop Loss| Relayer[Gasless Relayer Order Cancel/Exit] ``` -------------------------------- ### Subscribe to user orders and trades with UserSpec Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/live-dashboard-streaming-spec.md Authenticated subscription to user orders and trades via UserSpec. Requires CLOB API credentials and a Polygon private key. Handles order and trade events to update order and position tables. ```python import os from polymarket import AsyncSecureClient from polymarket.clob_types import ApiCreds from polymarket.streams import UserSpec creds = ApiCreds( api_key=os.environ["CLOB_API_KEY"], api_secret=os.environ["CLOB_API_SECRET"], api_passphrase=os.environ["CLOB_API_PASSPHRASE"], ) async with AsyncSecureClient( key=os.environ["POLYGON_PRIVATE_KEY"], creds=creds, chain_id=137, ) as client: async with await client.subscribe(UserSpec()) as stream: async for event in stream: if event.type == "order": # event.payload.order_event_type: PLACEMENT | UPDATE | CANCELLATION # event.payload.status: LIVE | MATCHED | CANCELED | DELAYED | UNMATCHED update_order_table(event.payload) elif event.type == "trade": # event.payload.status: MATCHED → CONFIRMED update_position_table(event.payload) ``` -------------------------------- ### apply_price_change method in strategy/streaming.py Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issue-359-socket-divergence-attribution.md This Python method updates the local order book for a price change. It removes a price level if size is zero, otherwise updates the size. It then recomputes best_bid and best_ask from the current book keys. The defect is that it does not remove stale levels when the venue omits explicit size-zero frames, leading to incorrect best ask values. ```python def apply_price_change(self, token_id: str, side: str, price: float, size: float) -> None: with self._state_lock: ... side_dict = book["bids"] if side.upper() in ("BUY", "BID") else book["asks"] if size <= 0: side_dict.pop(price, None) else: side_dict[price] = size book["best_bid"] = max(book["bids"].keys()) if book["bids"] else None book["best_ask"] = min(book["asks"].keys()) if book["asks"] else None ``` -------------------------------- ### List open issues with gh issue list Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issue-workflow.md Used by x-workflow-issue to discover up to 50 open issues. The command is `gh issue list --state open --limit 50`. ```bash gh issue list --state open --limit 50 ``` -------------------------------- ### stop_loss: measure excursion from entry price Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/engine-decision-rules.md Computes the price excursion for a filled leg to detect when the maximum excursion seen reaches the stop threshold. Excursions are rounded to six decimal places to avoid floating-point undercut skipping the stop. ```plaintext excursion = round(entry_price - mid, 6) # filled UP leg excursion = round(mid - (1 - entry_price), 6) # filled DOWN leg ``` -------------------------------- ### stop_loss: set stop price from fill Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/engine-decision-rules.md Rests a stop-loss order for a filled leg at the entry price minus the stop threshold, rounded to two decimals and clamped to the tradable range0.01–0.99. The stop is held pre-signed in memory and submitted only when the trigger fires because the venue accepts only GTC/GDT/FAK/FOK orders. ```plaintext stop_price = clamp(round(entry_fill_price - stop_threshold, 2), 0.01, 0.99) ``` -------------------------------- ### View issue comments with gh issue view Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issue-workflow.md Used by ii-plan-issue to read the issue and its comments. The command is `gh issue view --comments`. ```bash gh issue view --comments ``` -------------------------------- ### TypeScript DashboardEnvelope type for versioned events Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/live-dashboard-streaming-spec.md Versioned envelope schema used for all dashboard events broadcast from StateStore to the frontend. Includes version, type, stream_id, sequence number, server_time, and data payload. The frontend uses seq for replay and gap detection. ```typescript type DashboardEnvelope = { version: "1.0"; type: "snapshot" | "delta"; stream_id: "spot" | "books" | "orders" | "positions"; seq: number; server_time: number; data: T; }; ``` -------------------------------- ### Assign issue to self with gh issue edit Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issue-workflow.md Used by ii-plan-issue to claim the issue. The command is `gh issue edit --add-assignee @me`. ```bash gh issue edit --add-assignee @me ``` -------------------------------- ### Breaking Frame JSON Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/issue-359-socket-divergence-attribution.md The exact JSON frame that triggered the divergence, showing a price_change event with in-frame best_bid and best_ask that conflict with the reconstructed book. ```json { "market": "0x5a9d17dd9cc451fa0f75b8eb029fe3b6835a305befaefe367bb2c0a40692e590", "price_changes": [ { "asset_id": "37405155878908629326136933999342727702461662057689801005175075612557641558269", "price": "0.38", "size": "174", "side": "BUY", "best_bid": "0.42", "best_ask": "0.44" } ], "timestamp": "1790744274443", "event_type": "price_change" } ``` -------------------------------- ### PriceUpdatePayload type definition Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/live-dashboard-streaming-spec.md TypeScript type definition for the price update payload structure. The value field is a decimal string, and timestamp is in epoch milliseconds. ```typescript type PriceUpdatePayload = { symbol: string; timestamp: number; // EpochMilliseconds value: string; // DecimalString (e.g. "65420.50") }; ``` -------------------------------- ### RTDS_SYMBOLS constant in strategy/streaming.py Source: https://github.com/ai-degen-69/crypto-spread/blob/master/docs/rtds-clob-latency-audit.md Defines the set of symbols supported by the RTDS streaming feed. BNB is intentionally excluded, which triggers the REST fallback polling loop for BNB markets. ```python RTDS_SYMBOLS = {"btcusdt", "ethusdt", "solusdt", "xrpusdt"} # BNB excluded ```