Live Slippage Monitoring: Alerting When Execution Deviates from Signal
A trade can be technically correct and still lose money. The strategy may identify the right direction, the order may arrive at the right moment, and the position may eventually reach its target—but the entry can still be filled materially away from the signal price.
That gap is slippage, and it is one of the most dangerous discrepancies between a backtest and live execution. A strategy that assumes fills at the displayed price may look attractive on paper while producing poor live results after spreads, queue position, partial fills, fees, and market impact are included.
Real-time slippage monitoring turns this hidden execution cost into an observable engineering signal. The system compares each execution with a clearly defined reference price, aggregates the differences over a rolling window, and alerts when adverse slippage persists beyond a defined threshold.
1. The Problem: A Correct Signal Can Produce the Wrong Return
A backtest often assumes that a market order fills at the last traded price or at the mid-price shown in the snapshot used to generate the signal. Live markets rarely provide that guarantee. The order may cross a wider spread, wait behind existing queue priority, or execute in several partial fills as liquidity disappears.
The result is a silent difference between expected and realized entry quality:
Expected entry: 100.00
Actual fill: 100.09
Direction: Buy
Slippage: 9 bps
For a long position, the 9-basis-point difference may be small in isolation, but it compounds across repeated entries and exits. It also becomes more difficult to distinguish genuine market movement from an execution-system problem.
A useful live monitor must answer four separate questions:
- What price did the strategy use when it generated the signal?
- What price did the broker actually fill?
- How adverse was the difference, relative to the trade direction?
- Is the difference isolated, persistent, or statistically unusual?
The monitor should not treat every price movement as slippage. If the market moves 20 bps between signal generation and order submission, part of the difference belongs to signal staleness rather than broker execution. Separating those effects is essential for actionable alerts.
2. Slippage Measurement: Definitions and Units
2.1 The basic formula
For a buy order, adverse slippage is:
[
\text{Slippage}{buy} = \frac{P{fill} - P_{signal}}{P_{signal}}
]
For a sell order, the direction reverses:
[
\text{Slippage}{sell} = \frac{P{signal} - P_{fill}}{P_{signal}}
]
Both formulas can be expressed in basis points:
[
\text{SlippageBps} = 10{,}000 \times \text{Slippage}
]
A unified implementation is:
def calculate_slippage_bps(signal_price, fill_price, side):
if signal_price <= 0:
raise ValueError("signal_price must be positive")
if side.lower() == "buy":
return (fill_price - signal_price) / signal_price * 10_000
if side.lower() == "sell":
return (signal_price - fill_price) / signal_price * 10_000
raise ValueError("side must be 'buy' or 'sell'")
With this convention:
- Positive values indicate adverse execution.
- Zero indicates an exact fill.
- Negative values indicate a favorable fill.
The sign convention is important. Storing a raw price difference without the trade direction makes buy and sell statistics incomparable.
2.2 Choose the reference price carefully
The phrase “slippage versus the signal price” hides several different measurements. A production system should label the reference explicitly.
| Reference | What it measures | Main limitation |
|---|---|---|
| Last trade price | Difference between the signal and the observed trade print | A stale or moving last trade can distort execution quality |
| Best bid/ask | Difference between the signal and the executable side of the quote | Does not capture queue position or depth depletion |
| Mid-price | Difference between the signal and the midpoint of the market | Mid-price is not necessarily executable |
| Arrival price | Difference between the benchmark and the price when the order reaches the venue | Requires reliable arrival timestamps |
| Volume-weighted fill price | Difference between the benchmark and the average execution price | Must aggregate partial fills correctly |
A practical monitoring system usually maintains two measurements:
- Signal slippage: fill price versus the strategy’s decision price.
- Market slippage: fill price versus the contemporaneous executable quote or arrival benchmark.
The first answers whether the strategy is stale. The second answers whether the execution path is unusually expensive.
2.3 Partial fills require weighted aggregation
A single order may produce multiple executions. The monitor should aggregate those fills using a quantity-weighted average price:
[
P_{fill,weighted} =
\frac{\sum_i Q_i P_i}{\sum_i Q_i}
]
For example:
| Fill | Quantity | Price | Weighted contribution |
|---|---|---|---|
| Fill 1 | 100 | 100.06 | 10,006 |
| Fill 2 | 200 | 100.10 | 20,020 |
| Fill 3 | 50 | 100.12 | 5,006 |
| Total | 350 | 100.1043 | 35,032 |
The order’s effective fill price is 100.1043, not the price of the final partial fill. Using only the last fill would distort both the slippage statistic and the alert.
2.4 Include costs separately
Slippage and transaction costs should not be merged into one opaque number. Track at least:
- Spread-related execution difference
- Slippage against the selected benchmark
- Broker commission or exchange fees
- Market-impact proxy, where observable
- Rebate or fee adjustment, if applicable
This separation helps distinguish an expensive trading strategy from an inefficient execution configuration.
3. From Individual Fill to Rolling-Window Signal
A single large fill may reflect a market shock, a wide spread, or a data-processing delay. It does not necessarily indicate a broken execution path. A monitor therefore needs both absolute and relative thresholds.
3.1 Absolute threshold
The absolute rule is straightforward:
Alert when adverse slippage over the rolling window exceeds X bps.
For example:
Alert when the 20-fill weighted mean adverse slippage exceeds 8 bps.
The threshold should be calibrated by instrument, venue, order type, and time of day. A fixed 8-basis-point threshold may be aggressive for a highly liquid large-cap stock during normal trading hours but meaningless for a thin cryptocurrency pair.
3.2 Statistical threshold
A z-score identifies slippage that is unusual relative to the strategy’s own recent history:
[
z_t = \frac{\mu_t - \mu_{baseline}}{\sigma_{baseline}}
]
The rolling mean (\mu_t) can use recent executions, while the baseline distribution should exclude known event windows or already-alerting periods. Otherwise, a persistent regime shift can gradually normalize into the baseline and hide the problem.
A practical rule is:
Alert when mean adverse slippage exceeds 8 bps
AND the z-score exceeds 2.5
AND at least 5 of the last 10 fills were adverse.
3.3 Persistence and cooldown
Production alerts need two additional controls:
- Persistence requirement: The breach must occur across multiple observations.
- Cooldown window: Repeated alerts must not flood the incident channel while the same condition remains active.
| Control | Example purpose |
|---|---|
| Minimum sample size | Prevent alerts from two or three fills |
| Consecutive breaches | Require the condition to persist |
| Cooldown | Suppress duplicate alerts for 10 minutes |
| Recovery condition | Clear the incident only after slippage returns below the threshold |
A typical incident lifecycle is:
NORMAL → WARNING → CRITICAL → RECOVERING → NORMAL
The system should retain the first breach, maximum observed slippage, affected symbols, and the orders responsible for the incident.
4. Production Architecture
The monitor should separate signal state, broker events, aggregation, and incident delivery. This separation keeps the execution path testable and allows the alert policy to change without modifying a broker adapter.
┌─────────────────────┐
│ Strategy Engine │
│ signal price/side │
└──────────┬──────────┘
│ signal event
▼
┌─────────────────────┐
│ Signal Registry │
│ timestamp / price │
│ order correlation ID│
└──────────┬──────────┘
│
│ ┌─────────────────────┐
│ │ Broker API │
│ │ REST + WebSocket │
│ │ orders/fills/quotes │
│ └──────────┬──────────┘
│ │ fill events
└─────────────────┬──────────────────┘
▼
┌─────────────────────┐
│ Execution Matcher │
│ weighted fills │
│ side-adjusted bps │
└──────────┬──────────┘
▼
┌─────────────────────┐
│ Rolling Aggregator │
│ mean / z-score │
│ persistence rules │
└──────────┬──────────┘
▼
┌─────────────────────┐
│ Alert Manager │
│ dedupe / cooldown │
│ webhook / chat │
└─────────────────────┘
4.1 Correlation is the critical design decision
The signal and fill must share a durable correlation identifier. A symbol and timestamp are insufficient because a strategy may issue several orders for the same symbol within a short interval.
Use a broker-compatible client order ID or a locally generated ID that is propagated through the order request:
signal_id = "sig_01J..."
client_order_id = "sig_01J..."
broker_order_id = "broker-generated-id"
The matcher should maintain a bounded TTL registry:
- Add the signal when the order is submitted.
- Match fills by
client_order_id. - Aggregate fills until the order reaches a terminal state.
- Expire unmatched signals after a configurable period.
4.2 The reference feed
A broker fill event is the authoritative source for actual execution price. The reference feed provides the benchmark used to interpret that fill. The system should store both timestamps:
signal_ts = when the strategy made its decision
submit_ts = when the order was sent
arrival_ts = when the broker reports the order reached the venue
fill_ts = when the execution occurred
The intervals between these timestamps help distinguish:
- A slow strategy or execution gateway
- A long order-acknowledgment delay
- Queue-position effects
- Rapid market movement during the order’s lifetime
- Venue or broker-side execution anomalies
5. Production-Grade Monitoring Code
The following Python example implements the core monitoring loop. It assumes the broker exposes a WebSocket that emits normalized fill events and an HTTP endpoint for order submission. The event schema is isolated in parse_broker_message, so broker-specific field names can be adapted without changing the matching or alerting logic.
Install the required packages:
pip install aiohttp
import asyncio
import json
import logging
import os
import random
import time
import uuid
from collections import defaultdict, deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
import aiohttp
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
LOGGER = logging.getLogger("slippage-monitor")
BROKER_API_KEY = os.environ.get("BROKER_API_KEY")
BROKER_WS_URL = os.environ.get("BROKER_WS_URL")
BROKER_REST_URL = os.environ.get("BROKER_REST_URL")
ALERT_WEBHOOK_URL = os.environ.get("ALERT_WEBHOOK_URL")
if not all([BROKER_API_KEY, BROKER_WS_URL, BROKER_REST_URL]):
raise RuntimeError(
"BROKER_API_KEY, BROKER_WS_URL, and BROKER_REST_URL are required"
)
HEARTBEAT_SECONDS = 20
MAX_BACKOFF_SECONDS = 60
SIGNAL_TTL_SECONDS = 120
ROLLING_WINDOW_SIZE = 20
ABS_THRESHOLD_BPS = 8.0
ZSCORE_THRESHOLD = 2.5
MIN_PERSISTENT_BREACHES = 2
ALERT_COOLDOWN_SECONDS = 600
@dataclass
class Signal:
signal_id: str
symbol: str
side: str
signal_price: float
signal_ts: float
order_id: str | None = None
fills: list[dict] = field(default_factory=list)
@dataclass
class OrderObservation:
slippage_bps: float
observed_at: float
def calculate_slippage_bps(signal_price: float, fill_price: float, side: str) -> float:
if signal_price <= 0:
raise ValueError("signal_price must be positive")
if fill_price <= 0:
raise ValueError("fill_price must be positive")
side = side.lower()
if side == "buy":
return (fill_price - signal_price) / signal_price * 10_000
if side == "sell":
return (signal_price - fill_price) / signal_price * 10_000
raise ValueError(f"Unsupported side: {side}")
def weighted_fill_price(fills: list[dict]) -> float:
total_quantity = sum(float(fill["quantity"]) for fill in fills)
if total_quantity <= 0:
raise ValueError("Cannot calculate a weighted price without quantity")
notional = sum(
float(fill["quantity"]) * float(fill["price"])
for fill in fills
)
return notional / total_quantity
def parse_broker_message(message: dict) -> dict | None:
"""Map a broker-specific fill payload to the internal event schema."""
if message.get("type") not in {"fill", "execution"}:
return None
return {
"client_order_id": message.get("client_order_id"),
"broker_order_id": message.get("order_id"),
"symbol": message.get("symbol"),
"side": message.get("side"),
"quantity": message.get("quantity"),
"price": message.get("price"),
"timestamp": message.get("timestamp"),
"terminal": bool(message.get("terminal", False)),
}
class SignalRegistry:
def __init__(self):
self._signals: dict[str, Signal] = {}
def add(self, signal: Signal):
self._signals[signal.signal_id] = signal
def get_by_client_order_id(self, client_order_id: str) -> Signal | None:
for signal in self._signals.values():
if signal.order_id == client_order_id:
return signal
return None
def expire(self, now: float):
expired = [
signal_id
for signal_id, signal in self._signals.items()
if now - signal.signal_ts > SIGNAL_TTL_SECONDS
]
for signal_id in expired:
del self._signals[signal_id]
class RollingSlippageTracker:
def __init__(self, symbol: str):
self.symbol = symbol
self.observations: deque[OrderObservation] = deque(
maxlen=ROLLING_WINDOW_SIZE
)
self.breach_count = 0
self.last_alert_at = 0.0
def update(self, slippage_bps: float, now: float) -> dict:
self.observations.append(
OrderObservation(slippage_bps=slippage_bps, observed_at=now)
)
values = [item.slippage_bps for item in self.observations]
mean_slippage = sum(values) / len(values)
if len(values) >= 2:
variance = sum((value - mean_slippage) ** 2 for value in values) / (
len(values) - 1
)
std_dev = variance ** 0.5
zscore = (
(mean_slippage - mean_slippage) / std_dev
if std_dev > 0
else 0.0
)
else:
std_dev = 0.0
zscore = 0.0
# A rolling z-score requires a longer baseline than the live window.
# For a simple production baseline, maintain a separate historical
# distribution and pass its mean and standard deviation here.
absolute_breach = mean_slippage > ABS_THRESHOLD_BPS
statistical_breach = (
len(values) >= 10
and std_dev > 0
and mean_slippage / std_dev >= ZSCORE_THRESHOLD
)
persistence_breach = (
self.breach_count + 1 >= MIN_PERSISTENT_BREACHES
)
self.breach_count = (
self.breach_count + 1
if absolute_breach
else 0
)
should_alert = (
absolute_breach
and persistence_breach
and now - self.last_alert_at >= ALERT_COOLDOWN_SECONDS
)
return {
"symbol": self.symbol,
"mean_slippage_bps": round(mean_slippage, 3),
"absolute_breach": absolute_breach,
"statistical_breach": statistical_breach,
"should_alert": should_alert,
"sample_size": len(values),
}
class AlertManager:
async def send(self, payload: dict):
if not ALERT_WEBHOOK_URL:
LOGGER.warning("ALERT_WEBHOOK_URL is not configured")
return
timeout = aiohttp.ClientTimeout(total=10)
async with aiohttp.ClientSession(timeout=timeout) as session:
try:
async with session.post(
ALERT_WEBHOOK_URL,
json=payload,
) as response:
if response.status == 429:
retry_after = float(response.headers.get("Retry-After", "5"))
LOGGER.warning(
"Alert webhook rate limited; retrying in %.1fs",
retry_after,
)
await asyncio.sleep(retry_after)
return
response.raise_for_status()
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
LOGGER.error("Failed to deliver alert: %s", exc)
async def submit_order(
session: aiohttp.ClientSession,
signal_id: str,
symbol: str,
side: str,
quantity: float,
signal_price: float,
):
"""Submit an order through the broker REST API.
Replace /orders and the payload with the broker's documented fields.
The response must expose the broker order ID.
"""
headers = {
"Authorization": f"Bearer {BROKER_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"client_order_id": signal_id,
"symbol": symbol,
"side": side,
"quantity": quantity,
"order_type": "market",
"reference_price": signal_price,
}
timeout = aiohttp.ClientTimeout(total=15, connect=5)
async with session.post(
f"{BROKER_REST_URL.rstrip('/')}/orders",
headers=headers,
json=payload,
timeout=timeout,
) as response:
if response.status == 429:
retry_after = float(response.headers.get("Retry-After", "5"))
LOGGER.warning("Broker rate limit reached; waiting %.1fs", retry_after)
await asyncio.sleep(retry_after)
return None
response.raise_for_status()
body = await response.json()
return body.get("order_id")
async def broker_websocket(
registry: SignalRegistry,
trackers: dict[str, RollingSlippageTracker],
alerts: AlertManager,
):
retry = 0
while True:
try:
timeout = aiohttp.ClientTimeout(total=None, sock_connect=10)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.ws_connect(
BROKER_WS_URL,
params={"api_key": BROKER_API_KEY},
heartbeat=HEARTBEAT_SECONDS,
receive_timeout=None,
) as websocket:
LOGGER.info("Connected to broker WebSocket")
retry = 0
async for raw_message in websocket:
if raw_message.type == aiohttp.WSMsgType.TEXT:
try:
message = json.loads(raw_message.data)
event = parse_broker_message(message)
if event is None:
continue
signal = registry.get_by_client_order_id(
event["client_order_id"]
)
if signal is None:
LOGGER.warning(
"Unmatched fill: %s",
event["client_order_id"],
)
continue
signal.fills.append(event)
if event["terminal"]:
fill_price = weighted_fill_price(signal.fills)
slippage_bps = calculate_slippage_bps(
signal.signal_price,
fill_price,
signal.side,
)
tracker = trackers.setdefault(
signal.symbol,
RollingSlippageTracker(signal.symbol),
)
status = tracker.update(slippage_bps, time.time())
LOGGER.info(
"symbol=%s side=%s fill=%s "
"slippage_bps=%.3f mean_bps=%.3f",
signal.symbol,
signal.side,
round(fill_price, 6),
slippage_bps,
status["mean_slippage_bps"],
)
if status["should_alert"]:
tracker.last_alert_at = time.time()
await alerts.send({
"event": "slippage_threshold_breach",
**status,
"signal_id": signal.signal_id,
"side": signal.side,
"fill_price": fill_price,
"threshold_bps": ABS_THRESHOLD_BPS,
})
except (ValueError, KeyError, TypeError) as exc:
LOGGER.error("Invalid broker event: %s", exc)
elif raw_message.type == aiohttp.WSMsgType.ERROR:
raise RuntimeError("Broker WebSocket error")
except (
aiohttp.ClientError,
asyncio.TimeoutError,
RuntimeError,
) as exc:
retry += 1
delay = min(2 ** min(retry, 6), MAX_BACKOFF_SECONDS)
jitter = random.uniform(0, delay * 0.1)
LOGGER.warning(
"Broker connection failed (%s); reconnecting in %.2fs",
exc,
delay + jitter,
)
await asyncio.sleep(delay + jitter)
async def main():
registry = SignalRegistry()
trackers: dict[str, RollingSlippageTracker] = {}
alerts = AlertManager()
# Example signal. In production, the strategy engine calls this function
# immediately before submitting the order.
signal_id = str(uuid.uuid4())
signal = Signal(
signal_id=signal_id,
symbol="AAPL.US",
side="buy",
signal_price=100.00,
signal_ts=time.time(),
)
registry.add(signal)
timeout = aiohttp.ClientTimeout(total=15, connect=5)
async with aiohttp.ClientSession(timeout=timeout) as session:
order_id = await submit_order(
session,
signal.signal_id,
signal.symbol,
signal.side,
quantity=100,
signal_price=signal.signal_price,
)
if order_id:
signal.order_id = signal_id
LOGGER.info("Order submitted: signal_id=%s order_id=%s",
signal_id, order_id)
await broker_websocket(registry, trackers, alerts)
if __name__ == "__main__":
asyncio.run(main())
5.1 Engineering warnings
The implementation includes several controls that should not be removed in production:
- Environment-variable authentication: Credentials do not belong in source code or logs.
- Heartbeat: The WebSocket detects a dead connection before the next fill is missed.
- Exponential backoff with jitter: Reconnection attempts avoid synchronizing across workers.
- HTTP timeouts: A slow broker REST endpoint cannot block the event loop indefinitely.
- Rate-limit handling:
429responses honorRetry-After. - Bounded in-memory state: The rolling window prevents unbounded memory growth.
- Correlation IDs: Signals and fills remain associated even when several orders share a symbol.
The example uses a rolling mean as the primary trigger. For a production deployment, calculate the z-score against a separate historical baseline, segmented by symbol and execution session. Using the live rolling window’s own mean as both the numerator and denominator would make the z-score calculation invalid; the example marks that limitation explicitly rather than presenting a misleading statistic.
5.2 Broker-specific adaptation
Every broker uses different field names, authentication headers, event schemas, and rate-limit codes. The adapter boundary should contain those differences:
class BrokerAdapter:
async def submit_order(self, request):
raise NotImplementedError
async def stream_events(self):
raise NotImplementedError
def parse_event(self, payload):
raise NotImplementedError
Keep the slippage calculation, rolling-window policy, and alert lifecycle independent from the broker implementation. This reduces the risk that a vendor-specific message format leaks into strategy logic.
6. Broker API Integration and Operational Failure Modes
6.1 Connection and clock issues
A broker may report fills with exchange time, broker receipt time, or local receipt time. Store all three when available. If the clock domains differ, normalize them to UTC and estimate the residual offset.
Clock skew creates two distinct problems:
- A fill may appear before its signal due to timestamp ordering.
- The system may attribute market movement during a long delay to broker slippage.
Use a monotonic clock for internal durations. Use UTC timestamps for cross-system correlation.
6.2 Missing or duplicated events
WebSocket connections can reconnect after the client has missed one or more messages. A reliable fill stream should therefore support either:
- A cursor or sequence number for replay, or
- REST reconciliation after reconnection
After reconnecting, query recent orders and fills, reconcile them with the local registry, and then resume live processing. Deduplicate on a composite event key such as:
broker_order_id + fill_id
Do not deduplicate only by timestamp and price; two legitimate fills can share both.
6.3 Rate limits
Rate-limit behavior differs by broker and endpoint. The monitor should apply:
- Exponential backoff for transient failures
- Jitter for concurrent workers
Retry-Afterwhen the server provides it- Separate queues for order submission and fill reconciliation
- A bounded retry budget for non-idempotent requests
Before retrying an order submission, check whether the previous request succeeded. If the broker supports idempotency keys, use the signal ID as the idempotency key.
6.4 Partial fills and order state
An order may move through several states:
SUBMITTED → ACKNOWLEDGED → PARTIALLY_FILLED → FILLED
↘ CANCELLED
↘ REJECTED
Only completed or partially filled orders should contribute to realized execution statistics. Cancelled orders may still be useful for diagnosing latency, but their unfilled quantity must not be treated as an execution.
6.5 Alerts should describe causality
A weak alert says:
AAPL slippage too high
A useful alert says:
AAPL.US BUY slippage breached 8 bps.
Rolling 20-order mean: 11.4 bps.
Affected orders: 5.
Maximum observed slippage: 19.2 bps.
Average signal-to-submit latency: 84 ms.
Current spread estimate: 6 bps.
The second format gives the operator enough context to decide whether to inspect gateway latency, order type, venue routing, market conditions, or the strategy itself.
7. Historical Calibration and Live Context
A live threshold should be calibrated against the execution conditions the strategy actually experiences. Historical OHLCV data can help establish broad cost and volatility regimes, but it cannot reconstruct every fill-level queue interaction.
For completed historical periods, a cleaned and aligned OHLCV series can support broad regime analysis:
import os
import requests
API_KEY = os.environ.get("TICKDB_API_KEY")
if not API_KEY:
raise RuntimeError("TICKDB_API_KEY is required")
headers = {"X-API-Key": API_KEY}
response = requests.get(
"https://api.tickdb.ai/v1/market/kline",
headers=headers,
params={
"symbol": "AAPL.US",
"interval": "1h",
"limit": 1000,
},
timeout=(3.05, 10),
)
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", "5"))
print(f"Rate limited; retry after {retry_after} seconds")
elif not response.ok:
response.raise_for_status()
else:
payload = response.json()
if payload.get("code") == 0:
candles = payload.get("data", [])
print(f"Loaded {len(candles)} candles")
elif payload.get("code") in (1001, 1002):
raise ValueError("Check TICKDB_API_KEY")
elif payload.get("code") == 2002:
raise KeyError("Symbol not found; verify via /v1/symbols/available")
else:
raise RuntimeError(payload.get("message", "Unknown TickDB error"))
Historical candles can help compare live slippage with volatility and spread regimes, but they should not be presented as a substitute for broker execution records. The authoritative source for realized slippage remains the broker’s order and fill history.
Order-book depth can provide additional context where supported. Availability is market-specific: US equities expose L1 depth, while Hong Kong equities and crypto can expose multiple levels. Depth is not available for every asset class, so the monitor should treat the reference feed as an optional enrichment layer rather than a hard dependency.
7.1 Calibration procedure
A defensible calibration process has five steps:
- Define the benchmark for each instrument and order type.
- Collect at least several hundred completed executions under normal conditions.
- Segment by volatility and session, such as opening, midday, and closing windows.
- Set thresholds above normal tails, not merely above the average.
- Replay the rules against historical incidents and measure false-positive rate.
For example, if normal AAPL market-order execution has a 95th-percentile slippage of 4 bps, an 8-bps threshold may be reasonable as an initial warning level. It should then be adjusted after observing live behavior.
8. Deployment Guide
8.1 Recommended configurations
| Deployment profile | Window | Warning rule | Critical rule | Best use |
|---|---|---|---|---|
| Individual quant | 20 orders | 8 bps | 15 bps | Fast setup and basic oversight |
| Production strategy | 50 orders plus time window | Dynamic percentile | Absolute plus z-score | Stable, alert-controlled operation |
| Institutional desk | Symbol, venue, and order-type segments | Venue-specific | Multi-level threshold with manual incident routing | Cross-strategy execution governance |
A rolling order count alone can fail during inactivity. If only two orders occur in an hour, the metric may be stale. Combine the order window with a time window:
Include observations from the last 30 minutes,
but require at least 10 completed orders.
8.2 Alert routing
Use routing based on severity:
| Severity | Examples | Route |
|---|---|---|
| Warning | One threshold breach with limited persistence | Dashboard and development channel |
| Critical | Sustained breach, large maximum slippage, or partial-fill anomaly | Operations channel and on-call route |
| Emergency | Missing fills, duplicate execution, or unreconciled orders | Pager or equivalent incident system |
Do not send financial or execution alerts to a general marketing notification stream. A dedicated operations channel should preserve timestamps, symbols, order IDs, and incident links.
8.3 Testing the monitor
Use unit tests for the core calculations:
def test_buy_slippage():
assert calculate_slippage_bps(100.00, 100.08, "buy") == 800.0
def test_sell_slippage():
assert calculate_slippage_bps(100.00, 99.92, "sell") == 800.0
def test_favorable_fill():
assert calculate_slippage_bps(100.00, 99.99, "buy") < 0
Also test:
- Partial-fill weighting
- Order IDs with unusual characters
- Out-of-order WebSocket events
- Reconnect after a missed fill
- Duplicate broker events
- Threshold persistence and cooldown
- Clock skew
- Empty rolling windows
- Alert webhook timeouts and rate limits
The most valuable integration test replays a recorded broker event stream and verifies that the monitor produces exactly the expected incidents.
9. Closing and Next Steps
The fill price is where the backtest becomes real.
A robust live slippage monitor does more than compare two prices. It preserves signal context, aggregates partial fills, distinguishes adverse execution from market movement, applies a rolling policy, and alerts only when the evidence is persistent. That turns slippage from an invisible drag on returns into an actionable operational signal.
The implementation pattern remains the same across brokers:
capture the signal
→ submit with a correlation ID
→ receive and reconcile fills
→ calculate side-adjusted slippage
→ aggregate over a rolling window
→ suppress duplicate alerts
→ investigate latency, routing, spread, or strategy behavior
Next Steps
If you are monitoring an individual strategy, begin with a fixed basis-point threshold, a minimum sample size, and a cooldown period. Store raw signal prices, fills, timestamps, and order IDs before adding statistical alerts.
If you are building a production execution service, implement replayable broker-event reconciliation, idempotent order submission, per-symbol baselines, and separate signal-slippage and market-slippage measurements.
If you need historical market context for calibration, use the TickDB API with a valid TICKDB_API_KEY and compare completed-period OHLCV data with your broker’s execution records. The API supports 10+ years of cleaned and aligned US equity OHLCV for cross-cycle analysis.
If you operate a quant team, contact [email protected] to discuss institutional data and execution-monitoring requirements.
If you use AI coding assistants, search for and install the tickdb-market-data SKILL in your AI tool’s marketplace.
This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results.