Flag statistical anomalies in book, trades, or feed data for human review.
3. Why This Bot Matters
Book or trade anomaly goes unnoticed
Without a statistical watchdog, sudden mid-price jumps, volume spikes, or microstructure changes that signal a feed glitch, market manipulation, or upstream halt are detected only when a strategy bot already trades on the bad data. By then unintended fills have already occurred.
No baseline for human review
Operators reviewing a market in incident mode have no reference for what 'normal' looked like for that market in the prior hour. Anomaly emissions provide the timestamped baseline that every post-incident review needs.
Z-score signal duplicated across strategies
If anomaly detection lives inside individual strategy bots, every team reinvents it inconsistently. A single shared service emits one canonical anomaly stream that all consumers — Risk, Strategy, Governance — read from.
Strategy bots blind to feed degradation
A z-score spike often precedes a stale-book event by seconds. Without an explicit anomaly signal, downstream Risk bots have no early warning to widen their staleness windows or pause new entries.
4. Required Polymarket Inputs
Input
Source
Required?
Use
CLOB V2 order book mid-price per condition_id
clob_public
Yes
Compute price z-score vs rolling baseline.
Recent trade volume per condition_id
data
Yes
Compute volume z-score vs rolling baseline.
5. Required Internal Inputs
Input
Source
Required?
Use
KillSwitch active flag
KillSwitch
Yes
Suppress all anomaly emissions when KillSwitch is active.
6. Parameter Guide
Parameter
Default
Warning
Hard
What it controls
z_score_threshold
3.0
2.0
1.0
Minimum z-score (standard deviations from rolling mean) to trigger an anomaly signal.
baseline_window_s
3600
7200
300
Rolling window in seconds used to compute mean and standard deviation for z-score baseline.
7. Detailed Parameter Instructions
z_score_threshold
What it means
Minimum z-score (standard deviations from rolling mean) to trigger an anomaly signal.
Default
{ "z_score_threshold": 3.0 }
Why this default matters
3.0 sigma suppresses noise from normal market volatility while catching genuine outlier events.
Threshold logic
Condition
Action
z >= 3.0
ANOMALYDETECTOR_PRICE_SPIKE or VOLUME_SPIKE; emit ObservationReport
2.0–3.0
WARN — borderline anomaly; emit with low_confidence flag
Strategy paused on a market after price anomaly detected
An unusual price movement was detected on this market that is statistically significant compared to recent history. The system paused new entries pending market stabilisation.
No anomaly detected despite market movement
The recent price movement was within the normal statistical range based on the last hour of market data. No anomaly signal was generated.
18. Failure-Mode Block
main_failure_mode
CLOB API outage prevents fresh price data from being fetched, causing AnomalyDetector to serve stale z-scores and miss genuine anomalies during the outage period.
false_positive_risk
Thin book with high bid-ask spread causes mid-price jumps that generate price z-scores above threshold despite no meaningful price discovery event.
false_negative_risk
Slow-moving price manipulation that stays within 3 sigma of the rolling baseline evades the anomaly detector entirely until the baseline itself shifts.
safe_fallback
If CLOB API or Data API is unavailable, emit STALE_DATA WARN and halt anomaly detection. Do not emit from stale z-scores. Resume on API recovery with fresh baseline computation.
required_dependencies
Polymarket CLOB V2 public API, Polymarket Data API for trade volume, KillSwitch active flag, Redis for rolling baseline state
19. Failure-Injection Recipes
Scenario
How to inject
Expected behaviour
Recovery
CLOB_API_DOWN
Block CLOB public API for 10 min
Automatic on API recovery; baseline resumes updating on next poll
SYNTHETIC_PRICE_SPIKE
Inject mock mid-price 5 standard deviations above baseline for a test market
Automatic when price returns to normal range
KILL_SWITCH_ON
Set killswitch.active=true during active detection
Automatic on KillSwitch reset
20. State & Persistence
Cold-start recovery
On cold start, baseline rebuilt from next N poll cycles; anomaly detection suppressed until baseline is populated.
21. Concurrency & Idempotency
Aspect
Specification
Execution model
async per-market poll loop
Max in-flight
30
Idempotency key
condition_id + poll_cycle_ms
Per-call timeout (ms)
8000
Backpressure strategy
drop-after-buffer — skip markets that have not drained within 2x poll interval
Locking / mutual exclusion
Redis SETNX on condition_id + cycle to prevent duplicate detection runs
Adversary places and cancels orders to inflate z-scores and trigger false anomaly signals causing strategy pauses
Coordinated thin-book manipulation causes persistent high z-scores on a target market
Mitigations
z_score_threshold tuned to suppress noise from normal spread fluctuations
Anomalies are informational only — strategies apply independent validation before pausing
24. Polymarket V2 Compatibility
Aspect
Value
CLOB version
v2
Collateral asset
pUSD
EIP-712 Exchange domain version
2
Aware of builderCode field
no
Aware of negative-risk markets
yes
Multi-chain ready
no
SDK used
py-clob-client-v2
Settlement contract
CTFExchangeV2
Notes
Detects statistical anomalies in CLOB V2 price, volume, and on-chain flow data. Read-only. No order signing.
API surfaces declared
clob_publicdataonchaininternal
Networks supported
polygon
25. Versioning & Migration
Field
Value
spec
2.0.0
implementation
0.1.0
schema
2
released
None
planned_release
Q3-2026
Migration history
Date
From
To
Reason
Action taken
2026-04-28
n/a
v2-spec
Spec drafted post-CLOB-V2 cutover; bot not yet implemented
Designed against V2 schema (pUSD, builder codes, V2 EIP-712 domain)
26. Acceptance Tests
Unit Tests
Test
Setup
Expected result
Price z-score above threshold emits ObservationReport with anomaly_detected=true
mid_price 5 sigma above rolling mean, baseline_window=3600 s
ObservationReport emitted with z_price=5.0, anomaly_detected=true, ANOMALYDETECTOR_PRICE_SPIKE
Price within threshold emits sampled ObservationReport with anomaly_detected=false
mid_price 0.5 sigma above rolling mean; sample_rate=10
ObservationReport emitted every 10th cycle with anomaly_detected=false
KillSwitch suppresses emission
killswitch.active=true; anomaly present
No ObservationReport; KILL_SWITCH_ACTIVE logged
Integration Tests
Test
Expected result
Anomaly detected, emitted, consumed by LiquidityGuard for pre-trade gate
LiquidityGuard receives ObservationReport with anomaly_detected=true before strategy entry
CLOB API down: STALE_DATA emitted; no anomaly checks run
STALE_DATA WARN; AnomalyDetectorStale alert fires; no ObservationReports
Property Tests
Property
Required behaviour
AnomalyDetector never submits or signs orders
Always true
No ObservationReport emitted when KillSwitch is active
Always true
27. Operational Runbook
AnomalyDetector incidents include genuine market anomalies (informational), API outages, and high z-scores requiring strategy team attention. Page on z-score > 5.
On-call actions
Alert
First step
Diagnosis
Mitigation
Escalate to
AnomalyDetectorHighZScore
Identify condition_id from alert. Check live price and order book on Polymarket.com. Notify strategy team if z_score > 5.
Intelligence pod lead immediately; strategy team on-call for active positions
AnomalyDetectorStale
Check CLOB API and Data API health. Verify last_updated_at_ms for affected markets.
Intelligence pod lead if stale > 10 min
AnomalyDetectorPriceSpike
Verify on Polymarket.com. If genuine price movement, no action needed — downstream strategies consume signal. If book manipulation suspected, alert strategy team.
Strategy team on-call if anomaly persists > 5 min
Manual overrides
reset_baseline — DEL redis key baseline:<condition_id> to reset rolling baseline for a specific market; next N polls rebuild it — After known structural break in market (e.g. major news event resetting price regime)
Healthcheck
Endpoint: /internal/health/anomalydetector | Green: Last detection < 2x poll_interval_s AND Redis reachable AND CLOB + Data APIs returning 200 | Red: No detection for > 10 min OR Redis unreachable OR CLOB API down > 5 min
28. Promotion Gates
A bot does not advance to the next readiness state until every gate below is green. Gates are observable from production data — no subjective sign-off.
Promote to Shadow
Gate
How measured
Threshold
Unit tests pass for price spike, volume spike, insufficient baseline, and KillSwitch suppression
CI test run
100% pass
Promote to Limited live
Gate
How measured
Threshold
False-positive rate < 1% over 48 h on staging with live market data
anomaly_detected=true rate vs manual audit of price charts
< 1% false positives
Promote to General live
Gate
How measured
Threshold
100% detection of synthetic price and volume spikes (5-sigma) over 7-day soak