Building an Automated Quantitative Trading Stack: A Practical Guide for China Markets

    This article breaks down how to build a scriptable, automated quantitative trading infrastructure tailored to the Chinese market. Covering four core layers—data, computation, execution, and operations—it explains the architecture, key engineering decisions, and the critical differences between backtesting and live trading. Readers will learn how to handle data governance, real-time market data ingestion, order execution state machines, risk controls, and deployment on low-spec cloud servers, along with a step-by-step roadmap from simulation to scaled live trading.

    1. The Problem: A Working Strategy Is Not a Usable Strategy

    When searching open-source communities for quantitative trading implementations in the Chinese market, developers often run into a few recurring frustrations: many projects are abandoned and left unmaintained, with outdated dependencies; documentation is incomplete and examples cannot be reproduced; and market data, backtesting, and trading modules often come from different sources with incompatible interfaces, making integration cost far higher than rewriting from scratch. As a result, developers end up stuck in a cycle of searching, cloning, trying, and giving up, only to stitch the components back together themselves.

    More importantly, there is an order-of-magnitude gap between “backtest passing” and “live-trading ready.” Backtesting relies on historical data and matching assumptions, while live trading must contend with real-world constraints: real-time feed disconnects, partial fills, rejected cancellations, trading halts and resumptions, and rate limits. If the toolchain lacks design in data consistency, execution state management, pre-trade risk controls, and monitoring alerts, a strategy’s live performance will often diverge severely from its backtest results.

    Therefore, this article does not discuss specific strategy returns but focuses on a general engineering problem: how to use a scripting language to build a layered, replaceable, and observable quantitative trading infrastructure for the Chinese market. Data sources, trading channels, and cloud services are described here in terms of capability categories; actual choices should be evaluated according to your own needs and compliance requirements.

    2. Overall Architecture: Four Layers and One Core Principle

    A complete quantitative trading toolchain can be divided into four layers, each with a single responsibility and clear boundaries:

    Layer Core Responsibility Key Output
    Data Acquiring, cleaning, and storing market and reference data Time-correct, reproducible market and reference data
    Computation & Signal Backtesting, factor and stock-selection calculations Strategy signals validated out-of-sample
    Execution Submitting, cancelling, and processing order fills Risk-constrained, idempotently replayable order flow
    Operations & Monitoring Deployment, reconciliation, monitoring and alerting Availability assurance and traceability

    The core principle is dependency inversion: strategies are coded only against custom market-data, trading, and data interfaces, with all external dependencies (data sources, broker channels, databases) connected through adapter layers. This way, when a data source is discontinued or a channel changes, only the adapter implementation needs to be replaced while strategy code stays unchanged. It also makes it easy to validate in a simulation environment first, then switch to a live channel.

    3. Data Layer: Latency Tiers and Data Governance

    3.1 Matching Data Sources by Latency Tier

    For the Chinese market, common data-acquisition methods fall into roughly three categories:

    • Delayed market data: free or low-cost, with a fixed push delay, suitable for daily and minute-level stock selection and post-hoc research;
    • Real-time data services: paid subscriptions providing real-time snapshots, tick-by-tick orders and trades, and even order-book depth, suitable for intraday signals;
    • Data feeds bundled with a trading channel: available after opening an account, offering data for that channel at lower cost, though coverage and stability depend on the channel itself.

    The selection criterion is not “is it real-time,” but whether the strategy’s decision frequency can tolerate the delay. Minute-level rotation strategies typically cannot rely on significantly delayed data, while sub-second high-frequency signals demand extremely low latency, low packet loss, and precise clock synchronization—and are subject to regulatory constraints on programmatic trading.

    3.2 Data Governance Details

    Raw data cannot go directly into strategies; at minimum, the following must be handled:

    • Trading calendar and sessions: open, lunch break, close, call auction sessions; day and night sessions for futures;
    • Halts and resumptions: no trades occur during halts, and price gaps are extreme on the first day of resumption;
    • Adjustment method: whether price series are forward-adjusted directly affects moving-average and momentum indicators; a consistent basis must be applied across the full sample;
    • Security mapping: a unified dimension table for codes, boards, listing status, and delisting handling;
    • Survivorship bias: if the backtest universe includes only currently listed instruments, returns are systematically overstated.

    3.3 Storage and Updates

    High-frequency small writes of market data are best kept in a time-series database; reference data in a relational database; archives and batch backtest data in object storage. Incremental updates must define idempotency keys (e.g., “date + code + timestamp”) to avoid duplicate records on re-runs.

    4. Computation & Signal Layer: Backtesting, Screening, and Composite Conditions

    4.1 The Division of Labor Between Two Types of Backtest Engines

    Vectorized backtesting expresses strategies as batch array operations. It is extremely fast and suited to large-scale factor screening. Event-driven backtesting drives a “bar arrives → signal generated → order submitted → matching → fill” loop in chronological order. It is closer to live trading and suited to final validation before going live. The two should cross-validate each other rather than replace one another.

    A skeleton of an event-driven backtest engine is shown below (illustrative code, not a real interface):

    1. class BacktestEngine:
    2. def run(self, instruments, start, end):
    3. for bar in data_source.iter_bars(instruments, start, end):
    4. if not calendar.is_trading(bar.ts):
    5. continue
    6. signals = strategy.on_bar(bar) # generate signals
    7. for order in risk.check(signals, self.account):
    8. trade = self.matcher.match(order, bar) # matching includes slippage and constraints
    9. self.account.update(trade)
    10. broker.update(trade) # fill state machine
    11. return self.account.performance()

    4.2 Matching Assumptions Must Be Explicitly Modeled

    The specifics of the Chinese market must be reflected explicitly in backtests: buys are hard to fill and sells hard to fill when prices hit limit-up or limit-down; stocks bought today can only be sold the next day; call-auction and continuous-auction matching rules differ; futures are constrained by margin, position limits, and forced-liquidation rules; and costs include commission, stamp duty, transfer fees, and market impact. These assumptions should be configurable parameters, and parameter sensitivity analysis should be used to check the robustness of conclusions.

    4.3 Implementing Composite-Condition Screening

    Composite conditions such as “moving average turning up + volume ratio surging + consecutive net inflows” should not be implemented by scraping web pages instrument by instrument. Instead, they should be implemented in three layers:

    1. Data layer: compute standardized factor tables for volume ratio, moving-average slope, fund-flow direction, etc., and write them to the time-series database;
    2. Query layer: express multi-condition combinations with declarative queries, for example:
      1. SELECT code FROM factor_daily
      2. WHERE trade_date = :d AND ma20_slope > 0
      3. AND volume_ratio > 3 AND flow_dir_cnt >= 3;
    3. Service layer: during the trading day, perform only incremental re-checks on the screening results, avoiding full-market recomputation.

    5. Real-Time Market Data: Choosing Between WebSocket and HTTP Polling

    For second-level signals, WebSocket-based server push outperforms scheduled HTTP polling in timeliness, connection overhead, and server load; polling is simpler to implement and suited to low-frequency scenarios. When using push, the engineering focus is not on “getting connected” but on long-term connection stability:

    • Authentication and sessions: tokens usually have a validity period, requiring automatic renewal and re-authentication after reconnection;
    • Subscription management: changes to the subscription list (new instruments at market open, removals at delisting) need incremental updates;
    • Heartbeat and reconnection: set heartbeat timeout detection and exponential-backoff reconnection to avoid thundering-herd reconnects;
    • Message integrity: verify sequence-number and timestamp continuity; backfill gaps after disconnection;
    • Framing: correctly split the byte stream by length or delimiter, with unified deserialization;
    • Rate-limit protection: subscription scale and message frequency have upper bounds, requiring local throttling and graceful degradation.

    Parsing, strategy, and execution threads should be decoupled. An illustrative structure:

    1. class MarketDataClient:
    2. def __init__(self, token, on_tick):
    3. self.token, self.on_tick = token, on_tick
    4. def subscribe(self, symbols):
    5. # incremental subscribe: send only the set difference for new additions, unsubscribe removed
    6. ...
    7. def _on_raw(self, payload):
    8. msg = codec.decode(payload) # deserialization + field validation
    9. if not seq_checker.continuous(msg): # sequence continuity check
    10. requester.backfill(msg.ts)
    11. queue.put(msg) # post to in-memory queue
    12. # a worker thread consumes from the queue and calls back on_tick

    Market-data ingestion follows a “parse thread writes → in-memory queue → strategy and persistence threads consume” pattern. When consumption falls behind, drop recomputable intermediate states and keep only key snapshots to avoid a backlog that stalls the process.

    6. Execution Layer: Order State Machine and Pre-Trade Risk Controls

    6.1 Order State Machine

    Submitting an order is not a single call but a state transition: local pending → submitted → partially filled → fully filled, with additional branches for cancelled, partially cancelled, rejected, and declined. The design requires:

    • Idempotency: generate a locally unique identifier for each order so reconnections or restarts do not resubmit duplicates;
    • Reconciliation: periodically compare the local order book against broker reports and repair state inconsistencies;
    • Timeout cancel/replace: automatically cancel or reprice orders that remain unfilled for too long according to rules;
    • Rate limiting: schedule submissions and cancellations within the channel’s frequency constraints to avoid triggering abnormal-trading flags.
    1. class OrderClient:
    2. def submit(self, order):
    3. if not risk.precheck(order, self.account):
    4. return Rejected("risk")
    5. if self.dedup.seen(order.client_order_id):
    6. return self.dedup.result(order.client_order_id)
    7. ack = self.gateway.place(order) # returns submitted / rejected / invalid
    8. self.state.save(order.client_order_id, ack)
    9. return ack
    10. # on_trade / on_cancel callbacks drive state transitions and persist them

    6.2 Pre-Trade Risk Checklist

    Funds and available-position checks, per-order and daily cumulative limits, limit-up/limit-down price protection, instrument and contract trading permissions, position concentration and max-drawdown circuit breakers. Risk controls must run before order submission, not be patched after fills are reported.

    7. From Backtest to Live: A Ten-Point Gap Checklist

    1. Fill assumptions: limit-up/limit-down and queueing make backtest fills nonexistent in live trading;
    2. Slippage and impact: order size and order-book depth jointly determine actual cost;
    3. Partial fills: support multiple fill reports and remaining-quantity management;
    4. Halts, resumptions, and delisting: held positions may be unsellable for long periods;
    5. Ex-rights and dividends: inconsistent adjustment bases cause signal drift;
    6. Survivorship bias: a complete backtest universe must include delisted instruments;
    7. Overfitting: the more parameters, the more out-of-sample and rolling validation is needed;
    8. Capacity and crowding: returns decay as strategy size grows;
    9. Clock synchronization: local clock drift can scramble signal and order timing;
    10. Single points of failure: process crashes and network outages require automatic recovery and alerting.

    8. Deployment and Operations: Even Low-Spec Cloud Hosts Work

    Lightweight strategies can run perfectly well on single-core, small-memory cloud hosts, provided heavy computation is separated from the real-time path: during the trading day, keep only data ingestion, signal evaluation, and order submission; put historical backtesting and batch factor computation in offline jobs or container batch processing. Reusable cloud capabilities include container platforms (strategy packaging and self-healing), message queues (decoupling and peak-shaving of market and order events), object storage (data archiving and backtest samples), logging services (end-to-end order tracing), and monitoring/alerting (availability, latency, rejection rate). For example, on Baidu AI Cloud, you can deploy strategies in containers and pair them with monitoring and alerting to trigger automatic notifications on anomalies, without building an entire operations system yourself.

    Metrics that must be monitored: market-data connection status and message latency, subscription success rate, order success rate and rejection-reason distribution, cancellation rate, and consistency between strategy positions and actual account positions. Running a once-daily “strategy–broker” reconciliation is the most effective way to uncover hidden defects.

    9. Roadmap and Selection Principles

    • Stage 1: Data first. Unify data bases, complete the trading calendar and adjustment handling, and ensure any historical range can be reproduced;
    • Stage 2: Simulation validation. Run the full pipeline in a simulated broker environment, focusing on reconnection, partial fills, and invalid-order handling;
    • Stage 3: Small-capital live trading. Run with limited size and frequency, comparing daily live fills and costs against the backtest;
    • Stage 4: Scaling and governance. Add capacity assessment, circuit breakers, and complete audit logs.

    Selection principles can be summarized as: prioritize foundational components that are still maintained, have complete documentation and examples, offer a simulation environment, and expose clearly abstracted interfaces; isolate external dependencies through adapter layers; for long-abandoned implementations, borrow design ideas only and do not adopt them in production. Also, programmatic trading must comply with local regulatory requirements on reporting, rate limits, and abnormal trading; use legally authorized data sources; and keep accounts under real-name registration with self-managed control.

    10. Conclusion

    The bar for quantitative trading in China is shifting from “can you write a strategy” to “can you run it stably, compliantly, and observably.” By splitting the toolchain into four layers—data, computation, execution, and operations—isolating external dependencies through adapters, and using a simulation environment and reconciliation to ensure trustworthiness, even a single low-spec cloud host can support a complete path from backtest to automated execution.