At 10:03:17 on a volatile morning, a trend signal fires with the stock trading 42 basis points above its breakout level. The order fills, but the entry price lands six cents worse than the quote displayed one second earlier. The signal was correct; the execution still lost a measurable part of its edge.
That gap is an execution problem, not a signal problem. A breakout tells us when to enter; the National Best Bid and Offer, or NBBO, tells us what a marketable order is likely to pay and where a passive order might rest.
For systematic traders, the practical question is therefore narrower: once a trend entry triggers, should the algorithm cross the offer, post at the bid, wait inside the spread, or stand aside? This article builds a quote-aware decision framework and implements it as a resilient WebSocket execution monitor, with an explicit cost model for comparing aggressive and passive entry policies.
1. Why the NBBO Changes the Entry Decision
The NBBO combines the highest bid and lowest ask available across US equity trading venues. It provides the market-wide reference prices for two primary entry styles:
- Aggressive entry: Buy at or near the current ask, accepting the spread to reduce non-execution risk.
- Passive entry: Post at or near the current bid, earning part of the spread while accepting queue, adverse-selection, and non-fill risk.
A trend signal alone cannot distinguish between these outcomes. Two orders generated at the same instant can have materially different implementation shortfalls because the spread, quote size, quote age, and expected fill probability differ at that moment.
The following table illustrates a single evaluation point. The values are hypothetical but internally consistent.
| Signal time | Bid | Ask | Spread | Bid size | Ask size | Quote age | Signal state |
|---|---|---|---|---|---|---|---|
| 10:03:16.900 | $101.08 | $101.10 | $0.02 | 1,400 | 900 | 120 ms | No position |
| 10:03:17.000 | $101.08 | $101.11 | $0.03 | 800 | 1,600 | 85 ms | Breakout |
| 10:03:17.400 | $101.07 | $101.09 | $0.02 | 2,200 | 700 | 210 ms | Breakout |
| 10:03:18.100 | $101.05 | $101.09 | $0.04 | 600 | 1,900 | 1,800 ms | Breakout |
At 10:03:17.000, a marketable buy at $101.11 pays half of the spread plus a potential impact cost. Posting at $101.08 is cheaper if it fills, but the displayed 800 shares create queue risk and the fill probability depends on subsequent trading activity.
At 10:03:18.100, the spread has narrowed, yet the quote is already 1.8 seconds old. A narrow spread attached to a stale quote is not an attractive entry. Quote freshness is therefore part of execution quality, not merely a data-engineering detail.
The three costs that matter
A practical entry model separates implementation shortfall into three components:
- Spread cost: The difference between the decision-price reference and the execution price.
- Market impact: The additional price movement caused by consuming available liquidity.
- Opportunity cost: The expected economic cost of waiting when the order does not fill or when a passive order is filled only after adverse price movement.
Ignoring the third component biases the system toward passive orders. Ignoring the first two biases it toward aggressive orders.
2. Reference Architecture for Quote-Aware Entries
A reliable implementation separates market data, signal generation, execution policy, and order routing. Each layer should have a clear failure mode.
+--------------------------+
| Consolidated NBBO Feed |
| quotes + trades + venue |
+------------+-------------+
|
v
+--------------------------+
| Quote State Store |
| - best bid / ask |
| - displayed sizes |
| - quote age |
| - imbalance history |
| - trade arrival rate |
+------------+-------------+
|
+----------------+----------------+
| |
v v
+----------------------+ +----------------------+
| Trend Signal Engine | | Entry Policy Engine |
| breakout / momentum | | aggressive / passive |
+----------+-----------+ +----------+-----------+
| |
+-------------------+----------------+
v
+--------------------------+
| Order Router / OMS |
| - limit price |
| - participation rate |
| - child order logic |
+--------------------------+
The policy engine should receive a normalized market-state object rather than query data sources directly. That separation makes the execution logic testable and prevents a vendor-specific message format from leaking into the strategy layer.
Normalized quote state
A practical quote-state object should contain at least the following fields:
symbol
bid_price
ask_price
bid_size
ask_size
quote_timestamp
receive_timestamp
exchange
Two additional distinctions matter:
- Displayed size is not aggregate depth. The size attached to the winning bid or ask generally reflects the quote at the venue currently setting that price. It does not represent all executable liquidity beneath the top of book.
- A quote update is not a trade. A new bid or ask can replace an old quote without any transaction occurring. Fill estimates therefore need trade arrival data in addition to quote data.
3. Selecting the Optimal Entry Price
The policy engine compares expected implementation shortfall across several candidate orders. The reference price at the moment of the decision is the midpoint:
[
m = \frac{bid + ask}{2}
]
For a marketable buy, the basic spread cost is:
[
c_{spread} = ask - m = \frac{ask - bid}{2}
]
A passive bid order pays the following cost when it fills:
[
c_{passive,fill} = m - bid + c_{adverse} + fee_{maker}
]
The adverse-selection term estimates the loss from being filled while the market is moving against the order.
Let (p_f) represent the estimated fill probability and (T) represent the maximum passive waiting horizon. If unfilled orders impose an opportunity-cost rate of (\lambda) dollars per share per second, the passive policy becomes:
[
ES_{passive}
p_f \cdot c_{passive,fill}
+
\lambda \left(p_f \cdot \frac{T}{2} + (1-p_f)T\right)
]
An aggressive policy has a much shorter delay:
[
ES_{aggressive}
ask - m + fee_{taker} + impact
+
\lambda \cdot t_{aggressive}
]
The policy engine selects the order with the lower expected shortfall. It should also apply hard constraints before comparing costs:
- Reject a quote older than the configured maximum age.
- Reject a spread wider than the strategy’s tolerance.
- Reject an order when the required participation rate exceeds the limit.
- Reduce or cancel the order when a newer quote invalidates the original decision.
A practical policy table
| Market condition | Preferred entry | Rationale |
|---|---|---|
| Tight spread, large ask size, strong breakout | Aggressive at ask | Fill probability is high and spread cost is controlled |
| Wide spread, stable quotes, urgent signal | Limit just inside the ask | Reduces spread cost without resting far from the market |
| Wide spread, adequate queue estimate, non-urgent signal | Passive at bid | Earns spread compensation if fill probability is sufficient |
| Quote age exceeds threshold | Wait or re-evaluate | Stale prices create false execution estimates |
| Top-of-book size is insufficient | Split or route | A single child order would consume too much visible liquidity |
| Estimated expected shortfall is negative | No trade | The signal is not worth its execution cost |
The table describes a decision policy, not a universal parameter set. Every threshold should be estimated from the strategy’s own symbol universe and time-of-day liquidity profile.
4. Estimating Passive Fill Probability
NBBO quote sizes provide a starting point for the queue estimate, but they do not reveal the exact number of shares ahead of a new order. The displayed bid size is the minimum plausible queue when a passive order is posted immediately behind it.
A conservative first approximation is:
[
queue_{ahead} \approx bid_size
]
If the estimated arrival rate is (r) shares per second and the horizon is (T), expected consumed liquidity is:
[
volume_T = r \cdot T
]
Using a normal approximation for the probability that available volume reaches the queue:
[
p_f
\approx
\Phi\left(
\frac{volume_T - queue_{ahead} - 0.5}
{\sqrt{volume_T}}
\right)
]
This estimate is intentionally conservative. It ignores cancellations ahead of the order, hidden liquidity, queue-position improvement, and venue-specific execution priority. It should therefore be treated as an input to a decision system, not as a fill guarantee.
A more accurate model can update the queue estimate as follows:
[
queue_{ahead}(t+1)
max\left(0,\ queue_{ahead}(t) - consumed_{bid}(t)\right)
- new_size(t)
]
That update requires trade-level data and timestamp alignment. Without trades, a system can estimate fill probability but cannot distinguish a genuine queue reduction from a quote replacement.
5. Production-Grade WebSocket Decision Engine
The following Python implementation connects to Alpaca’s real-time equity quote and trade streams. The sip feed provides consolidated US equity market data; iex is a lower-cost exchange-specific feed and does not represent the same consolidated NBBO universe.
The program does not place orders. It evaluates a simple trade-print breakout and prints the recommended entry policy, limit price, estimated fill probability, and expected shortfall. The separation keeps the execution logic auditable before connecting it to an order management system.
Environment configuration
export ALPACA_API_KEY="your-api-key"
export ALPACA_SECRET_KEY="your-secret-key"
export ALPACA_FEED="sip"
export TARGET_SHARES="500"
Install the WebSocket dependency:
pip install websockets
Implementation
from __future__ import annotations
import asyncio
import json
import math
import os
import random
import statistics
import time
from collections import deque
from dataclasses import dataclass
from datetime import datetime
from typing import Deque
import websockets
from websockets.exceptions import ConnectionClosed
WS_FEED = os.environ.get("ALPACA_FEED", "sip").lower()
WS_URL = f"wss://stream.data.alpaca.markets/v2/{WS_FEED}"
SYMBOL = os.environ.get("TARGET_SYMBOL", "AAPL").upper()
API_KEY = os.environ.get("ALPACA_API_KEY")
API_SECRET = os.environ.get("ALPACA_SECRET_KEY")
TARGET_SHARES = int(os.environ.get("TARGET_SHARES", "500"))
# Model parameters, not broker-specific fee schedules.
ASSUMED_TAKER_FEE_BPS = float(os.environ.get("TAKER_FEE_BPS", "0.5"))
ASSUMED_MAKER_FEE_BPS = float(os.environ.get("MAKER_FEE_BPS", "0.0"))
URGENCY_COST_PER_SHARE_SEC = float(
os.environ.get("URGENCY_COST_PER_SHARE_SEC", "0.0005")
)
MAX_SPREAD_BPS = float(os.environ.get("MAX_SPREAD_BPS", "8"))
MAX_QUOTE_AGE_SEC = float(os.environ.get("MAX_QUOTE_AGE_SEC", "2.0"))
PASSIVE_HORIZON_SEC = float(os.environ.get("PASSIVE_HORIZON_SEC", "10.0"))
BREAKOUT_LOOKBACK = int(os.environ.get("BREAKOUT_LOOKBACK", "40"))
PARTICIPATION_CAP = float(os.environ.get("PARTICIPATION_CAP", "0.25"))
if not API_KEY or not API_SECRET:
raise RuntimeError(
"Set ALPACA_API_KEY and ALPACA_SECRET_KEY before starting the monitor."
)
if TARGET_SHARES <= 0:
raise ValueError("TARGET_SHARES must be positive.")
if WS_FEED not in {"sip", "iex"}:
raise ValueError("ALPACA_FEED must be either 'sip' or 'iex'.")
@dataclass(frozen=True)
class Quote:
symbol: str
bid: float
ask: float
bid_size: int
ask_size: int
received_at: float
@dataclass(frozen=True)
class Trade:
symbol: str
price: float
size: int
exchange: str
timestamp: float
@dataclass(frozen=True)
class EntryDecision:
policy: str
limit_price: float
fill_probability: float
expected_shortfall_per_share: float
estimated_delay_sec: float
reason: str
def parse_provider_timestamp(value: str) -> float:
"""Convert Alpaca's RFC3339 timestamp to Unix seconds."""
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
return dt.timestamp()
class MarketState:
"""Maintains normalized quotes, trades, and a simple breakout signal."""
def __init__(self) -> None:
self.last_quote: Quote | None = None
self.trades: Deque[Trade] = deque(maxlen=1_000)
self.imbalance_history: Deque[float] = deque(maxlen=100)
self.position_open = False
def on_quote(self, message: dict) -> None:
if message.get("T") != "q":
return
bid = float(message["P"])
ask = float(message["p"])
bid_size = int(message["S"])
ask_size = int(message["s"])
if bid <= 0 or ask <= 0 or bid >= ask:
return
quote = Quote(
symbol=message["S"],
bid=bid,
ask=ask,
bid_size=bid_size,
ask_size=ask_size,
received_at=time.time(),
)
self.last_quote = quote
total_size = bid_size + ask_size
imbalance = (
(bid_size - ask_size) / total_size if total_size > 0 else 0.0
)
self.imbalance_history.append(imbalance)
def on_trade(self, message: dict) -> None:
if message.get("T") != "t":
return
self.trades.append(
Trade(
symbol=message["S"],
price=float(message["p"]),
size=int(message["s"]),
exchange=message.get("x", ""),
timestamp=parse_provider_timestamp(message["t"]),
)
)
def has_breakout(self) -> bool:
if self.position_open or len(self.trades) < BREAKOUT_LOOKBACK + 1:
return False
last = self.trades[-1]
prior = list(self.trades)[-BREAKOUT_LOOKBACK - 1 : -1]
return bool(prior) and last.price > max(t.price for t in prior)
def recent_trade_rate(self) -> float:
"""Return shares per second arriving at or through the bid."""
quote = self.last_quote
if quote is None:
return 0.0
cutoff = time.time() - 5.0
at_bid = [
trade
for trade in self.trades
if trade.timestamp >= cutoff and trade.price <= quote.bid + 1e-9
]
return sum(trade.size for trade in at_bid) / 5.0
def per_second_volatility(self) -> float:
"""Estimate short-horizon price volatility per second."""
recent = list(self.trades)[-200:]
if len(recent) < 3:
return 0.0
returns = []
elapsed = []
for previous, current in zip(recent, recent[1:]):
if previous.price <= 0:
continue
returns.append(math.log(current.price / previous.price))
elapsed.append(
max(current.timestamp - previous.timestamp, 1e-6)
)
if len(returns) < 2:
return 0.0
raw_std = statistics.pstdev(returns)
mean_seconds = statistics.fmean(elapsed)
return raw_std / math.sqrt(mean_seconds)
class EntryPolicy:
"""Compares aggressive and passive entry policies."""
def __init__(self, state: MarketState) -> None:
self.state = state
def passive_fill_probability(self) -> float:
quote = self.state.last_quote
if quote is None:
return 0.0
arrival_rate = self.state.recent_trade_rate()
expected_volume = (
arrival_rate * PASSIVE_HORIZON_SEC * PARTICIPATION_CAP
)
if expected_volume <= 0:
return 0.0
# Normal approximation to the volume needed to clear the queue.
z_score = (
expected_volume - quote.bid_size - 0.5
) / math.sqrt(expected_volume)
probability = 0.5 * (1.0 + math.erf(z_score / math.sqrt(2.0)))
return max(0.0, min(1.0, probability))
def market_impact(self, mid: float, ask_size: int) -> float:
"""Conservative heuristic for consuming more than displayed ask size."""
if ask_size <= 0:
return mid * 0.0005
participation = TARGET_SHARES / ask_size
if participation <= 1.0:
return 0.0
impact_bps = min(25.0, 5.0 * (participation - 1.0))
return mid * impact_bps / 10_000.0
def evaluate(self) -> EntryDecision:
quote = self.state.last_quote
if quote is None:
raise RuntimeError("No NBBO quote is available.")
quote_age = time.time() - quote.received_at
if quote_age > MAX_QUOTE_AGE_SEC:
return EntryDecision(
policy="WAIT",
limit_price=0.0,
fill_probability=0.0,
expected_shortfall_per_share=0.0,
estimated_delay_sec=0.0,
reason=f"Quote age {quote_age:.3f}s exceeds limit.",
)
mid = (quote.bid + quote.ask) / 2.0
spread_bps = (quote.ask - quote.bid) / mid * 10_000.0
if spread_bps > MAX_SPREAD_BPS:
return EntryDecision(
policy="WAIT",
limit_price=0.0,
fill_probability=0.0,
expected_shortfall_per_share=0.0,
estimated_delay_sec=0.0,
reason=f"Spread {spread_bps:.2f} bps exceeds limit.",
)
taker_fee = mid * ASSUMED_TAKER_FEE_BPS / 10_000.0
maker_fee = mid * ASSUMED_MAKER_FEE_BPS / 10_000.0
impact = self.market_impact(mid, quote.ask_size)
# A passive fill may occur after the midpoint moves against the order.
volatility_per_sec = self.state.per_second_volatility()
adverse_penalty = max(
(quote.ask - quote.bid) * 0.25,
mid * volatility_per_sec * math.sqrt(PASSIVE_HORIZON_SEC),
)
fill_probability = self.passive_fill_probability()
passive_delay = (
fill_probability * PASSIVE_HORIZON_SEC / 2.0
+ (1.0 - fill_probability) * PASSIVE_HORIZON_SEC
)
passive_fill_cost = (
mid - quote.bid + adverse_penalty + maker_fee
)
passive_shortfall = (
fill_probability * passive_fill_cost
+ URGENCY_COST_PER_SHARE_SEC * passive_delay
)
aggressive_shortfall = (
quote.ask - mid
+ taker_fee
+ impact
+ URGENCY_COST_PER_SHARE_SEC * 0.2
)
if passive_shortfall <= aggressive_shortfall:
return EntryDecision(
policy="PASSIVE",
limit_price=quote.bid,
fill_probability=fill_probability,
expected_shortfall_per_share=passive_shortfall,
estimated_delay_sec=passive_delay,
reason="Passive expected shortfall is lower.",
)
return EntryDecision(
policy="AGGRESSIVE",
limit_price=quote.ask,
fill_probability=0.98,
expected_shortfall_per_share=aggressive_shortfall,
estimated_delay_sec=0.2,
reason="Aggressive expected shortfall is lower.",
)
async def run_monitor() -> None:
state = MarketState()
policy = EntryPolicy(state)
retry_attempt = 0
while True:
try:
async with websockets.connect(
WS_URL,
ping_interval=20, # Protocol-level ping/pong heartbeat.
ping_timeout=20,
close_timeout=5,
max_queue=1_024,
) as websocket:
await websocket.send(
json.dumps(
{
"action": "auth",
"key": API_KEY,
"secret": API_SECRET,
}
)
)
await websocket.send(
json.dumps(
{
"action": "subscribe",
"quotes": [SYMBOL],
"trades": [SYMBOL],
}
)
)
retry_attempt = 0
print(f"Subscribed to {SYMBOL} on the {WS_FEED.upper()} feed.")
while True:
raw_message = await asyncio.wait_for(
websocket.recv(), timeout=45
)
message = json.loads(raw_message)
if message.get("stream") == "authorization":
print("Authorization confirmed.")
continue
if message.get("stream") == "list_subscriptions":
print("Subscriptions confirmed.")
continue
state.on_quote(message)
state.on_trade(message)
if state.has_breakout():
decision = policy.evaluate()
print(
json.dumps(
{
"symbol": SYMBOL,
"signal": "breakout",
"decision": decision.__dict__,
"target_shares": TARGET_SHARES,
},
indent=2,
)
)
# Mark the paper position as filled only for demonstration.
# Replace this with order-state reconciliation in production.
state.position_open = True
except ConnectionClosed as exc:
print(
f"Connection closed: code={exc.code}, reason={exc.reason}"
)
if exc.code in {40103, 40104}:
# Alpaca subscription/rate limits: slow down before reconnecting.
await asyncio.sleep(30)
retry_attempt += 1
continue
delay = min(1.0 * (2 ** retry_attempt), 60.0)
delay += random.uniform(0.0, delay * 0.1)
await asyncio.sleep(delay)
retry_attempt += 1
except asyncio.TimeoutError:
print("No message received within the timeout; reconnecting.")
delay = min(1.0 * (2 ** retry_attempt), 60.0)
delay += random.uniform(0.0, delay * 0.1)
await asyncio.sleep(delay)
retry_attempt += 1
except Exception as exc:
print(f"Unexpected monitor error: {exc!r}")
delay = min(1.0 * (2 ** retry_attempt), 60.0)
delay += random.uniform(0.0, delay * 0.1)
await asyncio.sleep(delay)
retry_attempt += 1
if __name__ == "__main__":
try:
asyncio.run(run_monitor())
except KeyboardInterrupt:
print("Monitor stopped.")
Production considerations in the implementation
The reconnect path uses exponential backoff with jitter, which prevents multiple workers from reconnecting simultaneously after a venue or provider interruption. The WebSocket transport also sends periodic protocol-level ping frames and treats a prolonged message silence as a broken session.
The rate-limit branch slows reconnects for Alpaca subscription-limit close codes. A production service should additionally expose connection state, reconnection count, quote age, and decision latency as operational metrics.
The position_open flag in the example is intentionally simple. A live implementation should reconcile that state against the broker or order management system. If an order is rejected, partially filled, or canceled, the strategy must receive the corresponding state transition rather than relying on the local flag.
6. Using Order Book Size Without Misinterpreting It
Top-of-book size can support a simple imbalance measure:
[
imbalance_t = \frac{bid_size_t - ask_size_t}
{bid_size_t + ask_size_t}
]
A value near (+1) indicates more displayed size at the bid, while a value near (-1) indicates more displayed size at the ask. The metric is useful as a conditioning variable, but it is not a direct measure of buying or selling pressure.
The interpretation breaks down when:
- A large bid quote is canceled immediately after it appears.
- One venue displays a quote that another venue can improve.
- The displayed size is replenished repeatedly without trades occurring.
- The quote update crosses a network boundary but the trade occurred earlier.
- The strategy treats size as executable even though it only becomes available after a queue clears.
A robust implementation therefore uses quote size in combination with trade confirmation, quote persistence, and realized fill outcomes. It should not classify a single large resting order as institutional buying.
Quote update frequency as a diagnostic
An execution monitor should track the time between consecutive NBBO updates. A sudden collapse in update frequency can indicate a feed interruption, a symbol halt, or a loss of venue connectivity.
Useful diagnostics include:
| Metric | Operational question |
|---|---|
| Quote age | Is the decision based on current information? |
| Update interval | Is the feed delivering expected granularity? |
| Spread distribution | Has the spread widened because of stress or stale data? |
| Trade-to-quote lag | Are trades and quotes aligned in time? |
| Decision-to-fill latency | How much of the signal remains after execution? |
| Cancel ratio | Are observed quotes surviving long enough to matter? |
These metrics also help distinguish a genuine liquidity withdrawal from a data-quality problem.
7. Historical Baselines and TickDB Capability Boundaries
Historical bars can establish when a trend signal is historically active, but they cannot reconstruct a fill probability that depends on NBBO states and queue order. The data requirements are therefore more demanding than an ordinary OHLCV backtest.
TickDB supports historical US equity OHLCV through the completed-period kline endpoint. The following example retrieves daily bars with environment-variable authentication, request timeouts, and handling for TickDB's rate-limit response:
import os
import time
import requests
API_KEY = os.environ.get("TICKDB_API_KEY")
if not API_KEY:
raise RuntimeError("Set TICKDB_API_KEY before requesting market data.")
URL = "https://api.tickdb.ai/v1/market/kline"
def fetch_kline(symbol: str, interval: str = "1d", limit: int = 5_000):
response = requests.get(
URL,
headers={"X-API-Key": API_KEY},
params={
"symbol": symbol,
"interval": interval,
"limit": limit,
},
timeout=(3.05, 20),
)
payload = response.json()
if response.status_code == 429 or payload.get("code") == 3001:
retry_after = int(response.headers.get("Retry-After", "5"))
time.sleep(retry_after)
return fetch_kline(symbol, interval, limit)
if payload.get("code") != 0:
raise RuntimeError(
f"TickDB request failed: "
f"{payload.get('code')} — {payload.get('message')}"
)
return payload.get("data")
bars = fetch_kline("AAPL.US", interval="1d", limit=2_000)
This dataset can support several useful analyses:
- Time-of-day trend activity by session bucket.
- Historical breakout frequency for a given universe.
- Regime filters based on daily range or realized volatility.
- Liquidity-proxy comparisons using bar volume and range.
- Baseline comparisons between trend and mean-reversion regimes.
However, historical US equity bars cannot reconstruct historical NBBO snapshots, queue position, quote staleness, or realized market impact. TickDB also does not support US equity tick-level trades or multi-level US depth beyond the limits of its US depth channel. A quote-aware execution backtest therefore requires archived consolidated quote and trade data from a provider that retains them.
The correct workflow is to separate the two experiments:
- Signal backtest: Evaluate the trend rule with historical OHLCV data.
- Execution backtest: Replay archived NBBO and trade events through the entry-policy model.
- Parameter validation: Join the signal outcomes with estimated implementation shortfalls rather than assuming a constant slippage deduction.
Keeping the experiments separate prevents an unrealistic fill model from being hidden inside a favorable signal result.
8. Backtest Design and Disclosure Requirements
An NBBO-aware backtest should preserve the sequence of quote and trade events. Basing the simulation only on daily bars can turn a realistic asynchronous execution system into an idealized one.
A defensible design requires several explicit assumptions. The framework must state the consolidated quote source, venue coverage, timestamp normalization, and quote replacement rules. It should document the order-book queue model, trade-order assumptions, cancellation treatment, and available-liquidity caps. Furthermore, the design must define the order size, participation cap, child-order logic, and fee and rebate assumptions. Finally, it must capture the stale-quote threshold, maximum spread constraint, rejected-order policy, and latency between decision, order submission, and exchange acknowledgement.
At minimum, the report should include the following fields:
| Metric | Purpose |
|---|---|
| Test period | Establishes the regime coverage |
| Sample size | Measures the number of independent signals |
| Gross and net win rate | Separates signal quality from execution cost |
| Profit factor | Measures payoff asymmetry |
| Sharpe and Sortino ratios | Evaluate risk-adjusted return |
| Maximum drawdown | Captures the worst capital path |
| Buy-and-hold and sector benchmarks | Separate strategy value from market direction |
| Average and tail slippage | Detects hidden execution degradation |
| Fill-rate distribution | Measures passive-order behavior |
| Adverse-selection cost | Quantifies the cost of passive fills |
Backtest limitations: A simulated NBBO execution result does not guarantee live performance. Queue position, order cancellation, venue latency, hidden liquidity, partial fills, and price movement can all differ from the historical reconstruction. Any published result should state the sample period, symbol universe, cost assumptions, fill model, and out-of-sample period. Extended validation on archived quote and trade data is required before capital is allocated.
9. Deployment Guide
The operational design changes with the scale of the trading operation.
| User segment | Recommended setup | Primary constraint |
|---|---|---|
| Individual developer | One consolidated quote stream, paper orders, simple policy | API costs, feed latency, and limited capital |
| Independent systematic trader | Consolidated NBBO plus trades, replay engine, daily model calibration | Queue-model accuracy |
| Small quantitative team | Redundant streams, shared signal bus, centralized order state | Operational consistency across workers |
| Institutional team | Licensed low-latency feeds, co-location execution, full event replay | Infrastructure cost and venue-level modeling |
Recommended rollout sequence
A controlled rollout begins with data validation, which requires recording raw quote and trade events with exchange timestamps, receipt timestamps, and venue identifiers. The next phase covers policy simulation, replaying historical events while keeping signal generation and execution evaluation separate. Signal-only validation then measures the trend rule without execution assumptions to ensure the underlying signal has an edge. Following this, cost calibration estimates realized slippage by spread bucket, quote age, time of day, order size, and volatility regime. Live paper trading tests the complete order lifecycle, including rejections, partial fills, cancellations, and reconnects. Finally, limited live deployment should begin with a small size while the implementation compares modeled and realized execution shortfalls.
The most important production metric is not fill rate. Fill rate can be improved by placing more aggressive orders, but that may reduce net performance. The decisive metric is net implementation shortfall relative to the price available when the signal became actionable.
10. Closing
At 10:03:17, the cheapest displayed price is not automatically the best entry price. The relevant price is the one that balances spread cost, fill probability, queue risk, adverse selection, and the cost of waiting.
For US equity trend strategies, the NBBO transforms execution from a static rule such as “buy at the ask” into a state-dependent decision. A tight, fresh, deep quote may justify crossing the spread. A wide but stable quote may favor passive placement. A stale or unstable quote may justify standing aside.
TickDB’s historical US equity kline data can support signal and regime research, while a consolidated real-time NBBO feed supplies the quote state required for live entry selection. The two resources answer different questions: bars describe what happened, and the NBBO describes what the market was offering at the instant the decision was made.
Next Steps
If you want to study historical US equity regimes, sign up at tickdb.ai, generate an API key, set the TICKDB_API_KEY environment variable, and use the kline example to build a signal and time-of-day baseline.
If you need institutional historical coverage, contact [email protected] for plan details and data availability.
If you use AI coding assistants, search for and install the tickdb-market-data SKILL in your tool’s marketplace.
If you are building a live execution stack, begin with archived consolidated NBBO and trade replay. Validate the queue model against realized fills before connecting the policy engine to a broker.
This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results.