Designing a Mechanical Trading System: Practical Rules for K-Line and Moving Averages

    This article explains how to build a mechanical trading system by converting market behavior into a finite set of well-defined states using K-line patterns and moving averages. It covers state formalization, a three-layer framework of signals, filters, and position sizing, four-step validation through backtesting and out-of-sample testing, and engineering methods for controlling execution bias. Readers will learn how rule-based execution, risk budgeting, and proper validation help enforce consistency and manage risk.

    1. Why Mechanical Trading Matters

    Most traders lose money not because they cannot read a chart, but because their decision process is not reproducible: entry reasons are vague, exit conditions change on the fly, and position size drifts with emotion. The core value of mechanical trading is to move decisions from “in-the-moment judgment” to “defined in advance,” so that every trade can be traced back to a specific rule.

    Mechanical does not mean simplistic. It means converging complexity into a limited set of mutually exclusive, enumerable scenarios. The source material emphasizes reducing highly complex price action into roughly a dozen fully classified states. In engineering terms, this is equivalent to state machine design: a finite number of states, clearly defined transition conditions between them, and an input at any moment that maps to exactly one action.

    This leads to the central concept of the article: probabilistic edge. The outcome of a single trade is random, but a set of rules may show a positive expected value over a sufficiently large sample. If the expected return per trade is positive, long-term results are driven by sample size rather than by any single judgment.

    2. Compressing Market Data into Finite States: Formalizing Volatility Patterns

    Price movement can be abstracted into three parent states: trend continuation, range-bound oscillation, and trend exhaustion. These are then subdivided based on the relative relationship between K-lines and moving averages. A moving average is essentially a smoothing filter on price, used to suppress high-frequency noise; a K-line preserves the single-period extreme and body information, used to confirm the local balance of power.

    An example of a workable state definition (illustrative pseudocode, not any specific product interface):

    1. # Input: closing price series close[], period parameters n_fast, n_slow
    2. ma_fast = MA(close, n_fast)
    3. ma_slow = MA(close, n_slow)
    4. state = {
    5. "trend_up": ma_fast > ma_slow and slope(ma_slow) > 0,
    6. "trend_down": ma_fast < ma_slow and slope(ma_slow) < 0,
    7. "range": abs(ma_fast - ma_slow) / close < eps
    8. }
    9. # Action mapping: state -> single action, no ad-hoc new branches allowed
    10. action = POLICY[state] # only long / short / wait / reduce position allowed

    There are three engineering points. First, states must be mutually exclusive; otherwise multiple signals appear at the same moment. Second, thresholds such as eps and the periods n_fast/n_slow must be hard-coded in configuration and cannot be adjusted during a session. Third, the action set must be closed, and any undefined state maps to “wait.”

    3. Signals, Filters, and Position Sizing: Three Layers of Constraints

    The first layer is the signal layer, responsible only for answering “direction.” Moving average alignment and slope give direction, while K-line patterns give the trigger timing, for example a breakout beyond the extreme of the previous several periods as entry confirmation.

    The second layer is the filter layer, used to reduce the frequency of ineffective trades. Common approaches include volatility filtering (no trading when the range is too narrow), time filtering (no trading during periods of very poor liquidity), and consistency filtering (downgrading to “wait” when multi-period directions conflict). The purpose of the filter layer is not to raise the win rate, but to make the sample distribution more stable and prevent the rules from drifting sharply across different market conditions.

    The third layer is the position and stop-loss layer, which determines risk exposure. In a mechanical framework, the stop-loss must be derived from volatility before entry, and position size is back-calculated from “maximum acceptable loss per trade / stop distance”:

    1. risk_per_trade = equity * risk_ratio # risk_ratio recommended as a fixed small number
    2. stop_distance = k * ATR(period=14) # determined by volatility, not set subjectively
    3. position_size = risk_per_trade / stop_distance

    The value of this layer is that it turns “loss” into a budget item. During consecutive losses, the per-trade risk stays unchanged while account equity declines, so position size shrinks automatically and drawdown is constrained within a calculable range.

    4. Validating the Probabilistic Edge: Backtesting and Out-of-Sample Testing

    Any rule that has not been tested is only a hypothesis. A recommended validation process has four steps:

    1. In-sample testing: confirm the expected value is positive, and record win rate, profit/loss ratio, maximum drawdown, and number of trades.
    2. Out-of-sample testing: split off a period in time that did not participate in parameter tuning, and observe how much the metrics decay.
    3. Parameter sensitivity analysis: apply small perturbations to parameters; if performance collapses, the rule is overfitted.
    4. Cost stress testing: significantly increase commission and slippage assumptions to check whether the edge is consumed by costs.

    It must be clear that a backtest edge does not equal future returns. Mechanical trading only guarantees “consistent execution,” not “profitable results.” Real risk control comes from position sizing and stop-losses, not from pursuing a high win rate.

    5. Engineering the Management of Execution Bias and Mindset

    The source material treats “the pursuit of perfection” as a typical psychological trap in trading. This can be restated in engineering terms: perfectionism shows up as changing rules mid-session, taking profit early, and adding to positions after losses, which is essentially injecting undefined inputs into the system. The remedy is process-driven rather than willpower-driven:

    • Write the rules into a checklist before trading; during a session only “match and execute,” do not “create.”
    • Record the rule ID for each trade, and during review distinguish “rule failure” from “execution failure.”
    • Use a fixed template to log emotional trigger points, turning mindset issues into a statistically measurable deviation rate.
    • Accept that single-trade outcomes are random, and only assess rule execution rate and long-term expected value.

    6. Common Pitfalls and Implementation Advice

    Pitfall one: treating parameter optimization as the research goal. Parameters are just slices of noise, and over-optimization makes rules fit history rather than the future. Pitfall two: ignoring sample size. A few dozen trades cannot support any statistical conclusion. Pitfall three: stacking multiple strategies without correlation analysis, causing risk exposure to be double-counted.

    Suggested implementation path: first get a closed loop working with a single instrument and a single period, then expand gradually; solidify configuration, logging, and review so the system is observable; when deploying in the cloud, use a container platform to host backtest and live-trading processes, use object storage to save market data and trade records, and use a logging service with monitoring and alerting to track execution bias, so that rule versions are traceable and results are auditable.