The backtest looked calm. Entries filled at the expected price, exits appeared within seconds, and the equity curve climbed without a single red flag.
Then the strategy went live.
The first order filled 18 basis points away from the signal price. The second signal arrived while the previous position was still open. A WebSocket connection dropped during a volatile session, and the system missed the exit. By the end of the day, a strategy with a 68% win rate in simulation had produced a 21% loss.
The model did not fail because the market behaved randomly. The deployment stack changed the assumptions that made the backtest appear profitable.
Five gaps usually explain the difference:
- Backtest assumes frictionless fills; live markets impose slippage.
- Backtest treats timestamps as instantaneous; live execution adds latency.
- Backtest assumes every message arrives; live connections fail.
- Backtest selects the best historical variant; live markets punish overfitting.
- Backtest removes human intervention; live operators change behavior under pressure.
For systematic traders, the solution is not to abandon a strategy after one bad session. The solution is to measure each gap separately, model it in research, enforce technical limits in production, and create an operating procedure that remains stable when the market becomes uncomfortable.
1. What Actually Changes Between Backtest and Live Trading?
A backtest converts historical observations into simulated decisions. Live trading adds an execution stack between the signal and the fill.
That stack contains queues, venue latency, network delay, exchange throttling, broker gateways, order-state transitions, and—in many systems—an internal risk engine. Each component can change the result even when the original signal remains identical.
| Assumption | Backtest environment | Live environment | Typical failure |
|---|---|---|---|
| Fill price | Signal price or bar close | Bid, ask, partial fill, or no fill | Adverse selection |
| Market impact | Fixed or zero | Quantity-dependent and liquidity-dependent | Slippage increases with size |
| Data arrival | Synchronous and complete | Delayed, duplicated, reordered, or missing | Stale-state decisions |
| Position state | Updated immediately | Pending, partially filled, cancelled, or rejected | Duplicate or oversized orders |
| Connectivity | Always available | Intermittent | Missed entries or exits |
| Parameters | Selected on one sample | Tested out of sample | Overfitting |
| Operator | No behavioral influence | Fear and fatigue affect intervention | Inconsistent risk enforcement |
The central mistake is treating the backtest as a prediction of live P&L. It is better understood as a controlled experiment. Its purpose is to isolate the market signal before execution costs and infrastructure failures enter the result.
Live trading adds another experiment layer. The strategy must now demonstrate that its edge survives realistic assumptions and that the implementation behaves correctly under adverse conditions.
2. Gap One: Slippage Is a Distribution, Not a Constant
A backtest frequently assumes that an order fills at the signal price, the next bar's close, or a fixed fraction of volatility. Live fills depend on available liquidity at the moment the order reaches the venue.
2.1 Separate spread, impact, and delay
Slippage has at least three components:
[
\text{Total slippage}
\text{Spread crossing}
+
\text{Market impact}
+
\text{Latency drift}
]
Spread crossing is the immediate cost of consuming the bid or ask. Market impact grows as order size increases relative to visible liquidity. Latency drift occurs when the market moves between signal generation and order arrival.
A market order in a liquid US equity may fill close to the quote while paying the spread. A large market order may consume multiple price levels. A limit order may avoid spread crossing but introduce non-execution risk. None of these methods is universally superior.
2.2 Measure realized slippage against a pre-trade benchmark
The benchmark must be defined before evaluating the strategy. A practical benchmark is the executable quote observed when the strategy decides to trade:
[
\text{Slippage}_{\text{bps}}
10{,}000
\times
\frac{
\text{side} \times (\text{fill price} - \text{benchmark price})
}{
\text{benchmark price}
}
]
where side equals +1 for a buy and -1 for a sell.
The benchmark should come from the same decision-time snapshot used by the strategy. Comparing a live fill with the historical close introduces additional timing error and can falsely classify normal delay as execution failure.
| Measurement stage | Metric | Why it matters |
|---|---|---|
| Signal generation | Decision timestamp | Establishes when the strategy committed |
| Pre-trade | Executable quote | Defines the expected fill region |
| Submission | Broker receipt timestamp | Measures client and network delay |
| Exchange | Venue arrival timestamp | Measures gateway and transport delay |
| Fill | Fill timestamp and price | Measures actual execution outcome |
2.3 Stress the backtest with distributions
Replace a single slippage assumption with a distribution based on measured observations. A simple model may use three regimes:
| Regime | Example conditions | Slippage assumption |
|---|---|---|
| Normal | Moderate spread and depth | 1–3 bps |
| Stressed | Elevated spread or partial fill | 5–12 bps |
| Extreme | News, halt risk, or thin liquidity | 15–40 bps plus non-execution |
These numbers are illustrative, not universal. Calibrate them from your symbols, order sizes, execution times, and venue.
A more useful test assigns each simulated order a random value from an empirical distribution, then repeats the backtest thousands of times. The result should be a range of outcomes, not one attractive line.
3. Gap Two: Latency Changes the Signal
The timestamp on a candle does not represent the instant a trader can trade the information inside it.
Suppose a bar closes at 10:00:00.000. The feed may deliver it at 10:00:00.035. The strategy may require another 10 ms to calculate its target position. The order then travels through the client, broker, exchange gateway, and matching engine. If total latency reaches 45 ms, the order can arrive when the market has already moved beyond the backtest's assumed entry point.
3.1 Decompose the latency budget
| Segment | Target | Typical cause |
|---|---|---|
| Market-data ingestion | 1–10 ms | Exchange feed, transport, decoding |
| Signal computation | 1–20 ms | Feature calculation and model inference |
| Decision-to-submit | 2–15 ms | Risk checks, serialization, network |
| Broker-to-venue | 10–100+ ms | Matching or routing infrastructure |
| Fill feedback | 5–100+ ms | Fill report and client processing |
Targets must be measured in the deployment environment. A local development laptop does not represent a colocated production stack.
3.2 Use the same clock across the system
Do not combine timestamps from machines whose clocks have drifted. Synchronize them through a disciplined time protocol and verify the offset continuously.
Store at least three timestamps for each order:
signal_ts: when the strategy generated the intent.submit_ts: when the client handed the order to the broker.fill_ts: when the fill report was received.
A useful client-side delay metric is:
[
\text{Decision latency} = \text{submit_ts} - \text{signal_ts}
]
If the delay rises sharply, the system should reduce order rate or stop initiating positions. A strategy that tolerates 50 ms during testing may become unstable when scheduling contention pushes latency to 500 ms.
3.3 Test latency as an input, not an exception
Create a Monte Carlo simulation that delays signals by a sampled latency distribution. Then model the price movement during that delay.
A conservative model can use:
from dataclasses import dataclass
import random
@dataclass
class DelayAssumption:
median_ms: float
p95_ms: float
worst_ms: float
DELAY = DelayAssumption(
median_ms=25,
p95_ms=80,
worst_ms=250,
)
def sample_delay_ms() -> float:
"""Piecewise delay model calibrated from production timestamps."""
sample = random.random()
if sample < 0.50:
return random.uniform(8, DELAY.median_ms)
if sample < 0.95:
return random.uniform(DELAY.median_ms, DELAY.p95_ms)
return random.uniform(DELAY.p95_ms, DELAY.worst_ms)
Apply the sampled delay to each entry and exit before calculating fills. If the strategy survives only under a fixed one-millisecond delay, it has not survived a realistic deployment test.
4. Gap Three: Disconnection Is a State, Not an Exception
A live system has at least two independent communication paths:
- The market-data connection carries prices and order-book updates.
- The trading connection carries orders and execution reports.
Either path can fail. If the trading connection drops while the data connection remains active, the system may continue calculating signals without knowing whether an earlier order filled. If the market-data connection drops, stale prices may produce signals based on an obsolete market state.
4.1 The safe state machine
A robust order lifecycle should use explicit states:
NEW → PENDING_NEW → WORKING → PARTIALLY_FILLED → FILLED
│
├── CANCEL_PENDING → CANCELED
└── REJECTED
On disconnect, the system should not assume that an outstanding order disappeared. It should enter an UNKNOWN state and reconcile with the broker before sending another order.
4.2 Production monitoring client
The following reference client monitors a broker-compatible WebSocket feed. It uses heartbeat messages, exponential backoff with jitter, authenticated environment variables, HTTP timeouts, and explicit rate-limit handling. Replace the URL and message parser with the selected broker's adapter, but retain the state and failure-management logic.
import json
import os
import random
import time
from datetime import datetime, timezone
import requests
import websocket
API_KEY = os.environ.get("BROKER_API_KEY")
WS_URL = os.environ.get("BROKER_WS_URL")
HTTP_BASE_URL = os.environ.get("BROKER_HTTP_URL", "").rstrip("/")
HEARTBEAT_SECONDS = 15
MAX_RECONNECT_DELAY_SECONDS = 60
MAX_SLIPPAGE_BPS = 10.0
MAX_SIGNAL_LATENCY_MS = 250
class ExecutionGuard:
def __init__(self):
self.running = True
self.last_message_monotonic = time.monotonic()
self.in_flight = {}
def stop(self):
self.running = False
def on_message(self, raw_message):
self.last_message_monotonic = time.monotonic()
message = json.loads(raw_message)
# Adapter requirement: broker messages include these fields.
if message.get("type") != "fill":
return
order_id = message["order_id"]
fill = self.in_flight.get(order_id, {})
fill.update({
"filled_qty": message["filled_qty"],
"fill_price": float(message["fill_price"]),
"fill_ts": message.get("ts"),
})
self.in_flight[order_id] = fill
signal_ts = fill.get("signal_ts")
fill_ts = message.get("ts")
if signal_ts is not None and fill_ts is not None:
latency_ms = max(0.0, (float(fill_ts) - float(signal_ts)) * 1000)
if latency_ms > MAX_SIGNAL_LATENCY_MS:
self.alert(
f"Order {order_id}: signal latency {latency_ms:.1f} ms "
f"exceeds {MAX_SIGNAL_LATENCY_MS:.0f} ms"
)
benchmark = fill.get("benchmark_price")
side = fill.get("side")
if benchmark and side:
sign = 1 if side == "buy" else -1
slippage_bps = (
10_000
* sign
* (fill["fill_price"] - float(benchmark))
/ float(benchmark)
)
if slippage_bps > MAX_SLIPPAGE_BPS:
self.alert(
f"Order {order_id}: realized slippage "
f"{slippage_bps:.2f} bps exceeds "
f"{MAX_SLIPPAGE_BPS:.2f} bps"
)
def alert(self, message):
print(f"[ALERT] {message}", flush=True)
def stale_connection(self):
idle_seconds = time.monotonic() - self.last_message_monotonic
return idle_seconds > HEARTBEAT_SECONDS * 2
def fetch_open_orders(api_key):
"""Reconcile outstanding orders after a connection interruption."""
if not HTTP_BASE_URL:
return []
response = requests.get(
f"{HTTP_BASE_URL}/orders",
headers={"X-API-Key": api_key},
params={"status": "open"},
timeout=(3.05, 10),
)
# TickDB-style payload code 3001 is handled explicitly.
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", "5"))
time.sleep(retry_after)
return []
try:
payload = response.json()
except ValueError as exc:
raise RuntimeError("Broker returned invalid JSON") from exc
code = payload.get("code", 0)
if code == 3001:
retry_after = int(response.headers.get("Retry-After", "5"))
time.sleep(retry_after)
return []
if code in (1001, 1002):
raise ValueError("Invalid or missing BROKER_API_KEY")
if code != 0:
raise RuntimeError(f"Broker error {code}: {payload.get('message')}")
return payload.get("data", [])
def run():
if not API_KEY or not WS_URL:
raise RuntimeError(
"Set BROKER_API_KEY and BROKER_WS_URL before starting the guard"
)
guard = ExecutionGuard()
retry = 0
while guard.running:
try:
websocket.enableTrace(False)
socket = websocket.create_connection(
f"{WS_URL}?api_key={API_KEY}",
timeout=10,
enable_multithread=True,
)
retry = 0
print("[INFO] WebSocket connected", flush=True)
while guard.running:
socket.send(json.dumps({"cmd": "ping"}))
socket.settimeout(HEARTBEAT_SECONDS)
raw_message = socket.recv()
guard.on_message(raw_message)
if guard.stale_connection():
raise TimeoutError("Market or execution feed is stale")
socket.close()
except (websocket.WebSocketException, OSError, TimeoutError, ValueError) as exc:
print(f"[WARN] Connection failed: {exc}", flush=True)
# Reconcile before the next order can be submitted.
try:
open_orders = fetch_open_orders(API_KEY)
guard.in_flight = {item["order_id"]: item for item in open_orders}
print(
f"[INFO] Reconciled {len(open_orders)} open order(s)",
flush=True,
)
except Exception as reconcile_exc:
print(
f"[ERROR] Reconciliation failed: {reconcile_exc}",
flush=True,
)
delay = min(
2 ** retry,
MAX_RECONNECT_DELAY_SECONDS,
)
jitter = random.uniform(0, delay * 0.1)
retry += 1
print(
f"[INFO] Reconnecting in {delay + jitter:.2f}s",
flush=True,
)
time.sleep(delay + jitter)
if __name__ == "__main__":
run()
4.3 Required production safeguards
The monitoring client should be supplemented with the following controls:
- Staleness timer: Stop trading if no fresh market or execution data arrives.
- Position reconciliation: Compare broker positions with internal positions after every restart.
- Idempotent order IDs: Ensure retries cannot create duplicate orders.
- Maximum order rate: Limit submissions per symbol and per account.
- Dead-man switch: Trigger a controlled shutdown if the heartbeat service stops.
- Kill switch: Cancel open orders and flatten positions under an independent control path.
- Persistent audit log: Record signal, decision, order, acknowledgment, and fill events.
The crucial design principle is fail-closed behavior. When state is uncertain, the system should not continue opening positions.
5. Gap Four: Overfitting Survives the Backtest
Overfitting is often described as selecting parameters that happened to work in the past. In practice, it can occur at several levels:
- Choosing the best entry threshold from dozens of candidates.
- Selecting the best symbol universe after observing the test period.
- Changing a feature definition after inspecting performance.
- Choosing a favorable start and end date.
- Optimizing execution assumptions until the strategy passes.
- Treating multiple hypothesis tests as one experiment.
The strategy can look excellent in-sample and fail because the selected configuration captured noise rather than a persistent mechanism.
5.1 Separate research freedom from deployment freedom
A reliable process divides data and decisions into distinct stages:
| Stage | Purpose | Allowed actions |
|---|---|---|
| Research | Discover candidate signals | Feature engineering and broad exploration |
| Validation | Test stability across periods and symbols | Limited parameter changes |
| Freeze | Record code, data, parameters, and assumptions | No strategy edits |
| Out-of-sample test | Estimate unseen performance | One evaluation under fixed rules |
| Paper or shadow execution | Test the implementation | Operational changes with strategy frozen |
| Limited live deployment | Validate real fills and operations | No automatic parameter optimization |
The critical principle is that the final out-of-sample test must occur after the strategy is frozen. Repeatedly testing new versions against the same “out-of-sample” period converts it into another in-sample dataset.
5.2 Test parameter stability
A profitable parameter region is usually broader than one isolated optimum.
from dataclasses import dataclass
from itertools import product
@dataclass
class Result:
fast_window: int
slow_window: int
sharpe: float
max_drawdown: float
def parameter_grid(fast_values, slow_values):
for fast, slow in product(fast_values, slow_values):
if fast >= slow:
continue
yield fast, slow
def acceptable(result: Result) -> bool:
"""Example policy; thresholds must come from the research plan."""
return (
result.sharpe > 0.75
and result.max_drawdown > -0.20
)
def select_stable_region(results, minimum_neighbors=4):
"""Reject isolated peaks in a two-dimensional parameter surface."""
surface = {
(r.fast_window, r.slow_window): r
for r in results
if acceptable(r)
}
stable = []
for (fast, slow), result in surface.items():
neighbors = [
surface.get((fast + df, slow + ds))
for df in (-1, 0, 1)
for ds in (-1, 0, 1)
if (df, ds) != (0, 0)
]
valid_neighbors = [n for n in neighbors if n is not None]
if len(valid_neighbors) >= minimum_neighbors:
stable.append(result)
return stable
A stable parameter region does not guarantee profitability. It indicates that nearby configurations produce similar results, which reduces the risk that the selected point is a numerical accident.
5.3 Evaluate more than net return
The acceptance criteria should include:
- Net return after realistic fees and slippage.
- Sharpe and Sortino ratios.
- Maximum drawdown and drawdown duration.
- Profit factor and average win/loss ratio.
- Win rate and payoff distribution.
- Turnover and capacity by symbol.
- Performance across market regimes.
- Stability across nearby parameter values.
- Degradation after transaction costs increase.
- Recovery time after the largest loss.
If profitability disappears when slippage changes from 2 bps to 8 bps, the strategy does not have enough margin of safety.
6. Gap Five: Mental State Changes the System
A backtest has no fear, fatigue, or urge to intervene. A live operator experiences all three.
The behavioral problem is not merely emotional. It changes the system state:
- A trader closes a losing position manually.
- A trader increases size after a drawdown.
- A trader disables the strategy after several consecutive losses.
- A trader overrides an alert during an event because the signal looks “obviously wrong.”
- A trader changes a parameter after observing live results and then continues backtesting on the same data.
These actions create discretionary trades outside the tested strategy. They also contaminate the live dataset, making later research unreliable.
6.1 Separate signal decisions from emergency decisions
A production operating procedure should define who can do what:
| Action | Automated system | Human operator |
|---|---|---|
| Enter or exit according to strategy | Yes | No discretionary override |
| Adjust position size | Within tested limits | Emergency reduction only |
| Pause new entries | On stale data or risk breach | Yes |
| Modify parameters | No live modification | No; create a new research version |
| Cancel open orders | On policy trigger | Yes |
| Flatten positions | Under documented emergency rule | With two-person approval for institutional deployments |
The emergency path must also be explicit. “Intervene if it looks wrong” is not a control. A usable rule identifies the observable condition, required action, restoration procedure, and audit record.
6.2 Use precommitted operating rules
Before deployment, write down:
- Maximum loss per day and per strategy.
- Maximum acceptable slippage.
- Maximum stale-data duration.
- Maximum order and position rates.
- Conditions that pause entries.
- Conditions that require flattening.
- Who can authorize restarting the system.
- The requirement to preserve logs before investigating an incident.
Once the system is live, changing a rule because of discomfort introduces behavioral drift. If a rule is wrong, change it in the research environment, redeploy a versioned configuration, and restart the evaluation process.
6.3 Make the system harder to override incorrectly
Controls such as two-person approval, separate emergency credentials, and immutable configuration snapshots reduce the probability of impulsive intervention. Logging every override also creates accountability without requiring an automated system to make the final psychological judgment.
7. Calibrating the Backtest with Live-Shaped Assumptions
The most useful backtest is not one that predicts every fill perfectly. It is one that answers: How much execution deterioration can this strategy absorb before its expected edge disappears?
7.1 A complete stress grid
Run the strategy over several combinations of execution assumptions:
| Scenario | Slippage | Latency | Missing messages | Partial fills |
|---|---|---|---|---|
| Optimistic | Historical median | Historical median | None | Disabled |
| Base | 75th percentile | P50 | 0.1% | Enabled |
| Conservative | P95 | P95 | 0.5% | Enabled |
| Stress | 2× P95 | P95 | 1.0% | Severe |
| Failure | 3× P95 | Worst observed | 5.0% | Severe |
The resulting distribution should reveal which failure mode destroys the strategy. A trend-following system may tolerate delay but fail under slippage. A mean-reversion system may be highly sensitive to stale quotes. An execution-heavy strategy may fail because partial fills create inventory the model did not expect.
7.2 Build slippage directly from observed market depth
When reliable order-book data is available, estimate a fill path from available depth rather than applying one flat cost.
For a marketable buy:
[
\text{Expected fill price}
\frac{
\sum_{i=1}^{N}
P_i \times Q_i
}{
\sum_{i=1}^{N} Q_i
}
]
where (P_i) and (Q_i) represent the ask price and quantity at each level, truncated when cumulative quantity reaches the order size.
The estimate should also include a configurable latency shock. If the strategy consumes levels after the quote moves, the backtest can add or remove levels before calculating the fill.
7.3 Respect market-data boundaries
Not every symbol provides the same microstructure data. US equity depth is commonly limited to top-of-book data, while Hong Kong equities and many crypto venues provide multi-level depth. Forex, precious metals, and indices generally require different approaches because order-book depth is unavailable or fragmented.
For historical calibration, TickDB's GET /v1/market/kline endpoint can provide completed-period US equity OHLCV data for baseline research:
import os
import requests
API_KEY = os.environ.get("TICKDB_API_KEY")
if not API_KEY:
raise RuntimeError("Set TICKDB_API_KEY before fetching market data")
response = requests.get(
"https://api.tickdb.ai/v1/market/kline",
headers={"X-API-Key": API_KEY},
params={
"symbol": "AAPL.US",
"interval": "1d",
"limit": 1000,
},
timeout=(3.05, 10),
)
payload = response.json()
code = payload.get("code", 0)
if code == 0:
bars = payload.get("data", [])
elif code in (1001, 1002):
raise ValueError("Invalid or missing TICKDB_API_KEY")
elif code == 2002:
raise KeyError("Symbol not found; verify it via /v1/symbols/available")
elif code == 3001:
retry_after = int(response.headers.get("Retry-After", "5"))
print(f"Rate limited; retry after {retry_after}s")
else:
raise RuntimeError(payload.get("message", "Unexpected market-data error"))
Use /v1/market/kline for completed historical periods and /v1/market/kline/latest for a current dashboard candle. Do not substitute one endpoint for the other in a backtest.
Historical OHLCV can support signal research and cost modeling, but it does not recreate the exact queue position or visible depth available when a live order arrived. Keep that limitation in the acceptance criteria.
8. Production Architecture: Where Each Failure Is Caught
A live strategy should contain independent controls rather than relying on one process to detect every failure.
┌──────────────────────┐
│ Market Data Feed │
│ Freshness + sequence │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Signal Engine │
│ Features + target │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Risk Gate │
│ Size + limits + mode │
└──────────┬───────────┘
│ approved intent
▼
┌──────────────────────┐
│ Execution Adapter │
│ Idempotency + routing│
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Broker / Exchange │
│ Orders + fills │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Reconciliation Engine│
│ Positions + exposure │
└──────────┬───────────┘
│
├────────────► Audit Log / Metrics / Alerts
│
▼
┌──────────────────────┐
│ Emergency Controller │
│ Pause + cancel + halt│
└──────────────────────┘
| Layer | Primary responsibility | Failure response |
|---|---|---|
| Market-data adapter | Validate freshness and sequence continuity | Pause entries |
| Signal engine | Compute the strategy's target position | Stop on stale input |
| Risk gate | Enforce size, exposure, and loss limits | Reject or reduce order |
| Execution adapter | Produce unique, idempotent orders | Reconcile uncertain state |
| Reconciliation engine | Compare internal and broker positions | Halt new exposure |
| Emergency controller | Cancel orders or flatten positions | Isolate and alert |
The layers should fail independently. A timeout in the feature calculation must not bypass the risk gate, and an order-state uncertainty must not cause the system to assume the position is flat.
9. The Deployment Gate
Do not move directly from a successful backtest to full-size live execution. Use a sequence of gates that increases exposure only after each layer produces evidence.
| Gate | Required evidence | Failure action |
|---|---|---|
| Research | Stable results across relevant periods | Revise or reject the hypothesis |
| Out-of-sample test | Frozen configuration performs as expected | Do not tune on the test set |
| Shadow execution | Signals and target positions match the research logic | Fix implementation differences |
| Minimal-size deployment | Orders, fills, and reconciliation are correct | Pause and investigate |
| Partial exposure | Slippage and latency remain within limits | Reduce size or halt |
| Full deployment | Operational and risk metrics pass review | Continue monitoring |
A promotion checklist should require more than positive P&L:
- Strategy code and parameters are versioned.
- Historical assumptions include measured slippage and latency distributions.
- The out-of-sample period is documented and no longer used for tuning.
- Live timestamps use synchronized clocks.
- Stale data and duplicate messages are handled.
- Disconnect reconciliation is tested by killing the connection process.
- Partial fills and rejected orders are tested.
- Restart recovery has been rehearsed.
- Emergency cancellation and flattening procedures are documented.
- Daily loss and drawdown limits are active.
- Logs preserve signals, orders, acknowledgments, fills, and overrides.
- The operator has not altered parameters during the evaluation period.
10. A Practical Diagnostic Sequence
When live results diverge from the backtest, investigate the gaps in causal order rather than immediately changing the strategy.
- Compare signals. Does the live system generate the same entries and exits as the offline replay?
- Compare timestamps. Has signal-to-submit latency changed?
- Compare quotes. Was the live decision based on stale or crossed market data?
- Compare orders. Did the broker receive the intended quantity, price, and order type?
- Compare fills. How much of the difference came from spread, delay, and market impact?
- Reconcile positions. Did partial fills or rejected cancellations create unmodeled inventory?
- Check intervention logs. Did a human alter the intended execution?
- Only then reassess the strategy. Parameter changes require a new controlled research cycle.
This sequence prevents the most expensive mistake: changing strategy logic to compensate for an infrastructure defect.
11. What “Production-Ready” Actually Means
A production-ready strategy does not merely have positive backtest results. It demonstrates five properties:
- Economic validity: The signal has a plausible mechanism and survives realistic costs.
- Statistical stability: The result does not depend on one date, symbol, parameter, or test split.
- Operational resilience: Disconnects, stale data, duplicate messages, and partial fills do not corrupt state.
- Risk containment: The account-level loss remains bounded when assumptions fail.
- Behavioral discipline: Operators follow a precommitted procedure rather than improvising through recent losses.
The five gaps therefore form one causal chain:
- Incorrect friction assumptions create unrealistic backtests.
- Latency magnifies the difference between intended and executed prices.
- Disconnects break the mapping between internal state and broker state.
- Overfitting disguises weak assumptions as robust evidence.
- Behavioral drift converts uncertainty into unauthorized risk.
Close the gaps in that order. Start by reproducing the live signal path in replay, measure execution costs, inject failures, and freeze the strategy before evaluation. A successful live deployment is not the first day with positive returns. It is the first day the system behaves as designed under conditions you did not want to experience.
Next Steps
If you are building your first systematic strategy, begin with a paper-trading stage that records decision timestamps, executable quotes, order acknowledgments, and realized slippage. A small production dataset will improve your cost model more than another parameter sweep.
If you already have a live strategy, export one week of signal, submission, acknowledgment, and fill timestamps. Calculate the delay distribution and compare realized slippage with the backtest assumptions. The largest divergence usually identifies the most urgent engineering work.
If you need historical US equity OHLCV data to build or calibrate a backtest, create a TickDB API key, set TICKDB_API_KEY in your environment, and use completed-period /v1/market/kline data. Live execution data should still be collected independently.
If you are evaluating an institutional deployment, define operational ownership, reconciliation requirements, and emergency controls before increasing capital.
This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results.