At 8:03:07 a.m. ET, a pre-market scanner flashes green: the price has crossed the prior session’s high by 40 cents. The chart looks decisive. Thirty seconds later, the quote retreats below resistance, the order-book snapshot disappears, and the apparent breakout becomes another failed auction.

The failure is rarely caused by a bad threshold alone. Pre-market and post-market breakouts fail because thin liquidity, irregular volume, venue fragmentation, and temporary quotes can make a small order look like a genuine repricing.

For systematic traders, the solution is not to predict every false break. It is to require independent evidence: session-qualified volume, a sustained break beyond a volatility-aware buffer, stable quotes, and persistent order-book support. This article builds that filter as a state machine and provides a production-oriented Python implementation.

1. Why Extended-Hours Breakouts Produce False Signals

A breakout requires more than a trade printing above a reference level. It requires enough executed volume to move the market and enough remaining liquidity to keep the new price from reversing immediately.

Extended-hours markets weaken both conditions. Market makers operate with different inventory constraints, order flow concentrates in fewer venues, and quoted spreads can widen substantially. A single 100-share print may therefore cross resistance without changing the informational value of the session.

The practical problem is that conventional breakout logic often treats all 1-minute bars as equally reliable. A regular-session bar with 600,000 shares and a pre-market bar with 8,000 shares may receive the same signal, even though they do not represent comparable evidence.

The following illustrative profile shows why session context must precede the breakout test:

Session context Illustrative 1-minute volume Illustrative spread Typical failure mode
Pre-market 8,400 shares 11 bps Isolated quote or block trade crosses resistance
Early post-market 6,900 shares 14 bps Overnight auction order flow rolls over
Regular session 612,000 shares 2.1 bps More depth absorbs opposing orders
Late post-market 4,200 shares 18 bps Wide spread makes a 5-cent move appear structural

These numbers are normalization examples, not market-wide averages. Your thresholds must come from the symbols, venues, and sessions you trade.

A reliable filter must answer five separate questions:

  1. Is the event occurring in the intended trading session?
  2. Did sufficient executed volume support the break?
  3. Did price clear resistance by more than the prevailing spread and normal noise?
  4. Did the quote remain continuous and the order book remain present?
  5. Did the condition persist across multiple observations?

A “yes” answer to only one or two of these questions produces a fragile candidate.

2. The Microstructure Failure Pattern

Most false extended-hours breakouts contain several correlated warning signs.

2.1 Low Absolute Volume

Relative volume is useful, but it is insufficient when the baseline is close to zero. A 10-minute volume of 2.5 times a 400-share baseline still represents only 1,000 shares.

Use three independent volume controls:

[
V_{\text{pass}} =
\max\left(V_{\text{floor}},; m \times V_{\text{baseline}}\right)
]

Where:

  • (V_{\text{floor}}) is the minimum meaningful share count.
  • (m) is the required multiple of expected volume.
  • (V_{\text{baseline}}) is the median volume for the same clock minute across a reference sample.

Calculate the baseline using the same session and clock time. Comparing 8:05 a.m. with the regular-session opening average systematically underestimates expected early liquidity and can reject valid signals.

A median and median absolute deviation provide a more stable reference than a simple average:

[
z_{\text{volume}} =
\frac{V_{\text{bar}} - \operatorname{median}(V_{\text{baseline}})}
{\operatorname{MAD}(V_{\text{baseline}}) + \epsilon}
]

You can use this score as a secondary control, but avoid making it the only condition. Volume distributions become unstable on low-activity symbols and around scheduled news events.

2.2 Spread-Width Breakouts

A price that moves one tick above resistance may still be inside the quoted spread. The apparent break then disappears when the quote refreshes.

Require the traded price to exceed resistance by a buffer wider than current execution noise:

[
B_{\text{price}} =
\max\left(2 \times \text{spread},; k \times \text{ATR}_{\text{price}}\right)
]

The ATR component matters because a fixed $0.05 buffer behaves differently on a $12 stock and a $900 stock. The spread component matters because a 12-basis-point spread represents a different execution cost from a 2-basis-point spread.

2.3 Quote Disappearance

A break confirmed by a quote with zero or nearly zero size on either side is vulnerable to cancellation. The market may appear to have accepted a higher price when the displayed quote was not supported by meaningful size.

At minimum, validate:

  • Bid and ask prices remain present.
  • Both sides exceed a symbol-specific size floor.
  • The spread remains below a maximum threshold.
  • The quote persists for several observations.
  • The bid-to-ask size ratio remains consistent with the intended direction.

For an upward breakout, require persistent bid-side support without treating a single large bid as conclusive. A large L1 bid can disappear immediately. Continuity across multiple samples provides stronger evidence than one snapshot.

2.4 Clock-Time Distortion

The same 1-minute interval can represent different market states. The first minute after the pre-market opening, the final minute before the regular session, and the first minute after the regular close can all contain concentrated order flow.

Apply explicit session boundaries from the relevant venue calendar:

  • pre
  • regular
  • post

Do not infer the session from local time alone. Holidays, early closes, and venue-specific schedules can invalidate that mapping.

3. Three-Phase Trading Logic and System Architecture

The filter should operate as a three-phase state machine rather than a collection of unrelated indicators.

3.1 Pre-Event: Establish the Reference

Before evaluating an extended-hours session, establish:

  • Valid session boundaries.
  • Prior resistance and support levels.
  • Same-clock-minute volume baselines.
  • Symbol-specific spread and depth limits.
  • Price buffers based on spread and short-horizon volatility.
  • Scheduled-event and halt calendars.

The system should reject the setup if any required baseline is missing. A missing baseline must not silently become zero, because that makes a relative-volume filter meaningless.

3.2 During the Event: Require Converging Evidence

A candidate becomes eligible only when all core conditions converge:

  1. The session is explicitly allowed.
  2. Bar volume exceeds the absolute and relative thresholds.
  3. Turnover exceeds the minimum notional threshold.
  4. The close clears resistance plus the price buffer.
  5. The order-book snapshot passes spread, size, and persistence checks.
  6. Consecutive bars preserve the breakout.

The system should emit research signals rather than unconditional orders. A later confirmation stage can test retests, execution costs, and the tradable session’s liquidity conditions.

3.3 Post-Event: Test Persistence and Cost

A durable break often leaves the prior resistance level as potential support. The system can require a retest or a subsequent bar that holds above the breakout buffer.

Backtests for this logic should include at least three years of data, 50 qualifying events, commissions, spread cost, and slippage assumptions. They should report gross and net win rates, profit factor, Sharpe ratio, maximum drawdown, and drawdown duration against a buy-and-hold benchmark.

This article does not report simulated performance because no validated backtest dataset accompanies the implementation. Treat the thresholds as configurable research parameters rather than production recommendations.

3.4 Architecture

The data-source boundary determines the architecture. TickDB provides US L1 depth data and historical OHLCV through its kline data, but its trades endpoint does not support US equities. The system therefore separates authoritative session-tagged trade volume from real-time quote validation.

┌─────────────────────────────────────────────────────────────┐
│                 Extended-Hours Breakout Monitor             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│ Broker/consolidated tape                                    │
│   └─ Trade price, size, timestamp, session label            │
│          │                                                  │
│          ▼                                                  │
│   Session Clock + 1-Minute Volume Aggregator                │
│          │                                                  │
│          ├──────────────────────┐                           │
│          ▼                      ▼                           │
│ Historical baseline       Breakout State Machine            │
│ Same-clock median          └───────┬──────────────────────┘ │
│                                      │                       │
│ TickDB US L1 depth ───────► Quote & Depth Validator        │
│                                      │                       │
│                                      ▼                       │
│                              Candidate Signal                │
└─────────────────────────────────────────────────────────────┘

This separation prevents a common category error: treating an L1 quote feed as a tick-level transaction feed.

4. Production-Oriented Python Implementation

The following implementation combines two normalized inputs:

  1. TickDB depth over WebSocket, providing US L1 bid and ask quotes.
  2. A broker or consolidated tape feed, provided as newline-delimited JSON, providing trade price, size, timestamp, and session.

The broker feed is explicit because TickDB does not provide US equity tick-level trades. If your execution platform already exposes a normalized trade callback, replace only the consume_trades function.

4.1 Installation and Configuration

Install the WebSocket dependency:

pip install websockets

Set the required environment variables:

export TICKDB_API_KEY="your-api-key"
export TICKDB_WS_URL="your-current-tickdb-websocket-endpoint"
export BREAKOUT_LEVEL="210.00"

Configure the event tape:

export ALLOWED_SESSIONS="pre,post"
export BASELINE_PRE_VOLUME_60S="8000"
export BASELINE_POST_VOLUME_60S="6000"
export MIN_VOLUME_SHARES="3000"
export MIN_RELATIVE_VOLUME="1.50"
export MIN_TURNOVER_USD="500000"
export MAX_SPREAD_BPS="15"
export MIN_SIDE_SIZE="100"
export MIN_BID_ASK_RATIO="1.25"
export DEPTH_CONFIRM_SAMPLES="3"
export BREAKOUT_BUFFER_BPS="10"
export CONFIRM_BARS="2"

The WebSocket host is an environment variable because deployment environments may use different regional or account-specific endpoints. Use the current endpoint documented for your TickDB account.

4.2 Complete Filter

from __future__ import annotations

import asyncio
import json
import math
import os
import random
import sys
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

import websockets
from websockets.exceptions import ConnectionClosed


SYMBOL = os.getenv("SYMBOL", "AAPL.US")
API_KEY = os.getenv("TICKDB_API_KEY", "").strip()
WS_BASE_URL = os.getenv("TICKDB_WS_URL", "").strip()

ALLOWED_SESSIONS = {
    value.strip().lower()
    for value in os.getenv("ALLOWED_SESSIONS", "pre,post").split(",")
    if value.strip()
}

BREAKOUT_LEVEL = float(os.getenv("BREAKOUT_LEVEL", "0"))
MIN_VOLUME_SHARES = float(os.getenv("MIN_VOLUME_SHARES", "3000"))
MIN_RELATIVE_VOLUME = float(os.getenv("MIN_RELATIVE_VOLUME", "1.50"))
MIN_TURNOVER_USD = float(os.getenv("MIN_TURNOVER_USD", "500000"))

MAX_SPREAD_BPS = float(os.getenv("MAX_SPREAD_BPS", "15"))
MIN_SIDE_SIZE = float(os.getenv("MIN_SIDE_SIZE", "100"))
MIN_BID_ASK_RATIO = float(os.getenv("MIN_BID_ASK_RATIO", "1.25"))
DEPTH_CONFIRM_SAMPLES = int(os.getenv("DEPTH_CONFIRM_SAMPLES", "3"))
DEPTH_WINDOW_SECONDS = float(os.getenv("DEPTH_WINDOW_SECONDS", "5"))
MAX_QUOTE_AGE_SECONDS = float(os.getenv("MAX_QUOTE_AGE_SECONDS", "2"))

BREAKOUT_BUFFER_BPS = float(os.getenv("BREAKOUT_BUFFER_BPS", "10"))
CONFIRM_BARS = int(os.getenv("CONFIRM_BARS", "2"))
SIGNAL_COOLDOWN_SECONDS = int(os.getenv("SIGNAL_COOLDOWN_SECONDS", "300"))

HEARTBEAT_SECONDS = float(os.getenv("HEARTBEAT_SECONDS", "15"))
RECONNECT_BASE_SECONDS = 1.0
RECONNECT_MAX_SECONDS = 30.0

PRE_BASELINE = float(os.getenv("BASELINE_PRE_VOLUME_60S", "8000"))
POST_BASELINE = float(os.getenv("BASELINE_POST_VOLUME_60S", "6000"))


class AuthenticationError(RuntimeError):
    """Raised when the server rejects the configured API key."""


class ConfigError(RuntimeError):
    """Raised when mandatory configuration is absent or invalid."""


def validate_config() -> None:
    if not API_KEY:
        raise ConfigError("TICKDB_API_KEY is required")
    if not WS_BASE_URL:
        raise ConfigError("TICKDB_WS_URL is required")
    if BREAKOUT_LEVEL <= 0:
        raise ConfigError("BREAKOUT_LEVEL must be positive")
    if BREAKOUT_LEVEL >= math.inf:
        raise ConfigError("BREAKOUT_LEVEL must be finite")


def authenticated_ws_url(base_url: str, api_key: str) -> str:
    """Append WebSocket authentication without duplicating api_key."""
    parts = urlsplit(base_url)
    query = [(key, value) for key, value in parse_qsl(parts.query)
             if key != "api_key"]
    query.append(("api_key", api_key))
    return urlunsplit(
        (parts.scheme, parts.netloc, parts.path, urlencode(query), parts.fragment)
    )


def to_float(value: Any) -> float | None:
    try:
        result = float(value)
    except (TypeError, ValueError):
        return None
    if not math.isfinite(result):
        return None
    return result


def first_level(value: Any) -> tuple[float | None, float | None]:
    """Extract price and size from an L1 level."""
    if isinstance(value, dict):
        price = None
        size = None
        for price_key in ("price", "px", "p"):
            if price_key in value:
                price = to_float(value[price_key])
                break
        for size_key in ("size", "qty", "quantity", "volume", "v"):
            if size_key in value:
                size = to_float(value[size_key])
                break
        return price, size

    if isinstance(value, (list, tuple)) and value:
        price = to_float(value[0])
        size = to_float(value[1]) if len(value) > 1 else None
        return price, size

    return None, None


def find_value(payload: Any, names: set[str]) -> Any:
    """Recursively locate a field in supported depth payload layouts."""
    if isinstance(payload, dict):
        for name in names:
            if name in payload:
                return payload[name]
        for value in payload.values():
            found = find_value(value, names)
            if found is not None:
                return found
    elif isinstance(payload, list):
        for item in payload:
            found = find_value(item, names)
            if found is not None:
                return found
    return None


@dataclass
class Quote:
    timestamp: float
    bid_price: float
    ask_price: float
    bid_size: float
    ask_size: float

    @property
    def spread(self) -> float:
        return self.ask_price - self.bid_price

    @property
    def spread_bps(self) -> float:
        midpoint = (self.ask_price + self.bid_price) / 2
        if midpoint <= 0:
            return math.inf
        return self.spread / midpoint * 10_000

    @property
    def bid_ask_ratio(self) -> float:
        if self.ask_size <= 0:
            return math.inf
        return self.bid_size / self.ask_size


class DepthMonitor:
    def __init__(self) -> None:
        self.samples: list[Quote] = []

    def observe(self, quote: Quote) -> None:
        self.samples.append(quote)
        cutoff = quote.timestamp - DEPTH_WINDOW_SECONDS
        self.samples = [sample for sample in self.samples if sample.timestamp >= cutoff]

    @property
    def latest(self) -> Quote | None:
        return self.samples[-1] if self.samples else None

    def confirmed_upward(self) -> bool:
        """Require recent, continuous, two-sided support for a break."""
        now = asyncio.get_running_loop().time()
        recent = [
            sample for sample in self.samples
            if now - sample.timestamp <= DEPTH_WINDOW_SECONDS
        ]

        if len(recent) < DEPTH_CONFIRM_SAMPLES:
            return False

        if now - recent[-1].timestamp > MAX_QUOTE_AGE_SECONDS:
            return False

        for previous, current in zip(recent, recent[1:]):
            if current.timestamp - previous.timestamp > 2.5:
                return False

        for sample in recent:
            if sample.spread_bps > MAX_SPREAD_BPS:
                return False
            if sample.bid_size < MIN_SIDE_SIZE:
                return False
            if sample.ask_size < MIN_SIDE_SIZE:
                return False
            if sample.bid_ask_ratio < MIN_BID_ASK_RATIO:
                return False

        return True


def extract_quote(payload: dict[str, Any]) -> Quote | None:
    """
    Normalize common L1 depth representations.

    If your account's SDK changes field names, update this adapter only.
    """
    bids = find_value(payload, {"bids", "bid", "buy", "b"})
    asks = find_value(payload, {"asks", "ask", "sell", "a"})

    bid_price, bid_size = first_level(bids)
    ask_price, ask_size = first_level(asks)

    if bid_price is None or ask_price is None:
        return None

    if bid_size is None:
        bid_size = to_float(find_value(payload, {"bid_size", "bidSize", "b_size"})) or 0
    if ask_size is None:
        ask_size = to_float(find_value(payload, {"ask_size", "askSize", "a_size"})) or 0

    return Quote(
        timestamp=asyncio.get_running_loop().time(),
        bid_price=bid_price,
        ask_price=ask_price,
        bid_size=bid_size,
        ask_size=ask_size,
    )


@dataclass
class MinuteBar:
    session: str
    minute: datetime
    volume: float = 0
    turnover: float = 0
    close: float = 0
    high: float = -math.inf
    low: float = math.inf

    def update(self, price: float, size: float) -> None:
        self.volume += size
        self.turnover += price * size
        self.close = price
        self.high = max(self.high, price)
        self.low = min(self.low, price)


def parse_timestamp(value: Any) -> datetime:
    if not isinstance(value, str):
        raise ValueError("trade timestamp must be an ISO-8601 string")
    timestamp = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if timestamp.tzinfo is None:
        timestamp = timestamp.replace(tzinfo=timezone.utc)
    return timestamp.astimezone(timezone.utc)


def baseline_for_session(session: str) -> float:
    if session == "pre":
        return PRE_BASELINE
    if session == "post":
        return POST_BASELINE
    return 0.0


def evaluate_bar(
    bar: MinuteBar,
    depth: DepthMonitor,
) -> tuple[bool, dict[str, Any]]:
    """Evaluate one completed one-minute bar."""
    quote = depth.latest
    baseline = baseline_for_session(bar.session)

    required_volume = max(
        MIN_VOLUME_SHARES,
        baseline * MIN_RELATIVE_VOLUME,
    )

    spread_buffer = 0.0
    if quote is not None:
        spread_buffer = 2 * quote.spread

    price_buffer = max(
        BREAKOUT_LEVEL * BREAKOUT_BUFFER_BPS / 10_000,
        spread_buffer,
    )

    volume_pass = bar.volume >= required_volume
    turnover_pass = bar.turnover >= MIN_TURNOVER_USD
    breakout_pass = bar.close >= BREAKOUT_LEVEL + price_buffer
    depth_pass = depth.confirmed_upward()

    diagnostics = {
        "session": bar.session,
        "minute": bar.minute.isoformat(),
        "volume": round(bar.volume, 2),
        "required_volume": round(required_volume, 2),
        "turnover": round(bar.turnover, 2),
        "close": bar.close,
        "breakout_level": BREAKOUT_LEVEL,
        "price_buffer": round(price_buffer, 6),
        "spread_bps": round(quote.spread_bps, 3) if quote else None,
        "bid_ask_ratio": round(quote.bid_ask_ratio, 3) if quote else None,
        "volume_pass": volume_pass,
        "turnover_pass": turnover_pass,
        "breakout_pass": breakout_pass,
        "depth_pass": depth_pass,
    }

    confirmed = all(
        (volume_pass, turnover_pass, breakout_pass, depth_pass)
    )
    return confirmed, diagnostics


class BreakoutEngine:
    def __init__(self, depth: DepthMonitor) -> None:
        self.depth = depth
        self.current_bar: MinuteBar | None = None
        self.consecutive_confirmations = 0
        self.last_session: str | None = None
        self.last_signal_at: float | None = None

    def process_trade(self, event: dict[str, Any]) -> None:
        if event.get("type") != "trade":
            return

        session = str(event.get("session", "")).lower()
        if session not in ALLOWED_SESSIONS:
            return

        timestamp = parse_timestamp(event["timestamp"])
        price = to_float(event.get("price"))
        size = to_float(event.get("size"))

        if price is None or size is None or size <= 0:
            return

        minute = timestamp.replace(second=0, microsecond=0)

        if self.current_bar is None:
            self.current_bar = MinuteBar(session=session, minute=minute)
            self.last_session = session

        elif (
            self.current_bar.session != session
            or self.current_bar.minute != minute
        ):
            self.finalize_current_bar()
            self.current_bar = MinuteBar(session=session, minute=minute)

        self.current_bar.update(price=price, size=size)

    def finalize_current_bar(self) -> None:
        bar = self.current_bar
        if bar is None:
            return

        confirmed, diagnostics = evaluate_bar(bar, self.depth)

        if confirmed:
            self.consecutive_confirmations += 1
        else:
            self.consecutive_confirmations = 0

        diagnostics["consecutive_confirmations"] = self.consecutive_confirmations

        print(json.dumps(diagnostics, separators=(",", ":")), flush=True)

        now = asyncio.get_running_loop().time()
        cooldown_clear = (
            self.last_signal_at is None
            or now - self.last_signal_at >= SIGNAL_COOLDOWN_SECONDS
        )

        if (
            self.consecutive_confirmations >= CONFIRM_BARS
            and cooldown_clear
        ):
            print(
                json.dumps(
                    {
                        "event": "candidate",
                        "symbol": SYMBOL,
                        "session": bar.session,
                        "minute": bar.minute.isoformat(),
                        "close": bar.close,
                        "note": (
                            "Research signal only; execution and retest "
                            "validation remain separate stages."
                        ),
                    },
                    separators=(",", ":"),
                ),
                flush=True,
            )
            self.last_signal_at = now
            self.consecutive_confirmations = 0

        self.current_bar = None


async def consume_trades(engine: BreakoutEngine) -> None:
    """
    Read normalized trades from stdin.

    Expected JSONL:
    {"type":"trade","timestamp":"2026-04-15T12:03:07Z",
     "price":210.12,"size":100,"session":"pre"}
    """
    while True:
        line = await asyncio.to_thread(sys.stdin.readline)
        if not line:
            break

        try:
            event = json.loads(line)
        except json.JSONDecodeError as error:
            print(
                json.dumps({"event": "input_error", "message": str(error)}),
                file=sys.stderr,
                flush=True,
            )
            continue

        try:
            engine.process_trade(event)
        except (KeyError, TypeError, ValueError) as error:
            print(
                json.dumps({"event": "input_error", "message": str(error)}),
                file=sys.stderr,
                flush=True,
            )


async def consume_depth(websocket: Any, depth: DepthMonitor) -> None:
    subscription = {
        "cmd": "subscribe",
        "channel": "depth",
        "symbol": SYMBOL,
    }
    await websocket.send(json.dumps(subscription))

    while True:
        try:
            raw_message = await asyncio.wait_for(
                websocket.recv(),
                timeout=HEARTBEAT_SECONDS,
            )
        except asyncio.TimeoutError:
            # Protocol heartbeat; the transport-level ping/pong is also enabled.
            await websocket.send(json.dumps({"cmd": "ping"}))
            continue

        if isinstance(raw_message, bytes):
            raw_message = raw_message.decode("utf-8", errors="replace")

        try:
            payload = json.loads(raw_message)
        except json.JSONDecodeError:
            continue

        if not isinstance(payload, dict):
            continue

        code = payload.get("code", 0)
        try:
            code = int(code)
        except (TypeError, ValueError):
            code = 0

        if code == 3001:
            retry_after = payload.get("retry_after", payload.get("retryAfter", 5))
            try:
                retry_after = max(float(retry_after), 1.0)
            except (TypeError, ValueError):
                retry_after = 5.0
            await asyncio.sleep(retry_after)
            continue

        if code in (1001, 1002):
            raise AuthenticationError(
                "TickDB rejected the API key; check TICKDB_API_KEY"
            )

        quote = extract_quote(payload)
        if quote is not None:
            depth.observe(quote)


async def run_websocket_with_reconnect(
    depth: DepthMonitor,
    trade_task: asyncio.Task[None],
) -> None:
    url = authenticated_ws_url(WS_BASE_URL, API_KEY)
    retry = 0

    while not trade_task.done():
        try:
            # Transport ping/pong complements the application heartbeat.
            async with websockets.connect(
                url,
                open_timeout=10,
                close_timeout=5,
                ping_interval=20,
                ping_timeout=10,
                max_size=2 ** 20,
            ) as websocket:
                await consume_depth(websocket, depth)
                retry = 0

        except AuthenticationError:
            raise
        except (ConnectionClosed, OSError, TimeoutError) as error:
            delay = min(
                RECONNECT_BASE_SECONDS * (2 ** retry),
                RECONNECT_MAX_SECONDS,
            )
            jitter = random.uniform(0, delay * 0.1)
            retry += 1

            print(
                json.dumps(
                    {
                        "event": "reconnect",
                        "delay_seconds": round(delay + jitter, 3),
                        "error": str(error),
                    }
                ),
                file=sys.stderr,
                flush=True,
            )
            await asyncio.sleep(delay + jitter)

    if trade_task.done() and not trade_task.cancelled():
        trade_task.result()


async def main() -> None:
    validate_config()

    depth = DepthMonitor()
    engine = BreakoutEngine(depth)

    trade_task = asyncio.create_task(consume_trades(engine))

    try:
        await run_websocket_with_reconnect(depth, trade_task)
    finally:
        if not trade_task.done():
            trade_task.cancel()
        await asyncio.gather(trade_task, return_exceptions=True)


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except (ConfigError, AuthenticationError) as error:
        print(f"Configuration error: {error}", file=sys.stderr)
        raise SystemExit(2)

4.3 Running the Monitor

A replay file can exercise the state machine without a live trade feed:

python extended_hours_filter.py < normalized_trades.jsonl

Each normalized trade requires this structure:

{"type":"trade","timestamp":"2026-04-15T12:03:07Z","price":210.12,"size":100,"session":"pre"}

The UTC timestamp may look unusual for US equities because pre and post are session labels assigned by the source feed, not hours relative to UTC. The application should trust the venue-normalized session label rather than attempting to infer it later.

4.4 Engineering Warnings

The implementation includes several safeguards that should not be removed:

  • Do not hardcode the API key. The WebSocket protocol requires the key as a URL parameter, so prevent query-string logging at the proxy and load balancer layers.
  • Do not remove reconnect jitter. Synchronized clients can create a reconnect surge after an outage.
  • Do not treat a fresh quote as deep liquidity. The validator requires repeated samples.
  • Do not use L1 depth as an L2 order-flow reconstruction. It does not reveal the full queue or every resting order.
  • Do not use the monitor as an execution engine. Keep research signaling, risk controls, and order routing in separately testable components.

5. The Core Filtering Algorithm

The complete decision process is more important than any individual threshold.

5.1 Hard Session Gate

Reject every event whose session is not explicitly allowed. This check should happen before computing indicators.

if session not in ALLOWED_SESSIONS:
    return

A missing session field must be treated as a rejection, not as regular or pre.

5.2 Volume and Turnover Gate

The volume condition uses both absolute and relative thresholds:

required_volume = max(
    MIN_VOLUME_SHARES,
    baseline * MIN_RELATIVE_VOLUME,
)

The turnover condition prevents a technically active but economically insignificant break:

turnover_pass = bar.turnover >= MIN_TURNOVER_USD

For low-priced securities, share volume may be misleading. For high-priced securities, turnover can be more informative. Use both when the symbol universe is heterogeneous.

5.3 Price-Buffer Gate

The close must exceed resistance by a buffer wider than the spread:

price_buffer = max(
    BREAKOUT_LEVEL * BREAKOUT_BUFFER_BPS / 10_000,
    2 * quote.spread,
)
breakout_pass = bar.close >= BREAKOUT_LEVEL + price_buffer

In a more advanced implementation, replace the static breakout component with a short-horizon ATR estimate:

[
\text{ATR buffer} = k \times ATR_{\text{session}}
]

Do not use a regular-session ATR value for a pre-market symbol without testing the difference. Early-session volatility often requires a different estimator.

5.4 Depth-Persistence Gate

The L1 validator checks:

  • Quote freshness.
  • Maximum spread.
  • Minimum bid and ask size.
  • Minimum bid-to-ask size ratio.
  • Continuity across observations.
confirmed = all(
    (
        sample.spread_bps <= MAX_SPREAD_BPS,
        sample.bid_size >= MIN_SIDE_SIZE,
        sample.ask_size >= MIN_SIDE_SIZE,
        sample.bid_ask_ratio >= MIN_BID_ASK_RATIO,
    )
    for sample in recent
)

The size floor should scale with the symbol and session. A threshold of 100 shares may be meaningful for a highly liquid mega-cap but irrelevant for a less active instrument.

5.5 Multi-Bar Confirmation

A single bar can still be distorted by a block trade or momentary liquidity withdrawal. Requiring consecutive confirmed bars reduces this failure mode:

if confirmed:
    self.consecutive_confirmations += 1
else:
    self.consecutive_confirmations = 0

Two bars are a conservative default, not a universal optimum. Evaluate one, two, and three-bar confirmation windows as separate hypotheses rather than selecting the best result after seeing the test set.

5.6 Candidate Versus Execution

The emitted event is a candidate, not an order. A production decision pipeline should add:

  1. Price-impact estimation.
  2. A retest or hold condition.
  3. Trading-session permissions.
  4. Maximum-loss and position-size controls.
  5. Duplicate-order prevention.
  6. Execution-latency monitoring.
  7. An audit log containing every input and rejected condition.

6. Data-Source Boundaries and Comparison

Choosing the right data source requires matching each signal to its actual data requirement.

Required capability Consolidated trade feed Historical kline feed US L1 depth feed
Session-tagged executed volume Native capability Subject to session coverage Not available
Exact executed price and size Native capability Aggregated by bar Not available
Real-time bid and ask prices Usually available Not its primary purpose Available
Real-time displayed size Feed-dependent Not available Available at L1
Full L2 depth queue Feed-dependent No No
Multi-year OHLCV research Optional Available, including 10+ years of cleaned US equity data No
US tick-level trades Feed-dependent No No

TickDB’s US order-book support is L1, while Hong Kong and crypto support L1–L10. Forex, precious metals, and indices do not support the depth channel. These boundaries matter when designing a reusable monitoring architecture.

For a US extended-hours strategy, a sound data design is:

  • Use a session-aware consolidated or broker tape for executed volume.
  • Use US L1 depth for quote and displayed-liquidity validation.
  • Use historical kline data for baseline research after verifying how the dataset represents extended-hours sessions.
  • Do not attempt to reconstruct US tick-level trades from an L1 depth feed.

The following comparison illustrates why combining sources is preferable to forcing one endpoint to perform every task:

Design choice Tape volume only Depth only Tape + L1 depth
Detects low-volume breakouts Yes No Yes
Verifies executed participation Yes No Yes
Validates current spread Feed-dependent Yes Yes
Detects displayed-liquidity withdrawal No Yes Yes
Produces false-breakout candidates High risk High risk Lower risk
Supports session-aware filtering Yes Possible Yes

This comparison measures capability, not expected returns. A combined feed can still generate poor signals if thresholds are incorrectly calibrated.

7. Deployment Guide

7.1 Recommended Baselines

Build the volume baseline by clock minute rather than by generic session average.

Baseline Recommended sample Typical use
20-session median At least 20 valid sessions Default same-clock baseline
60-session median At least 60 valid sessions More stable for low-activity names
Median absolute deviation 20+ sessions Robust volatility score
Event-adjusted baseline Exclude scheduled-news windows Earnings, macro releases, major announcements
Liquidity-tier baseline Group by spread and volume Large cross-symbol universe

Exclude halts, invalid prints, and sessions with incomplete tape coverage. An interrupted tape can make a missing-volume period look like a valid low-volume bar.

7.2 User-Segment Configurations

User segment Recommended configuration Operational priority
Individual researcher Fixed breakout level, 20-session median, two-bar confirmation, L1 persistence Reproducibility and simple diagnostics
Small quant team Session calendar service, centralized baselines, normalized event bus, replay archive Consistent data across strategies
Institutional team Vendor-quality consolidated tape, symbol-specific thresholds, cost model, production monitoring Execution realism and risk controls
AI-assisted development Typed adapters, unit tests, deterministic replay, structured diagnostic logs Safe integration and auditability

7.3 Monitoring Checklist

Monitor the following system-level metrics independently from strategy performance:

  • TickDB WebSocket reconnect count.
  • Time since the last valid L1 quote.
  • Missing or invalid normalized trade events.
  • Difference between source session labels and the venue calendar.
  • Number of bars rejected by each filter.
  • Distribution of spread, volume ratio, and turnover.
  • Latency between trade timestamp, receipt timestamp, and decision timestamp.
  • Duplicate or out-of-order trade events.

A sudden rise in rejected events may indicate a broken feed rather than a change in market behavior.

7.4 Validation Protocol

Before evaluating the filter, freeze a reproducible protocol:

  1. Split the data chronologically into development, validation, and final holdout periods.
  2. Keep all threshold calculation inside the development process.
  3. Include pre-market, post-market, earnings, macro-event, and ordinary sessions.
  4. Model commissions, half-spread cost, and symbol-dependent slippage.
  5. Compare one-bar, two-bar, and three-bar confirmation.
  6. Report gross and net results.
  7. Inspect performance by symbol liquidity tier and volatility regime.
  8. Require a separate paper-trading phase before capital is exposed.

Do not optimize a threshold on the same data used to report performance. A filter that works only on the selected breakouts is a fitted artifact rather than a deployable rule.

8. Conclusion: Require Evidence, Not Just a New Price

The green scanner flashes because the price crossed resistance. It becomes unreliable when the system mistakes a thin quote or isolated trade for genuine market demand.

The robust filter separates the question into independent checks: session, volume, turnover, price buffer, quote continuity, displayed depth, and persistence. Each check reduces a different failure mode. Together, they replace a fragile line crossing with an auditable state transition.

Before connecting this architecture to a live broker or institutional data feed, validate the historical session boundaries and volume baselines for every symbol. Keep the API key in TICKDB_API_KEY, preserve the heartbeat and reconnect logic, and test the normalized trade adapter against recorded replay data.

Next Steps

If you are an investor looking for deeper market insight, subscribe to the TickDB newsletter for regular analysis of liquidity, order-book structure, and extended-hours behavior.

If you want to run this research monitor yourself:

  1. Sign up at tickdb.ai; the free API key does not require a credit card.
  2. Generate an API key in the dashboard.
  3. Set TICKDB_API_KEY and TICKDB_WS_URL in your environment.
  4. Feed normalized session-tagged trades into the monitor and validate every rejection reason.

If you need 10+ years of historical OHLCV data for strategy research and backtesting, contact [email protected] for institutional data options.

If you use AI coding assistants, search for and install the tickdb-market-data SKILL in your tool’s marketplace.

This article does not constitute investment advice. Markets involve risk; past performance does not guarantee future results.