Skip to content

InertialEvent: Functional Requirements Specification

Cross-Platform Prediction Market Trading System

Version: 1.0
Date: 2026-01-08
Status: Draft for Review


1. Executive Summary

InertialEvent is a high-performance, low-latency trading system designed for cross-platform arbitrage and copy trading across Polymarket and Kalshi prediction markets. The system aims to exceed the capabilities of existing solutions (Polycule, Polymarket-Kalshi-Arbitrage bot) while providing a scalable, monetizable platform.

Key Differentiators

Feature Polycule Poly-Kalshi Arb Bot InertialEvent
Copy Trading ✅ Polymarket only ❌ ✅ Both platforms
Cross-Platform Arbitrage ❌ ✅ ✅ Enhanced
Same-Platform Arbitrage ❌ ✅ ✅
Control Interface Telegram CLI Telegram + Web API
Language Unknown Rust Rust
Multi-tenancy ❌ ❌ ✅
Performance Analytics Basic ❌ ✅ Advanced
Strategy Marketplace Partial ❌ ✅

2. System Overview

graph TB
    subgraph "Control Layer"
        TG[Telegram Bot]
        API[REST/gRPC API]
        WEB[Web Dashboard]
    end

    subgraph "Core Engine - Rust - Data Center"
        MM[Market Monitor]
        AE[Arbitrage Engine]
        CE[Copy Engine]
        OE[Order Executor]
        RM[Risk Manager]
        PT[Position Tracker]
    end

    subgraph "External APIs"
        PM_WS[Polymarket WebSocket]
        PM_CLOB[Polymarket CLOB API]
        PM_GAMMA[Polymarket Gamma API]
        KA_WS[Kalshi WebSocket]
        KA_REST[Kalshi REST API]
        POLY[Polygon Blockchain]
    end

    TG --> API
    WEB --> API
    API --> MM
    API --> CE

    MM --> PM_WS
    MM --> KA_WS
    AE --> MM
    AE --> OE
    CE --> OE
    OE --> PM_CLOB
    OE --> KA_REST
    OE --> POLY
    RM --> AE
    RM --> CE
    PT --> OE
    RM --> CE
    PT --> OE

3. Functional Requirements

3.1 Market Data Ingestion

3.1.1 Polymarket Data Sources

Data Source Type Purpose Latency Target
CLOB WebSocket wss://ws-subscriptions-clob.polymarket.com Orderbook deltas, price updates <10ms
RTDS (Real-Time Data Stream) WebSocket Low-latency prices (market makers) <5ms
Gamma API REST Market discovery, metadata, events <100ms
Data API REST Positions, trade history <200ms
Subgraph GraphQL On-chain state queries <500ms

Required Channels: - orderbook_delta - Real-time orderbook changes - price_change - Best bid/ask updates - trade - Executed trade notifications - order_status - User order updates

3.1.2 Kalshi Data Sources

Data Source Endpoint Purpose Latency Target
WebSocket wss://api.elections.kalshi.com/trade-api/v2/ws Real-time market data <10ms
REST API https://api.elections.kalshi.com/trade-api/v2 Market data, trading <100ms
FIX Protocol Available for Premier/Prime tiers Institutional trading <5ms

WebSocket Channels: - orderbook_delta - Orderbook changes - ticker - Price/volume updates - fill - Trade executions - trade - Market trades

3.1.3 Market Discovery & Matching

[!IMPORTANT] Cross-platform market matching is critical for arbitrage. The system must maintain accurate mapping between Polymarket and Kalshi markets.

Requirements (Phase 1 - Text Similarity): - [x] FR-MD-001: Maintain persistent cache of team/event name mappings across platforms - ADR-017 ✅ src/discovery/storage.rs - [x] FR-MD-002: Implement fuzzy matching as a suggestion engine only (Candidate Proposal) - ADR-017 ✅ src/discovery/matcher.rs (revision proposed - see FR-MD-011-017) - [x] FR-MD-003: Require Human Confirmation for all market mappings (No automated mapping execution) - ADR-017 ✅ src/discovery/approval.rs - [x] FR-MD-004: Auto-discover and match markets expiring within N days (configurable) - ADR-017 ✅ src/discovery/scanner.rs - [x] FR-MD-005: Track market resolution status and settlement dates - ADR-017 ✅ src/discovery/candidate.rs - [x] FR-MD-006: Enumerate Polymarket Gamma API for market discovery - ADR-017 ✅ src/market/discovery_client/polymarket_gamma.rs - [x] FR-MD-007: Enumerate Kalshi /v2/markets API with mve_filter=exclude - ADR-017 ✅ src/market/discovery_client/kalshi_markets.rs - [x] FR-MD-008: Semantic warning detection for settlement differences - ADR-017 ✅ src/discovery/matcher.rs - [x] FR-MD-009: Audit logging for all approval/rejection decisions - ADR-017 ✅ src/discovery/storage.rs - FR-MD-010: Reserved for future Phase 1 enhancements

Requirements (Phase 2 - Fingerprint Matching - Proposed):

[!NOTE] Post-implementation testing revealed text similarity (Jaccard + Levenshtein) is insufficient for cross-platform matching. Real market pairs score 8-9% similarity despite semantic equivalence. See ADR-017 Revision and Cross-Platform Market Matching White Paper.

  • FR-MD-011: Fingerprint extraction from market titles/rules (MarketFingerprint struct) - ADR-017 (Must)
  • FR-MD-012: Entity-based candidate generation with inverted index - ADR-017 (Must)
  • FR-MD-013: Field-weighted similarity scoring (entity 30%, date 25%, threshold 20%, outcome 15%, resolution 10%) - ADR-017 (Must)
  • FR-MD-014: Rule-based named entity recognition for common prediction market entities - ADR-017 (Must)
  • FR-MD-015: ML-based NER integration (spaCy/transformers) - ADR-017 (Could)
  • FR-MD-016: Embedding-based semantic matching for fallback - ADR-017 (Should)
  • FR-MD-017: External service integration (Matchr/Dome API) for validation - ADR-017 (Could)

Requirements (Phase 3 - Embedding-Based Semantic Matching - Proposed):

[!NOTE] Embedding-based matching captures semantic similarity beyond lexical overlap. "Super Bowl" and "Pro Football Championship" have zero word overlap but high embedding similarity.

  • FR-MD-018: Embedding model evaluation and selection (MiniLM, mpnet, OpenAI) - ADR-017 (Should, Medium effort)
  • FR-MD-019: Vector storage integration (sqlite-vec or pgvector) - ADR-017 (Should, Medium effort)
  • FR-MD-020: Batch embedding generation pipeline during market discovery - ADR-017 (Should, Low effort)
  • FR-MD-021: Hybrid scoring algorithm (fingerprint + embedding + text) - ADR-017 (Should, Medium effort)
  • FR-MD-022: Confidence calibration for hybrid scores - ADR-017 (Should, Medium effort)
  • FR-MD-023: Contrastive fine-tuning on approved match pairs - ADR-017 (Could, High effort)

Requirements (Phase 4 - LLM-Based Verification - Proposed):

[!NOTE] LLM verification provides human-level reasoning for complex cases. Used selectively for uncertain matches and deep resolution criteria analysis.

  • FR-MD-024: LLM verification prompt engineering for market comparison - ADR-017 (Should, Medium effort)
  • FR-MD-025: Cost-optimized LLM invocation (Haiku screening, Sonnet escalation) - ADR-017 (Should, Medium effort)
  • FR-MD-026: Automated escalation rules for uncertain matches - ADR-017 (Should, Low effort)
  • FR-MD-027: Resolution criteria deep analysis via LLM - ADR-017 (Could, Medium effort)

Requirements (Phase 5 - Reinforcement Learning from Human Feedback - Proposed):

[!NOTE] Human approval decisions are training data. The system learns from every approval/rejection to improve future matching accuracy.

  • FR-MD-028: Decision logging with complete context (scores, features, reasoning) - ADR-017 (Should, Low effort)
  • FR-MD-029: Training data export pipeline for model retraining - ADR-017 (Should, Low effort)
  • FR-MD-030: Automatic entity alias learning from approved matches - ADR-017 (Should, Medium effort)
  • FR-MD-031: Fingerprint weight optimization via logistic regression on decisions - ADR-017 (Could, Medium effort)
  • FR-MD-032: Continuous evaluation and retraining pipeline (weekly cycle) - ADR-017 (Could, High effort)

3.2 Arbitrage Engine

3.2.1 Arbitrage Opportunity Types

graph LR
    subgraph "Cross-Platform"
        A1[Poly YES + Kalshi NO]
        A2[Kalshi YES + Poly NO]
    end

    subgraph "Same-Platform"
        B1[Poly YES + Poly NO]
        B2[Kalshi YES + Kalshi NO]
    end

    subgraph "Multi-Option"
        C1[Sum of Options < $1.00]
    end

Requirements: - [ ] FR-ARB-001: Detect when YES_ask + NO_ask < $1.00 (accounting for fees) - [ ] FR-ARB-002: Calculate net profit after Kalshi fees: ceil(0.07 × contracts × price × (1-price)) - [ ] FR-ARB-003: Account for Polymarket zero trading fees - [ ] FR-ARB-004: Support minimum profit threshold configuration (e.g., 1.5% minimum) - [ ] FR-ARB-005: Implement position sizing based on orderbook depth - [ ] FR-ARB-006: Support all four arbitrage modes: - poly_yes_kalshi_no - kalshi_yes_poly_no - poly_same_market - kalshi_same_market

3.2.2 Execution Requirements

  • FR-ARB-007: Concurrent order execution across platforms (Best effort)
  • FR-ARB-008: Synchronized View Evaluation (Acknowledging non-atomicity between venues)
  • FR-ARB-009: Maximum execution latency: 50ms from detection to order submission
  • FR-ARB-010: Automatic position reconciliation for partial fills
  • FR-ARB-011: Exposure management for mismatched fills

3.2.3 Execution Safety & Recovery (Legging State Machine)

[!CRITICAL] Since true atomicity is impossible between Polygon and Kalshi, the system must handle "Legging Risks" robustly.

Requirements: - [ ] FR-ARB-012: Implement Saga Pattern for distributed transactions - State: Pending, Leg1_Filled, Leg2_Filled, Failed, Compensating - [ ] FR-ARB-013: Automated Hedge Logic if Leg 2 fails (e.g., limit order chase, market dump, or hold) - [ ] FR-ARB-014: "Un-Happy Path" simulation tests required before mainnet


3.3 Copy Trading Engine

3.3.1 Trader Tracking

Polymarket: - [ ] FR-CT-001: Monitor Polygon blockchain for specified wallet transactions - [ ] FR-CT-002: Detect buy/sell orders via on-chain events or CLOB API - [ ] FR-CT-003: Support tracking multiple wallets concurrently

Kalshi: - [ ] FR-CT-004: Monitor Kalshi trade feed for high-volume traders - [ ] FR-CT-005: Track leaderboard traders (via public profiles)

3.3.2 Copy Modes (Matching/Exceeding Polycule)

Mode Description Polycule InertialEvent
Percentage Copy X% of original trade size ✅ ✅
Fixed Amount Always trade exact $Y amount ✅ ✅
Range Copy X% with min/max bounds ✅ ✅
Mirror Match exact position ratio ❌ ✅ New
Counter Bet opposite of trader ✅ ✅

Requirements: - [ ] FR-CT-006: Implement all 5 copy modes - [ ] FR-CT-007: Configurable per-trader settings - [ ] FR-CT-008: Support cross-platform copy (track on Poly, execute on Kalshi)

3.3.3 Advanced Filters (Matching/Exceeding Polycule)

Filter Description Polycule InertialEvent
Max Days Out Only copy if market expires within X days ✅ ✅
Max Per Market Limit total exposure per market ✅ ✅
Min Liquidity Minimum market liquidity ✅ ✅
Min Volume Minimum market volume ✅ ✅
Max Odds Skip if odds exceed threshold ✅ ✅
Min Trigger Minimum source trade size ✅ ✅
Category Filter Only copy specific categories ❌ ✅ New
Time-of-Day Copy only during specific hours ❌ ✅ New
PnL Pause Pause if daily loss exceeds threshold ❌ ✅ New

Requirements: - [ ] FR-CT-009: Implement all 9 filter types - [ ] FR-CT-010: Support AND/OR filter combinations - [ ] FR-CT-011: Real-time filter evaluation with <100ms latency

3.3.4 Sell Configuration (Matching Polycule)

  • FR-CT-012: Same % as trader (mirror sell ratio)
  • FR-CT-013: Fixed amount sells
  • FR-CT-014: Custom % of current position
  • FR-CT-015: Independent sell disable (hold positions indefinitely)

3.4 Wallet & Position Management

3.4.1 Polygon Wallet Operations

  • FR-WM-001: Secure private key storage (encrypted at rest)
  • FR-WM-002: Multi-wallet support per user
  • FR-WM-003: USDC balance tracking on Polygon
  • FR-WM-004: POL (native token) balance for gas
  • FR-WM-005: CTF (Conditional Token Framework) operations:
  • Split positions (USDC → outcome tokens)
  • Merge positions (outcome tokens → USDC)
  • Redeem resolved positions

3.4.2 Kalshi Account Operations

  • FR-WM-006: API key authentication with RSA-PSS signing
  • FR-WM-007: Balance and position synchronization
  • FR-WM-008: Order history tracking

3.4.3 Position Tracking

  • FR-WM-009: Real-time position aggregation across platforms
  • FR-WM-010: P&L calculation (realized and unrealized)
  • FR-WM-011: Historical performance metrics
  • FR-WM-012: Portfolio breakdown by market/category
  • FR-WM-013: Liquidity Rebalancing Alerts (Notification when venue balance is low/high)

3.5 Risk Management

3.5.1 Circuit Breaker System

[!CAUTION] Circuit breakers are critical for preventing catastrophic losses. These must be battle-tested before production.

Parameter Description Default
max_position_per_market Maximum $ exposure per market $100
max_total_position Maximum total open position value $500
max_daily_loss Daily loss limit (triggers halt) $5,000
max_consecutive_errors Error count before halt 5
cooldown_seconds Pause duration after trigger 60

Requirements: - [ ] FR-RM-001: Implement all circuit breaker parameters - [ ] FR-RM-002: Configurable per-user and per-strategy - [ ] FR-RM-003: Automatic notifications on trigger - [ ] FR-RM-004: Manual override capability for admins

3.5.2 Order Validation

  • FR-RM-005: Pre-trade balance validation
  • FR-RM-006: Gas fee estimation before Polygon transactions
  • FR-RM-007: Slippage protection with configurable tolerance
  • FR-RM-008: Rate limit compliance for both platforms
  • FR-RM-009: Compliance Filter (Check order patterns against ToS/Wash Trading rules)

3.6 Control Interface

3.6.1 Telegram Bot Commands

Command Description Priority
/start Initialize account, display wallet P1
/home Dashboard with balances, quick actions P1
/wallet Detailed wallet view, withdraw, export P1
/fund Funding instructions, bridge integration P1
/positions All open positions with P&L P1
/trending Trending markets by category P2
/search <query> Search markets P2
/arb status Arbitrage engine status P1
/arb start/stop Control arbitrage engine P1
/copy list List active copy trades P1
/copy add <wallet> Add new copy trade P1
/copy remove <id> Remove copy trade P1
/copy pause/resume <id> Toggle copy trade P1
/stats Performance statistics P2
/settings User preferences P2

3.6.2 REST/gRPC API

  • FR-API-001: Full programmatic access to all features
  • FR-API-002: JWT authentication with refresh tokens
  • FR-API-003: WebSocket stream for real-time updates
  • FR-API-004: Rate limiting per API key
  • FR-API-005: OpenAPI specification for clients

3.7 Multi-Tenancy & Monetization

3.7.1 User Management

  • FR-MT-001: User registration and onboarding
  • FR-MT-002: Subscription tiers (Free, Pro, Enterprise)
  • FR-MT-003: Usage metering and billing integration
  • FR-MT-004: Referral/affiliate system

3.7.2 Strategy Marketplace

  • FR-MT-005: Users can share copy trading configurations
  • FR-MT-006: Performance tracking for shared strategies
  • FR-MT-007: Revenue sharing for strategy creators
  • FR-MT-008: Strategy ratings and reviews

4. API & Integration Requirements

4.1 Polymarket Integration

Component Implementation
CLOB Client Rust rewrite of py-clob-client (order submission)
WebSocket tokio-tungstenite for CLOB subscriptions
Signing EIP-712 typed data signing via ethers-rs
Chain Interaction ethers-rs for Polygon transactions

Authentication: - Ethereum wallet private key - API key/secret for CLOB (if using relayer) - Builder program credentials (optional gasless transactions)

4.2 Kalshi Integration

Component Implementation
REST Client reqwest with RSA-PSS signing
WebSocket tokio-tungstenite for orderbook/ticker
SDK Wrap official Python SDK patterns in Rust

Authentication: - API Key ID - RSA Private Key (PEM file)

Rate Limits: | Tier | Requirements | Limits | |------|--------------|--------| | Basic | Signup | Standard | | Advanced | Application + knowledge check | Higher | | Premier | 3.75% exchange volume | Higher + batch orders | | Prime | 7.5% exchange volume | Highest |

4.3 External Services

Service Purpose
deBridge Solana → Polygon bridging
Alchemy/QuickNode Polygon RPC provider
Telegram API Bot hosting
Redis Session storage, pub/sub
PostgreSQL Persistent storage

5. Non-Functional Requirements

5.1 Performance

Metric Target
Arbitrage detection latency <1ms
Order submission latency <50ms
WebSocket message processing <100μs
Concurrent market tracking 10,000+
Trade throughput 1,000+ orders/second

5.2 Reliability

  • 99.9% uptime SLA
  • Automatic reconnection for WebSocket connections
  • Graceful degradation on API failures
  • Data persistence for crash recovery

5.3 Security

  • NFR-SEC-001: Encrypted private key storage (AES-256-GCM)
  • NFR-SEC-002: No private keys in logs
  • NFR-SEC-003: TLS 1.3 for all connections
  • NFR-SEC-004: Audit logging for all trades
  • NFR-SEC-005: 2FA for Telegram bot (optional)
  • NFR-SEC-006: Dry Run Mode (Safe verification of signing/logic without broadcast) - ADR-002
  • NFR-SEC-007: Connectivity Check (Pre-flight verification of API access) - ADR-001
  • NFR-SEC-008: Encrypt credentials with AES-256-GCM, HSM optional - ADR-009

5.4 Architecture

  • NFR-ARCH-001: Core engine must be implemented in Rust - ADR-004 (~95% complete)
  • NFR-ARCH-002: Use actor model with message passing for concurrency - ADR-005 (~90% complete)
  • NFR-ARCH-003: Orderbook cache must be lock-free for reads - ADR-006 (arc_swap + dashmap)
  • NFR-ARCH-004: Implement saga pattern for distributed transactions - ADR-007 (~95% complete)
  • NFR-ARCH-005: Support Telegram and REST/gRPC control interfaces - ADR-008
  • NFR-ARCH-006: Deploy core in AWS us-east-1 for low latency - ADR-010
  • NFR-ARCH-007: Support multi-tenant with pod-based isolation - ADR-011

5.5 Performance Monitoring

[!IMPORTANT] Performance monitoring must not degrade the hot path. All instrumentation on tick-to-trade must minimize allocation and be non-blocking.

Monitoring (ADR-012):

  • NFR-PERF-001: Tick-to-trade latency measurement with TSC precision (RDTSCP + LFENCE) - ADR-012 ✅ src/metrics/timing.rs
  • NFR-PERF-002: HDR histogram capture for latency distributions (p50, p99, p99.99) with double-buffering - ADR-012 ✅ src/metrics/histogram.rs
  • NFR-PERF-003: Non-blocking tracing subscriber for warm path logging - ADR-012 (Future: Phase 2)
  • NFR-PERF-004: Prometheus metrics export for KPIs - ADR-012 (Future: Phase 3)
  • NFR-PERF-005: Alerting on latency threshold breaches (p99 > 2ms) - ADR-012 (Future: Phase 4)
  • NFR-PERF-006: Platform-portable timing (x86_64 TSC, ARM CNTVCT_EL0, fallback) - ADR-012 ✅ src/metrics/timing.rs

Optimization (ADR-013):

  • NFR-OPT-001: Thread affinity with core pinning for trading threads - ADR-013 ✅ src/runtime/affinity.rs
  • NFR-OPT-002: Adaptive busy-polling with configurable spin/yield backoff - ADR-013 ✅ src/runtime/polling.rs
  • NFR-OPT-003: Fixed-size object pools for order allocation - ADR-013 ✅ src/runtime/pool.rs
  • NFR-OPT-004: Cache-line alignment to prevent false sharing - ADR-013 ✅ src/runtime/cache_align.rs
  • NFR-OPT-005: Low-latency channels (crossbeam) for inter-thread communication - ADR-013 ✅ src/runtime/polling.rs

KPI Targets:

KPI Target Alert Threshold
Tick-to-Trade p50 < 100 μs > 500 μs
Tick-to-Trade p99 < 500 μs > 2 ms
Tick-to-Trade p99.99 < 2 ms > 10 ms
Event Loop Lag < 1 ms > 5 ms
Lock Contention Rate < 0.1% > 1%

5.6 Observability

[!NOTE] Observability requirements are tracked separately from hot-path performance monitoring. These components run on background threads and do not affect trading latency.

  • NFR-OBS-001: Prometheus metrics endpoint for KPI export - ADR-012 (Future: Phase 3)
  • NFR-OBS-002: Grafana dashboards for real-time monitoring - ADR-012 (Future: Phase 3)
  • NFR-OBS-003: Structured JSON logging via tracing crate - ADR-012 (Future: Phase 2)
  • NFR-OBS-004: Distributed tracing with OpenTelemetry - (Future)
  • NFR-OBS-005: Alert manager integration for threshold breaches - ADR-012 (Future: Phase 4)

5.7 Paper Trading & Backtesting

[!NOTE] Paper trading and backtesting capabilities enable strategy evaluation without financial risk. These requirements cover simulation infrastructure for risk-free strategy testing.

Requirement ID Numbering: IDs are grouped by category with gaps for future expansion: - 001-009: Simulation core - 010-019: Position tracking - 020-029: Historical data - 030-039: Backtesting - 040-049: Analytics

Simulation (ADR-014):

ID Requirement Priority Status
NFR-SIM-001 SimulatedExchangeClient implements ExchangeClient trait Must Implemented
NFR-SIM-002 Fill simulation with configurable latency injection Must Implemented
NFR-SIM-003 Partial fill support for large orders Should Implemented
NFR-SIM-004 Order book state tracking for realistic fills Should Implemented
NFR-SIM-005 Queue position modeling for HFT simulation (Level 3) Could Deferred
NFR-SIM-006 Fee simulation (Kalshi: 7% formula, Polymarket: 0%) Should Implemented

Position Tracking (ADR-014):

ID Requirement Priority Status
NFR-SIM-010 Track paper positions per market/side Must Implemented
NFR-SIM-011 Real-time PnL calculation (realized/unrealized) Must Implemented
NFR-SIM-012 Position limits enforcement for paper trading Should Implemented
NFR-SIM-013 Multi-market portfolio view aggregation Should Implemented

Historical Data (ADR-014):

ID Requirement Priority Status
NFR-SIM-020 Store trade history in SQLite database Must Implemented
NFR-SIM-021 Record live market data for replay Must Implemented
NFR-SIM-022 Time-range queries for backtesting Must Implemented
NFR-SIM-023 Optional Parquet export for external analysis Could Deferred

Backtesting (ADR-014):

ID Requirement Priority Status
NFR-SIM-030 Replay historical data at configurable speed Must Implemented
NFR-SIM-031 Deterministic replay (same data = same results) Must Implemented
NFR-SIM-032 Clock abstraction for simulated vs real time Must Implemented
NFR-SIM-033 Event ordering preservation during replay Must Implemented

Analytics (ADR-014):

ID Requirement Priority Status
NFR-SIM-040 Calculate Sharpe ratio (annualized) Must Implemented
NFR-SIM-041 Calculate maximum drawdown Must Implemented
NFR-SIM-042 Trade-level statistics (win rate, profit factor) Must Implemented
NFR-SIM-043 Generate performance reports Should Deferred
NFR-SIM-044 Compare paper vs live performance metrics Could Deferred

Simulation Fidelity Levels:

Level Name Use Case Fill Logic
1 Basic Quick validation Instant fill at mid-price
2 Realistic Paper trading Order book crossing, partial fills
3 HFT Latency analysis Queue position, market impact

5.8 Testing & Development Infrastructure

[!NOTE] Testing infrastructure enables safe development and validation without risking production credentials or capital. These requirements cover exchange environment switching and development tooling.

Exchange Environment Support:

ID Requirement Priority Status
NFR-TEST-001 Kalshi demo environment support (--kalshi-demo flag) Must Implemented
NFR-TEST-002 Separate credential namespacing for demo environments Must Implemented
NFR-TEST-003 Environment-aware URL configuration (API, WebSocket) Must Implemented
NFR-TEST-004 Safe default to production environment Must Implemented

Implementation Details:

  • KalshiEnvironment enum: Production and Demo variants with URL configuration
  • CLI flag: --kalshi-demo switches to demo environment
  • Demo credentials: KALSHI_DEMO_KEY_ID, KALSHI_DEMO_PRIVATE_KEY
  • Production credentials: KALSHI_KEY_ID, KALSHI_PRIVATE_KEY

Related: - GitHub Issue #39 - Kalshi Demo Docs: https://docs.kalshi.com/getting_started/demo_env

5.9 Discovery Operations

[!NOTE] Discovery operations requirements cover CI/CD, testing, monitoring, and security for the market discovery feature (ADR-017). These are non-functional requirements that support production deployment of the discovery system.

CI/CD & Testing:

ID Requirement Priority Status
NFR-DISC-001 Discovery CI job with feature flag (--features discovery) Must Proposed
NFR-DISC-002 Mock API responses for integration testing (wiremock) Must Proposed

Monitoring & Observability:

ID Requirement Priority Status
NFR-DISC-003 Rate limit compliance monitoring (CloudWatch metrics) Should Proposed
NFR-DISC-004 Discovery-specific metrics (scan duration, candidates, approvals) Should Proposed

Security & Compliance:

ID Requirement Priority Status
NFR-DISC-005 Candidate approval audit trail (JSONL format, 7-year retention) Must Implemented
NFR-DISC-006 API key rotation support via AWS Secrets Manager Should Proposed

Scaling & Cost:

ID Requirement Priority Status
NFR-DISC-007 Embedding infrastructure scaling (pgvector, batch processing) Could Proposed
NFR-DISC-008 LLM cost monitoring and budget controls ($50/day default) Should Proposed

Implementation Status: - NFR-DISC-001: Requires GitHub Actions workflow update - NFR-DISC-002: wiremock dependency already added, tests pending - NFR-DISC-005: Implemented in src/discovery/storage.rs (audit_log table)

Related: - ADR-017: Automated Market Discovery - Cross-Platform Market Matching White Paper


6. Deployment Architecture

graph TB
    subgraph "User Layer"
        U1[Telegram Users]
        U2[API Clients]
        U3[Web Dashboard]
    end

    subgraph "Edge - Cloudflare/AWS CloudFront"
        CDN[CDN + WAF]
    end

    subgraph "Data Center - Low Latency Region"
        subgraph "Control Plane"
            TG_BOT[Telegram Bot Service]
            API_GW[API Gateway]
            WEB_SVC[Web Service]
        end

        subgraph "Trading Core"
            TRADING[Trading Engine - Rust]
        end

        subgraph "Data Layer"
            PG[(PostgreSQL)]
            REDIS[(Redis)]
        end
    end

    subgraph "External"
        POLY_API[Polymarket APIs]
        KALSHI_API[Kalshi APIs]
        POLYGON[Polygon RPC]
    end

    U1 --> CDN
    U2 --> CDN
    U3 --> CDN
    CDN --> TG_BOT
    CDN --> API_GW
    CDN --> WEB_SVC

    TG_BOT --> TRADING
    API_GW --> TRADING
    WEB_SVC --> TRADING

    TRADING --> PG
    TRADING --> REDIS
    TRADING --> POLY_API
    TRADING --> KALSHI_API
    TRADING --> POLYGON
Service Provider Region Rationale
AWS us-east-1 (N. Virginia) Near Kalshi (NYC-based), low latency to Polygon RPC
Hetzner Ashburn or NYC Cost-effective, low-latency co-location
Fly.io iad (Washington DC) Edge compute, closer to financial services

7. Success Metrics

Metric Target
Arbitrage opportunities captured >90% of detected opportunities
Copy trade execution latency <2 seconds from source detection
User retention (30-day) >60%
Monthly recurring revenue growth 15% MoM
System availability >99.9%

8. Appendix

A. Reference Implementation Analysis

Polycule Features Captured

✅ All trading commands (/home, /wallet, /positions, etc.) ✅ Copy trading with all modes (percentage, fixed, range, counter) ✅ All advanced filters (7/7) ✅ Sell configuration options (3/3)
✅ Bridging support (Solana → Polygon) ✅ Strategy sharing

Polymarket-Kalshi-Arbitrage Bot Features Captured

✅ All arbitrage types (4/4) ✅ Rust implementation ✅ Lock-free orderbook cache ✅ SIMD-accelerated detection ✅ Circuit breaker protection ✅ Concurrent order execution ✅ Position tracking and P&L

New Features (Not in Reference Implementations)

🆕 Cross-platform copy trading 🆕 Kalshi copy trading 🆕 Multi-tenancy 🆕 Strategy marketplace 🆕 Category and time-of-day filters 🆕 PnL pause feature 🆕 Web dashboard 🆕 REST/gRPC API 🆕 Mirror copy mode

B. Glossary

Term Definition
CLOB Central Limit Order Book
CTF Conditional Token Framework (Gnosis)
RTDS Real-Time Data Stream
SIMD Single Instruction, Multiple Data
POL Polygon native token (formerly MATIC)