“The order filled. The price did not match the signal.”

That mismatch is easy to miss when execution reporting shows only a completed order. The strategy generated a signal at $100.00, the broker reported a fill at $100.03, and the position looked correct in aggregate. Three basis points of adverse slippage had already vanished from the P&L.

Live execution contains several mechanical frictions: order-routing delays, exchange fees, partial fills, hidden liquidity, timestamp skew, and last-price versus bid-ask differences. Treating all of those movements as strategy alpha—or ignoring them entirely—distorts both attribution and risk management.

For systematic traders and execution engineers, the important question is operational: How large does live slippage need to be before it warrants attention, and how can that threshold become an automated alert instead of a post-trade spreadsheet exercise? This article defines the metrics, designs the monitoring architecture, and provides production-oriented Python for broker integration, alert delivery, and order-book context.

1. Slippage Is a Timestamp Problem Before It Is a Price Problem

A fill is not compared with an arbitrary later market price. It must be compared with the immutable reference price captured when the strategy generated the execution signal.

The core calculation is:

[
\text{Adverse slippage}_{bps}

\frac{
\text{signal price} - \text{weighted fill price}
}{
\text{signal price}
}
\times 10{,}000
\quad \text{for a buy}
]

For a sell, the numerator is reversed:

[
\text{Adverse slippage}_{bps}

\frac{
\text{weighted fill price} - \text{signal price}
}{
\text{signal price}
}
\times 10{,}000
]

This side-adjusted definition produces a consistent monitoring value:

  • Positive values indicate adverse execution.
  • Negative values indicate favorable execution.
  • Zero means the average fill matched the signal price.

The formula changes slightly for short positions because a higher fill is favorable, not adverse. Removing the side adjustment is one of the most common reporting errors in execution dashboards.

1.1 Define the Signal Price Before Production

The “signal price” must be captured at signal-generation time and stored with the order intent. It should not be reconstructed later from the most recent quote.

A valid signal record contains at least these fields:

Field Purpose
signal_id Correlates the signal with its execution lifecycle
symbol Canonical instrument identifier
side Buy or sell
signal_price Exact price used by the strategy
signal_timestamp Exchange-aware event timestamp
signal_source Midpoint, last trade, order-book level, or model output
order_id Broker identifier assigned after submission
strategy_id Enables attribution by strategy

The reference price should match the logic that generated the signal. If a strategy decides to buy when its midquote model reaches $100.00, the signal price is $100.00. Comparing that order with the last trade ten seconds later mixes two different market references.

1.2 Partial Fills Require an Aggregate View

The average fill across multiple executions determines the order-level slippage. A large favorable partial fill can hide an adverse later fill, while an adverse partial fill can disappear when the remaining quantity receives a better price.

For fills (i = 1 \ldots n), the weighted fill is:

[
\text{Weighted fill}

\frac{\sum_{i=1}^{n} P_iQ_i}{\sum_{i=1}^{n}Q_i}
]

Consider a buy order for 1,000 shares with a signal price of $100.00:

Execution Quantity Fill Price Fill-Level Slippage Cumulative Weighted Price
Signal 1,000 $100.00 — $100.00
Partial fill 1 100 $100.04 +4.0 bps $100.04
Partial fill 2 900 $100.01 +1.0 bps $100.012

The final order-level adverse slippage is only 1.2 bps:

[
\frac{100.012-100.000}{100.000}\times10{,}000=1.2\text{ bps}
]

This example demonstrates why the alert engine needs both fill-level and order-level views. Fill-level monitoring detects a problematic individual execution; order-level monitoring reports the actual completed cost.

2. What Magnitude of Slippage Should Trigger Action?

No universal slippage threshold exists. A five-basis-point move can be routine in a fragmented liquid market but severe in an illiquid order book. Volatility, order size, urgency, venue, and strategy holding period all affect the appropriate baseline.

A production monitor should combine three threshold types.

2.1 Absolute Thresholds

An absolute threshold provides a simple safety floor. The following policy is an illustrative starting point for liquid US equities, not a universal standard:

Adverse Slippage Default Classification Typical Response
Less than 5 bps Normal Record only
5–10 bps Watch Add to daily execution report
10–25 bps Warning Validate signal clock, routing, and order state
25 bps or more Critical Immediate alert and execution investigation
Persistent negative slippage Review opportunity Confirm pricing and fill completeness

The thresholds should be calibrated by symbol, strategy, order type, and time of day. Start broad, collect at least several hundred completed orders, and then narrow the policy using observed percentiles.

2.2 Distribution-Aware Thresholds

A fixed threshold misses the difference between normal and exceptional behavior for a specific strategy. The monitor should also compare each observation with its recent rolling distribution.

A basic implementation uses the rolling median and median absolute deviation:

[
MAD = median\left(|x_i - median(x)|\right)
]

[
\text{Robust z-score}

0.6745 \times
\frac{x - median(x)}{MAD}
]

The median and MAD are less sensitive to outliers than a mean and standard deviation. That matters because a single severe execution should not redefine the normal range for the following orders.

A practical policy is:

  • Warn at a robust z-score of 3 or higher.
  • Escalate at 4 or higher.
  • Require at least 30 historical observations before applying the statistical threshold.
  • Continue applying the absolute threshold even when the sample is small.

2.3 Absolute and Relative Thresholds Must Agree

The engine should alert when either the absolute or statistical threshold is crossed:

alert = adverse_slippage_bps >= absolute_threshold
        OR robust_z_score >= statistical_threshold

A large adverse move should always generate an event, even if the strategy’s recent history has been unusually favorable. Conversely, a statistically unusual result may deserve review even when it remains below the hard limit.

2.4 Separate Slippage from Total Execution Cost

Slippage does not include commissions, exchange fees, rebates, financing, or taxes. It describes the difference between the signal reference and the fill price.

Total implementation shortfall should be calculated separately:

[
\text{Implementation shortfall}

\text{adverse slippage}
+
\text{commissions and fees}
+
\text{other explicit costs}
]

A system can execute precisely at its signal price while still losing money after costs. Conversely, a small favorable fill can partially offset transaction fees. Mixing these measures makes strategy attribution unreliable.

3. Monitoring Architecture

The monitoring service should receive three inputs:

  1. The original signal or order intent.
  2. Broker order and fill state.
  3. Optional market context, including current order-book conditions.

The alert path should remain independent of strategy decision code. A monitoring failure must not prevent the strategy from submitting or canceling orders.

┌────────────────────┐
│ Signal generator   │
│ Stores signal price│
└─────────┬──────────┘
          │ order intent + signal_id
          ▼
┌────────────────────┐    ┌──────────────────────┐
│ Broker API adapter │───▶│ Normalized order     │
│ Orders / fills     │    │ and execution events │
└─────────┬──────────┘    └──────────┬───────────┘
          │                           │
          ▼                           ▼
┌────────────────────┐    ┌──────────────────────┐
│ Reconciliation     │───▶│ Slippage calculation │
│ and idempotency    │    │ and threshold engine │
└────────────────────┘    └──────────┬───────────┘
                                    │
                    ┌───────────────┴───────────────┐
                    ▼                               ▼
           ┌─────────────────┐             ┌──────────────────┐
           │ SQLite outbox   │             │ Market context   │
           │ and audit log   │             │ Depth / quotes   │
           └────────┬────────┘             └──────────────────┘
                    │
                    ▼
           ┌─────────────────┐
           │ Webhook / email │
           │ or incident API │
           └─────────────────┘

3.1 Pre-Execution: Persist the Signal

Before submitting the order, the strategy writes the signal record. The monitor joins this record to the broker’s order_id after acknowledgement.

The signal write should occur before or atomically with order submission. If the process crashes between those operations, the strategy needs enough information to reconcile the order rather than generating a duplicate.

3.2 During Execution: Reconcile Orders and Fills

The service polls the broker for changed orders and fills, then computes cumulative weighted slippage.

Every event needs an idempotency key. A safe key is:

broker_name + order_id + fill_id

Without deduplication, a retried API request can insert the same fill multiple times and inflate the monitored cost.

3.3 Post-Execution: Preserve the Evidence

The service stores the raw broker payload alongside the normalized fields. An alert without supporting evidence is difficult to investigate.

Persist at least:

  • Raw signal and order payloads.
  • Raw fill payloads.
  • Signal and fill timestamps.
  • Local receive timestamps.
  • Weighted fill price.
  • Adverse slippage in basis points.
  • Robust z-score.
  • Alert severity and delivery status.

4. Broker API Integration

Broker APIs differ in authentication, endpoint names, pagination, and order-status vocabularies. The monitoring service should therefore use a thin adapter that converts vendor-specific responses into a stable internal contract.

The following example assumes two normalized endpoints:

GET {BROKER_ORDERS_URL}?updated_since={timestamp}
GET {BROKER_FILLS_URL}?order_id={order_id}

Expected normalized fields are:

Entity Required Fields
Order order_id, symbol, side, signal_price, quantity, status, updated_at
Fill fill_id, order_id, price, quantity, executed_at

A production adapter must also map the broker’s authentication scheme. The sample uses a bearer token, but some brokers require a custom header or query parameter.

4.1 Production-Grade Monitoring Service

The following service demonstrates the complete control loop:

  • Environment-variable authentication.
  • Timeouts on every HTTP request.
  • Rate-limit handling through 3001 and Retry-After.
  • Exponential backoff with jitter.
  • Idempotent SQLite storage.
  • A persistent alert outbox.
  • Terminal and partial-fill thresholds.
  • Robust z-score detection.
import json
import os
import random
import sqlite3
import statistics
import time
from decimal import Decimal

import requests


BASE_URL = os.environ["BROKER_BASE_URL"].rstrip("/")
ORDERS_URL = os.environ.get(
    "BROKER_ORDERS_URL",
    f"{BASE_URL}/monitor/orders",
)
FILLS_URL = os.environ.get(
    "BROKER_FILLS_URL",
    f"{BASE_URL}/monitor/fills",
)
API_KEY = os.environ["BROKER_API_KEY"]
ALERT_WEBHOOK_URL = os.environ.get("ALERT_WEBHOOK_URL", "")

WARN_BPS = float(os.getenv("SLIPPAGE_WARN_BPS", "10"))
CRITICAL_BPS = float(os.getenv("SLIPPAGE_CRITICAL_BPS", "25"))
POLL_SECONDS = float(os.getenv("SLIPPAGE_POLL_SECONDS", "1"))
TERMINAL_STATUSES = {"filled", "canceled", "cancelled", "rejected", "expired"}

DB_PATH = os.getenv("SLIPPAGE_DB_PATH", "slippage_monitor.sqlite")
MAX_RETRIES = 5
HTTP_TIMEOUT = (3.05, 10)


def backoff_seconds(attempt: int) -> float:
    """Exponential backoff with jitter to avoid synchronized retries."""
    delay = min(0.5 * (2 ** attempt), 30)
    return delay + random.uniform(0, delay * 0.1)


def retry_after_seconds(response, default: int = 5) -> int:
    value = response.headers.get("Retry-After")
    try:
        return max(1, int(value)) if value is not None else default
    except ValueError:
        return default


def request_json(session, method: str, url: str, **kwargs):
    """Send an authenticated request with timeout and rate-limit handling."""
    for attempt in range(MAX_RETRIES + 1):
        try:
            response = session.request(
                method,
                url,
                timeout=HTTP_TIMEOUT,
                **kwargs,
            )
        except requests.RequestException:
            if attempt >= MAX_RETRIES:
                raise
            time.sleep(backoff_seconds(attempt))
            continue

        if response.status_code == 429:
            if attempt >= MAX_RETRIES:
                raise RuntimeError("Rate limit persisted after retries")
            time.sleep(retry_after_seconds(response))
            continue

        response.raise_for_status()
        payload = response.json()
        code = int(payload.get("code", 0) or 0)

        if code == 3001:
            if attempt >= MAX_RETRIES:
                raise RuntimeError("TickDB rate limit persisted after retries")
            delay = retry_after_seconds(response)
            time.sleep(delay)
            continue

        if code in (1001, 1002):
            raise RuntimeError("Invalid or missing API key")
        if code == 2002:
            raise KeyError(f"Unknown symbol: {kwargs.get('params')}")

        return payload.get("data", payload)

    raise RuntimeError("Request retry budget exhausted")


def extract_records(payload, key: str):
    if isinstance(payload, list):
        return payload
    if isinstance(payload, dict):
        return payload.get(key, [])
    return []


def adverse_slippage_bps(side: str, signal_price: Decimal,
                         weighted_fill: Decimal) -> Decimal:
    """Return positive values for execution adverse to the signal."""
    if signal_price <= 0:
        raise ValueError("signal_price must be positive")

    if side.lower() == "buy":
        adverse_price = weighted_fill - signal_price
    elif side.lower() == "sell":
        adverse_price = signal_price - weighted_fill
    else:
        raise ValueError(f"Unsupported side: {side}")

    return adverse_price / signal_price * Decimal("10000")


def weighted_fill_price(fills) -> Decimal:
    total_quantity = Decimal("0")
    total_notional = Decimal("0")

    for fill in fills:
        quantity = Decimal(str(fill["quantity"]))
        price = Decimal(str(fill["price"]))
        total_quantity += quantity
        total_notional += quantity * price

    if total_quantity == 0:
        raise ValueError("Cannot calculate weighted fill without quantity")

    return total_notional / total_quantity


def initialize_database():
    db = sqlite3.connect(DB_PATH, timeout=10)
    db.execute("PRAGMA journal_mode=WAL")

    db.execute(
        """
        CREATE TABLE IF NOT EXISTS observations (
            order_id TEXT PRIMARY KEY,
            symbol TEXT NOT NULL,
            strategy_id TEXT,
            side TEXT NOT NULL,
            signal_price TEXT NOT NULL,
            weighted_fill TEXT NOT NULL,
            adverse_bps TEXT NOT NULL,
            robust_z REAL,
            status TEXT NOT NULL,
            updated_at TEXT NOT NULL
        )
        """
    )

    db.execute(
        """
        CREATE TABLE IF NOT EXISTS outbox (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            order_id TEXT NOT NULL,
            severity TEXT NOT NULL,
            payload TEXT NOT NULL,
            delivered INTEGER NOT NULL DEFAULT 0,
            UNIQUE(order_id, severity)
        )
        """
    )

    db.commit()
    return db


def robust_z_score(db, order_id: str, value: float):
    rows = db.execute(
        """
        SELECT adverse_bps
        FROM observations
        WHERE order_id != ?
        ORDER BY updated_at DESC
        LIMIT 200
        """,
        (order_id,),
    ).fetchall()

    values = [float(row[0]) for row in rows]
    if len(values) < 30:
        return None

    median = statistics.median(values)
    mad = statistics.median(abs(item - median) for item in values)

    if mad <= 0:
        return None

    return 0.6745 * (value - median) / mad


def enqueue_alert(db, order_id: str, severity: str, payload: dict):
    db.execute(
        """
        INSERT OR IGNORE INTO outbox
            (order_id, severity, payload)
        VALUES (?, ?, ?)
        """,
        (
            order_id,
            severity,
            json.dumps(payload, default=str),
        ),
    )
    db.commit()


def flush_outbox(db, session):
    rows = db.execute(
        """
        SELECT id, payload
        FROM outbox
        WHERE delivered = 0
        ORDER BY id
        LIMIT 20
        """
    ).fetchall()

    for row_id, raw_payload in rows:
        if not ALERT_WEBHOOK_URL:
            print(f"ALERT [delivery disabled]: {raw_payload}")
            continue

        try:
            request_json(
                session,
                "POST",
                ALERT_WEBHOOK_URL,
                json=json.loads(raw_payload),
            )
        except Exception as exc:
            print(f"Alert delivery failed; retaining outbox row: {exc}")
            continue

        db.execute(
            "UPDATE outbox SET delivered = 1 WHERE id = ?",
            (row_id,),
        )
        db.commit()


def poll_orders_and_fills(db, session, updated_since: str):
    payload = request_json(
        session,
        "GET",
        ORDERS_URL,
        params={"updated_since": updated_since},
    )
    orders = extract_records(payload, "orders")
    latest_update = updated_since

    for order in orders:
        order_id = str(order["order_id"])
        latest_update = max(latest_update, str(order["updated_at"]))

        fills_payload = request_json(
            session,
            "GET",
            FILLS_URL,
            params={"order_id": order_id},
        )
        fills = extract_records(fills_payload, "fills")

        if not fills:
            continue

        signal_price = Decimal(str(order["signal_price"]))
        weighted_fill = weighted_fill_price(fills)
        slippage = float(
            adverse_slippage_bps(
                order["side"],
                signal_price,
                weighted_fill,
            )
        )

        z_score = robust_z_score(db, order_id, slippage)
        status = str(order["status"]).lower()
        terminal = status in TERMINAL_STATUSES

        # Partial fills receive looser thresholds to avoid noise.
        warn_limit = WARN_BPS if terminal else WARN_BPS * 2
        critical_limit = CRITICAL_BPS if terminal else CRITICAL_BPS * 2

        severity = None
        if slippage >= critical_limit or (z_score is not None and z_score >= 4):
            severity = "critical"
        elif slippage >= warn_limit or (z_score is not None and z_score >= 3):
            severity = "warning"

        db.execute(
            """
            INSERT INTO observations (
                order_id, symbol, strategy_id, side, signal_price,
                weighted_fill, adverse_bps, robust_z, status, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON CONFLICT(order_id) DO UPDATE SET
                weighted_fill = excluded.weighted_fill,
                adverse_bps = excluded.adverse_bps,
                robust_z = excluded.robust_z,
                status = excluded.status,
                updated_at = excluded.updated_at
            """,
            (
                order_id,
                order.get("symbol", ""),
                order.get("strategy_id"),
                order["side"],
                str(signal_price),
                str(weighted_fill),
                str(slippage),
                z_score,
                status,
                str(order["updated_at"]),
            ),
        )
        db.commit()

        if severity:
            enqueue_alert(
                db,
                order_id,
                severity,
                {
                    "severity": severity,
                    "order_id": order_id,
                    "symbol": order.get("symbol"),
                    "strategy_id": order.get("strategy_id"),
                    "side": order["side"],
                    "signal_price": str(signal_price),
                    "weighted_fill": str(weighted_fill),
                    "adverse_slippage_bps": round(slippage, 4),
                    "robust_z": z_score,
                    "status": status,
                    "fills": fills,
                },
            )

    return latest_update


def main():
    if not API_KEY:
        raise RuntimeError("BROKER_API_KEY is required")

    db = initialize_database()
    session = requests.Session()
    session.headers.update(
        {
            "Authorization": f"Bearer {API_KEY}",
            "Accept": "application/json",
        }
    )

    updated_since = os.getenv(
        "SLIPPAGE_UPDATED_SINCE",
        time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 86400)),
    )

    retry = 0

    while True:
        try:
            updated_since = poll_orders_and_fills(
                db,
                session,
                updated_since,
            )
            flush_outbox(db, session)
            retry = 0
            time.sleep(POLL_SECONDS)
        except Exception as exc:
            retry += 1
            delay = backoff_seconds(min(retry, 10))
            print(f"Monitor cycle failed: {exc}; retrying in {delay:.2f}s")
            time.sleep(delay)


if __name__ == "__main__":
    main()

⚠️ The endpoint contract above is deliberately normalized. Map the broker’s actual paths, authentication headers, timestamps, and status values inside the adapter. Do not expose raw API keys in logs or exception messages.

For high-frequency environments, polling every order can create unnecessary API traffic. Prefer the broker’s execution-event stream or a consolidated fill endpoint. The reconciliation and alert logic can remain unchanged.

5. Add Market Context Without Replacing the Signal Reference

A slippage alert should answer two questions:

  1. How far did the execution move from the signal?
  2. What market conditions surrounded that movement?

The first question requires the original signal and broker fill data. The second can benefit from order-book context.

For US equities, the TickDB depth channel provides L1 bid and ask snapshots. The channel supports deeper levels for Hong Kong equities and crypto, but it is not available for forex, precious metals, or indices. A US-equity monitor can therefore calculate an L1 pressure ratio:

[
\text{L1 Pressure Ratio}

\frac{\text{L1 bid size}}{\text{L1 ask size}}
]

The ratio helps classify an alert as:

  • Liquidity-supported: Bid pressure remains high while slippage is adverse.
  • Liquidity-withdrawal: Bid depth falls before or during the adverse fill.
  • Price-impact event: The order itself may have consumed available liquidity.
  • Reference-price mismatch: The strategy reference and executable quote diverged materially.

This metric is contextual evidence, not proof of causality. An L1 ratio does not expose hidden depth, queue priority, venue fragmentation, or the full shape of the order book. It should annotate an alert rather than independently determine it.

5.1 TickDB WebSocket Context Collector

The following collector maintains a WebSocket connection, sends the application-level heartbeat, reconnects with exponential backoff, and calculates L1 pressure. It uses protocol-level WebSocket pings in addition to the application command.

Configure the WebSocket endpoint and subscription message through environment variables because deployment details and supported payload variants can vary.

import asyncio
import json
import os
import random
from urllib.parse import urlencode

import websockets


WS_URL = os.environ["TICKDB_WS_URL"]
API_KEY = os.environ["TICKDB_API_KEY"]
SUBSCRIBE_MESSAGE = json.loads(
    os.environ["TICKDB_DEPTH_SUBSCRIBE_MESSAGE"]
)

HTTP_TIMEOUT = (3.05, 10)
HEARTBEAT_SECONDS = 15
MAX_BACKOFF_SECONDS = 30


def authenticated_url(url: str) -> str:
    separator = "&" if "?" in url else "?"
    return f"{url}{separator}{urlencode({'api_key': API_KEY})}"


def backoff_seconds(attempt: int) -> float:
    delay = min(0.5 * (2 ** attempt), MAX_BACKOFF_SECONDS)
    return delay + random.uniform(0, delay * 0.1)


def extract_level_size(value):
    if isinstance(value, dict):
        return float(value.get("size", value.get("quantity", 0)))
    return float(value or 0)


async def application_heartbeat(websocket):
    while True:
        await asyncio.sleep(HEARTBEAT_SECONDS)
        await websocket.send(json.dumps({"cmd": "ping"}))


async def normalize_depth(message: dict):
    data = message.get("data", message)

    bid = data.get("bid", data.get("bids", [{}])[0])
    ask = data.get("ask", data.get("asks", [{}])[0])

    if isinstance(bid, list):
        bid = bid[0]
    if isinstance(ask, list):
        ask = ask[0]

    bid_size = extract_level_size(bid)
    ask_size = extract_level_size(ask)

    if ask_size <= 0:
        return None

    return {
        "bid_price": float(bid.get("price", 0)),
        "ask_price": float(ask.get("price", 0)),
        "bid_size": bid_size,
        "ask_size": ask_size,
        "pressure_ratio": bid_size / ask_size,
    }


async def run():
    if not API_KEY:
        raise RuntimeError("TICKDB_API_KEY is required")

    retry = 0

    while True:
        heartbeat_task = None

        try:
            # Never log the authenticated URL because it contains the API key.
            async with websockets.connect(
                authenticated_url(WS_URL),
                open_timeout=10,
                close_timeout=5,
                ping_interval=20,
                ping_timeout=10,
                max_queue=None,
            ) as websocket:
                await websocket.send(json.dumps(SUBSCRIBE_MESSAGE))
                heartbeat_task = asyncio.create_task(
                    application_heartbeat(websocket)
                )

                retry = 0
                print("Depth WebSocket connected")

                async for raw_message in websocket:
                    message = json.loads(raw_message)

                    if message.get("cmd") == "pong":
                        continue

                    normalized = await normalize_depth(message)
                    if normalized:
                        print(json.dumps(normalized))

        except asyncio.CancelledError:
            raise
        except Exception as exc:
            retry += 1
            delay = backoff_seconds(min(retry, 10))
            print(f"Depth connection failed: {exc}; retry in {delay:.2f}s")
            await asyncio.sleep(delay)
        finally:
            if heartbeat_task is not None:
                heartbeat_task.cancel()
                await asyncio.gather(
                    heartbeat_task,
                    return_exceptions=True,
                )


if __name__ == "__main__":
    asyncio.run(run())

⚠️ For production high-frequency workloads, use a maintained asynchronous transport, validate message schemas, and avoid printing raw payloads that may contain sensitive execution information.

5.2 Do Not Use Current Depth as the Signal Price

Depth snapshots are contextual. The fill must still be compared with the signal captured at decision time. Replacing the historical signal with a current bid or ask makes the slippage calculation circular: the alert ends up measuring movement since the alert engine looked, not execution error since the strategy acted.

6. From Alert to Investigation

A useful alert contains enough context to begin an investigation without opening five different tools.

6.1 Alert Payload

{
  "severity": "warning",
  "order_id": "ord_12345",
  "symbol": "AAPL.US",
  "strategy_id": "mean_reversion_v3",
  "side": "buy",
  "signal_price": "100.0000",
  "weighted_fill": "100.0180",
  "adverse_slippage_bps": 1.8,
  "robust_z": 3.42,
  "status": "filled",
  "fills": [
    {
      "fill_id": "fill_1",
      "price": "100.0180",
      "quantity": "500",
      "executed_at": "2026-04-15T14:32:11.042Z"
    }
  ]
}

The payload should also include:

  • Signal timestamp and venue.
  • Broker order acknowledgement timestamp.
  • First fill timestamp and last fill timestamp.
  • Order duration.
  • Requested quantity and filled quantity.
  • Current best bid and ask.
  • Spread in basis points.
  • L1 pressure ratio, if available.
  • Strategy-side and symbol-side thresholds.
  • Current incident correlation ID.

6.2 Investigation Sequence

The operator should follow the same sequence for every alert:

  1. Validate instrument identity. Confirm symbol mapping, exchange, currency, and contract multiplier.
  2. Validate the reference price. Confirm that the signal price came from the intended source and was not overwritten.
  3. Check timestamp alignment. Compare exchange, broker, and local timestamps using synchronized clocks.
  4. Inspect individual fills. Separate venue latency, partial-fill behavior, and price improvement.
  5. Inspect market state. Review spread, depth, volatility, and nearby news.
  6. Check strategy behavior. Determine whether the strategy repeatedly uses marketable or aggressive orders.
  7. Compare by cohort. Break results down by symbol, strategy, time session, order type, and venue.
  8. Document the resolution. Store the incident outcome with the raw evidence.

A high slippage rate does not automatically imply a bad strategy. It may indicate an aggressive execution policy, a stale signal, a broker routing problem, or an illiquid instrument. The monitor should reveal which cause dominates.

7. Calibrating Against a No-Slippage Backtest

A backtest that assumes zero slippage can materially overstate executable returns. Before deploying the monitor, replay the strategy under several explicit cost assumptions:

Scenario One-Way Slippage Commission Purpose
Idealized 0 bps $0 Upper-bound performance only
Liquid 3 bps Broker schedule Conservative baseline for large-cap liquidity
Moderate 10 bps Broker schedule Stress case for urgent or less liquid orders
Severe 25 bps Broker schedule Execution-break detection

This grid is an assumption set, not a historical performance claim. The correct values depend on the instrument, order size, holding period, and execution policy.

If a strategy remains profitable across the moderate case, its economics are less sensitive to execution assumptions. If performance collapses as soon as realistic slippage is introduced, the live monitor should treat execution quality as a strategy-level risk control rather than an isolated post-trade metric.

The monitor should also record realized slippage during the backtest replay. Comparing simulated and live distributions reveals:

  • Adverse-selection assumptions.
  • Unrealistic fill timing.
  • Insufficient market-impact modeling.
  • Signals that cannot be reached at their original reference prices.
  • Exchange or venue effects missing from the simulation.

8. Deployment Guide

The appropriate deployment depends on the operator’s responsibilities and latency requirements.

User Segment Recommended Polling Storage Alert Delivery
Individual quant developer 5–15 seconds SQLite Webhook or console
Production strategy team 1–5 seconds PostgreSQL or TimescaleDB Pager and Slack
Institutional execution desk Broker events or sub-second feed Durable event store SIEM, Pager, and incident API

8.1 Production Checklist

Before enabling the alert:

  • Signal price and timestamp are persisted before order submission.
  • Fill records have stable broker-generated identifiers.
  • Duplicate events cannot create duplicate alerts.
  • Buy and sell slippage use the correct side adjustment.
  • Partial fills are aggregated by executed quantity.
  • Absolute and statistical thresholds are configured separately.
  • Exchange, broker, and local clocks are synchronized.
  • Every HTTP request has a connect and read timeout.
  • Rate limits trigger Retry-After handling.
  • WebSocket connections send heartbeat messages and reconnect with jittered backoff.
  • Alerts persist until delivery succeeds.
  • Raw broker payloads remain available for investigation.
  • The strategy cannot disable monitoring through an ordinary runtime failure.
  • Threshold assumptions are documented and reviewed quarterly.

8.2 Failure Modes

Failure Mode Consequence Mitigation
Signal price missing Slippage cannot be calculated Fail closed or mark order as unreconciled
Duplicate fills Cost is overstated Broker fill ID plus unique database constraint
Broker outage Alerts stop silently Independent service heartbeat and stale-order check
Clock drift Execution latency appears negative NTP monitoring and exchange-aware timestamps
Market closure False alerts from stale quotes Session calendar and quote-age validation
Corporate action Historical price becomes non-comparable Adjusted reference-price policy
WebSocket reconnect storm Broker rate limiting Exponential backoff, jitter, and connection limits

Conclusion

“The order filled. The price did not match the signal.”

That mismatch is not a rounding error; it is an execution fact. The safest production system treats slippage as a measured quantity with an immutable reference, an order-aware aggregation rule, and a context-sensitive escalation policy.

The essential takeaway is simple: do not wait for a backtest to reveal the problem in production. Capture the signal, reconcile every fill, measure side-adjusted slippage, and alert on both absolute limits and rolling distribution changes.

Next Steps

If you are an individual quant developer, sign up at tickdb.ai for a free API key, generate credentials in the dashboard, and store the key in TICKDB_API_KEY. Normalize your broker’s order and fill events, then begin collecting a rolling execution baseline.

If you operate a production strategy team, deploy the monitor as a separate reliability service with durable event storage, an alert outbox, clock synchronization, and incident-level audit logs.

If you need historical OHLCV data for strategy calibration and execution-cost research, contact [email protected] for institutional data options.

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.