1.4 LiquidityGuard
LiquidityGuard prevents strategies from placing orders that would consume too much of the visible order-book depth on a given market. It checks book depth, spread, and top-of-book freshness on every OrderIntent and either approves, downsizes, or rejects the order. It cannot change the market, the direction, or the strategy intent — only the size and the timing of execution.
v3 readiness
A bot is done when all four scores are. What does done mean?
1. Bot Identity
| Layer | Risk Risk |
|---|---|
| Bot class | Guardrail |
| Authority | RejectReshape |
| Status | LIVE |
| Readiness | General live |
| Runs before | ExecutionPlan emit |
| Runs after | Strategy OrderIntent |
| Applies to | Every OrderIntent before it reaches the execution layer |
| Default mode | general_live |
| User-visible | Advanced details only |
| Developer owner | Polytraders core — Risk pod |
Operational profile
| Modes supported | quarantine |
|---|
2. Purpose
LiquidityGuard prevents strategies from placing orders that would consume too much of the visible order-book depth on a given market. It checks book depth, spread, and top-of-book freshness on every OrderIntent and either approves, downsizes, or rejects the order. It cannot change the market, the direction, or the strategy intent — only the size and the timing of execution.
3. Why This Bot Matters
Thin-book consumption
An oversized order eats through the visible top-of-book and walks the price several ticks against the user before fully filling, resulting in worse-than-expected execution.
Stale book approved
If depth data is not refreshed, the system may believe there is enough liquidity when the book has thinned out since the last snapshot, leading to surprise price impact.
Excessive spread ignored
Trading into a wide spread means crossing more slippage than the strategy priced in, which can turn a positive-expected-value order into a losing one.
No size floor on top-of-book
An order placed on a market with near-zero resting size can move the price dramatically even for small notional amounts.
No worked examples on this bot yet. Worked examples are optional but strongly recommended — they turn an abstract failure mode into something a developer can verify in a fixture.
4. Required Polymarket Inputs
| Input | Source | Required? | Use |
|---|---|---|---|
| CLOB order book — top 50 levels (bid and ask) | CLOB | Yes | Compute total visible USD depth and the inside spread; compare against thresholds. |
| Best-bid / best-ask resting size | WebSocket | Yes | Determine how large the top-of-book is to enforce min_top_of_book_usd. |
| 30-day median spread for the target market | Data API | Yes | Calculate the spread multiple: current spread divided by 30d median, compared to max_spread_multiple. |
| Top-of-book last-update timestamp | WebSocket | Yes | Detect stale book data; reject if older than stale_top_seconds. |
5. Required Internal Inputs
| Input | Source | Required? | Use |
|---|---|---|---|
| Strategy budget remaining for this market | PortfolioGuard | Yes | Cap the reshape size to the budget remaining so downsized orders don't exceed the portfolio limit. |
| KillSwitch active flag | KillSwitch | Yes | If KillSwitch is active, reject all orders immediately without consulting book data. |
6. Parameter Guide
| Parameter | Default | Warning | Hard | What it controls |
|---|---|---|---|---|
| max_pct_of_visible_depth | 25 | 35 | 60 | Maximum share of top-50-level USD depth that a single order may consume. |
| min_top_of_book_usd | 250 | 100 | 50 | Minimum USD size required at the best bid or best ask before any order is allowed. |
| max_spread_multiple | 2.5 | 2.0 | 4.0 | Maximum allowed spread expressed as a multiple of the 30-day median spread for that market. |
| stale_top_seconds | 60 | 45 | 120 | Maximum age in seconds of the top-of-book snapshot before it is considered stale. |
7. Detailed Parameter Instructions
max_pct_of_visible_depth
What it means
Maximum share of top-50-level USD depth that a single order may consume.
Default
{ "max_pct_of_visible_depth": 25 }
Why this default matters
At 25% the order can fill without moving the inside quote more than one tick on a typical Polymarket book.
Threshold logic
| Condition | Action |
|---|---|
| ≤ 25% of visible depth | APPROVE |
| 25–60% of visible depth | RESHAPE_REQUIRED — downsize to 25% |
| > 60% of visible depth | REJECT — INSUFFICIENT_VISIBLE_DEPTH |
Developer check
if (orderSizeUsd / visibleDepthUsd > p.hard) return reject('INSUFFICIENT_VISIBLE_DEPTH'); else if (orderSizeUsd / visibleDepthUsd > p.default) return reshape({ max_size_usd: visibleDepthUsd * p.default });
User-facing English
We reduced your order because the market did not have enough visible liquidity to fill it without moving the price.
min_top_of_book_usd
What it means
Minimum USD size required at the best bid or best ask before any order is allowed.
Default
{ "min_top_of_book_usd": 250 }
Why this default matters
A top-of-book below $250 means the market is thin enough that even small orders may gap the price.
Threshold logic
| Condition | Action |
|---|---|
| top-of-book ≥ 250 USD | APPROVE |
| 50–250 USD | RESHAPE_REQUIRED — downsize order to at most top-of-book USD |
| < 50 USD | REJECT — INSUFFICIENT_VISIBLE_DEPTH |
Developer check
if (topOfBookUsd < p.hard) return reject('INSUFFICIENT_VISIBLE_DEPTH'); else if (topOfBookUsd < p.default) return reshape({ max_size_usd: topOfBookUsd });
User-facing English
The market has very little resting liquidity right now, so we blocked the order to protect you from large price impact.
max_spread_multiple
What it means
Maximum allowed spread expressed as a multiple of the 30-day median spread for that market.
Default
{ "max_spread_multiple": 2.5 }
Why this default matters
A spread more than 2.5× the 30d median indicates the market is abnormally wide, which increases execution cost and may signal a data or liquidity anomaly.
Threshold logic
| Condition | Action |
|---|---|
| spread ≤ 2.5× median | APPROVE |
| 2.5–4× median | WARN (logged, not blocking by default) |
| > 4× median | REJECT — SPREAD_TOO_WIDE |
Developer check
const mult = currentSpread / medianSpread30d; if (mult > p.hard) return reject('SPREAD_TOO_WIDE'); else if (mult > p.default) return warn('SPREAD_TOO_WIDE');
User-facing English
The market spread was much wider than usual, which would make this trade unexpectedly expensive. We blocked it to protect your position.
stale_top_seconds
What it means
Maximum age in seconds of the top-of-book snapshot before it is considered stale.
Default
{ "stale_top_seconds": 60 }
Why this default matters
A book that has not moved in 60 seconds may reflect a disconnected data feed or an inactive market. Approving on stale data risks acting on a snapshot that no longer reflects real liquidity.
Threshold logic
| Condition | Action |
|---|---|
| book updated within 60 s | APPROVE |
| 60–120 s since last update | WARN — flag latency to monitor |
| > 120 s since last update | REJECT — STALE_MARKET_DATA |
Developer check
const ageSeconds = (Date.now() - bookLastUpdatedMs) / 1000; if (ageSeconds > p.hard) return reject('STALE_MARKET_DATA'); else if (ageSeconds > p.default) return warn('STALE_MARKET_DATA');
User-facing English
The market data had not updated recently enough to safely process this order. We blocked it until a fresh snapshot is available.
8. Default Configuration
{
"bot_id": "risk.liquidity_guard",
"version": "1.0.0",
"mode": "hard_guard",
"defaults": {
"max_pct_of_visible_depth": 25,
"min_top_of_book_usd": 250,
"max_spread_multiple": 2.5,
"stale_top_seconds": 60
},
"locked": {
"min_top_of_book_usd": {
"min": 50
},
"stale_top_seconds": {
"max": 120
}
}
}9. Implementation Flow
- Receive OrderIntent from Strategy layer including market_id, side, size_usd, and price.
- Check KillSwitch active flag from KillSwitch service; if active, return REJECT with reason code KILL_SWITCH_ACTIVE immediately.
- Pull top 50 levels from the CLOB WebSocket book channel for the target market_id.
- Check top-of-book last-update timestamp; if age > stale_top_seconds hard limit, return REJECT with STALE_MARKET_DATA.
- Compute total visible_depth_usd from top 50 levels on the relevant side. If top-of-book USD < min_top_of_book_usd hard floor, return REJECT with INSUFFICIENT_VISIBLE_DEPTH.
- Compute current spread in percentage points and compare to median30d spread from Data API. If spread_multiple > max_spread_multiple hard ceiling, return REJECT with SPREAD_TOO_WIDE.
- Compute pct_of_depth = order.size_usd / visible_depth_usd. If > hard ceiling (60%), return REJECT with INSUFFICIENT_VISIBLE_DEPTH.
- If pct_of_depth > default threshold (25%), compute safe_size_usd = visible_depth_usd × 0.25 and return RESHAPE_REQUIRED with constraints.max_size_usd = safe_size_usd.
- If spread_multiple > warning threshold, attach a warning annotation to the approval without blocking.
- Return APPROVE with inputs_used list and checked_at timestamp.
10. Reference Implementation
Fetches the top-50 CLOB book for the target market, checks KillSwitch, then evaluates depth, spread, and book freshness against configured thresholds. Returns a RiskVote of APPROVE, RESHAPE_REQUIRED, or HARD_REJECT.
Pseudocode is language-agnostic. FETCH = read input. EMIT = produce output. Translate to TS/Python/Go/Rust.
FUNCTION evaluateLiquidity(intent):
// --- 0. KillSwitch gate ---
ks = FETCH internal.killswitch.status
IF ks.active:
EMIT RiskVote(decision=HARD_REJECT, reason=KILL_SWITCH_ACTIVE)
RETURN
// --- 1. Fetch book ---
book = fetchClobPublic('/book?market=' + intent.market_id)
IF book IS NULL OR book.updated_at IS NULL:
EMIT RiskVote(decision=HARD_REJECT, reason=STALE_MARKET_DATA)
RETURN
// --- 2. Staleness check ---
ageSeconds = (now_ms() - book.updated_at_ms) / 1000
IF ageSeconds > params.stale_top_seconds.hard:
EMIT RiskVote(decision=HARD_REJECT, reason=STALE_MARKET_DATA)
RETURN
// --- 3. Compute depth ---
side = IF intent.side == BUY THEN book.asks ELSE book.bids
visibleDepthUsd = SUM(level.price * level.size * collateralDecimals
FOR level IN side[:50])
topOfBookUsd = side[0].price * side[0].size
// --- 4. Top-of-book floor ---
IF topOfBookUsd < params.min_top_of_book_usd.hard:
EMIT RiskVote(decision=HARD_REJECT, reason=INSUFFICIENT_VISIBLE_DEPTH)
RETURN
// --- 5. Spread check ---
spread = book.asks[0].price - book.bids[0].price
median30d = FETCH fetchClobPublic('/spread-stats?market=' + intent.market_id).median30d
spreadMultiple = spread / median30d
IF spreadMultiple > params.max_spread_multiple.hard:
EMIT RiskVote(decision=HARD_REJECT, reason=SPREAD_TOO_WIDE)
RETURN
// --- 6. NegRisk check (optional) ---
IF intent.neg_risk AND isStale(book, params.stale_top_seconds.default):
EMIT RiskVote(decision=WARN, reason=LIQUIDITY_GUARD_NEGRISK_THIN_BOOK)
// --- 7. Depth percentage ---
pctOfDepth = intent.size_usd / visibleDepthUsd
IF pctOfDepth > params.max_pct_of_visible_depth.hard:
EMIT RiskVote(decision=HARD_REJECT, reason=INSUFFICIENT_VISIBLE_DEPTH)
RETURN
IF pctOfDepth > params.max_pct_of_visible_depth.default:
safeSizeUsd = visibleDepthUsd * params.max_pct_of_visible_depth.default
safeSizeUsd = toUsdcUnits(safeSizeUsd) // round to pUSD precision
EMIT RiskVote(decision=RESHAPE_REQUIRED,
reason=INSUFFICIENT_VISIBLE_DEPTH,
constraints={ max_size_usd: safeSizeUsd })
RETURN
// --- 8. Happy path ---
EMIT RiskVote(decision=APPROVE, checked_at=now_iso())
Helpers used
| Helper | Signature | Purpose |
|---|---|---|
| toUsdcUnits | toUsdcUnits(rawUsd: float) -> int | Round a raw USD float to the integer pUSD unit used by CTFExchangeV2 (6 decimals). |
| isStale | isStale(book: BookSnapshot, maxAgeS: int) -> bool | Returns true if book.updated_at_ms is older than maxAgeS seconds relative to now. |
| fetchClobPublic | fetchClobPublic(path: str) -> JSON | Authenticated-free GET against https://clob.polymarket.com; returns parsed JSON or null on error. |
| platformFee | platformFee(notional: float, prob: float, feeRate: float) -> float | Computes C * feeRate * p * (1-p); peaks at p=0.5. Used to estimate transaction cost for depth comparisons. |
SDK calls used
fetchClobPublic('/book?market=0xabc123...&side=asks&depth=50')fetchClobPublic('/spread-stats?market=0xabc123...')fetchClobPublic('/markets/0xabc123...')internal.killswitch.status()
Complexity: O(N) where N = book depth levels (max 50)
11. Wire Examples
Input — what arrives on the wire
OrderIntent from strategy — internal
{
"intent_id": "int_7f3a1b2c9d4e5f60",
"market_id": "0x3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b",
"side": "BUY",
"outcome": "YES",
"size_usd": 1850,
"price": 0.62,
"neg_risk": false,
"generated_at": "2026-05-09T05:51:00Z"
}
CLOB book snapshot (ws_market) — ws_market
{
"market": "0x3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b",
"asks": [
{
"price": "0.62",
"size": "820"
},
{
"price": "0.63",
"size": "1200"
},
{
"price": "0.64",
"size": "3180"
}
],
"bids": [
{
"price": "0.61",
"size": "950"
},
{
"price": "0.60",
"size": "2100"
}
],
"updated_at_ms": 1746768672000
}
Output — what the bot emits
RiskVote — RESHAPE_REQUIRED (order too large for visible depth)
{
"guard_id": "risk.liquidity_guard",
"decision": "RESHAPE_REQUIRED",
"severity": "WARN",
"reason_code": "INSUFFICIENT_VISIBLE_DEPTH",
"message": "Order size 1850 pUSD exceeded 25% of 5200 pUSD visible top-50 depth. Resized to 1300 pUSD.",
"constraints": {
"max_size_usd": 1300,
"passive_only": false,
"close_only": false
},
"inputs_used": [
"clob_public.book.top50",
"data_api.spread.median30d",
"internal.killswitch.status"
],
"checked_at": "2026-05-09T05:51:12Z"
}
RiskVote — HARD_REJECT (stale book)
{
"guard_id": "risk.liquidity_guard",
"decision": "HARD_REJECT",
"severity": "HARD",
"reason_code": "STALE_MARKET_DATA",
"message": "Book last updated 135s ago; stale_top_seconds hard limit is 120s.",
"constraints": {},
"inputs_used": [
"clob_public.book.top50"
],
"checked_at": "2026-05-09T06:05:00Z"
}
Reproduce locally
curl 'https://clob.polymarket.com/book?market=0x3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b'12. Decision Logic
APPROVE
Top-of-book ≥ min_top_of_book_usd, book updated within stale_top_seconds, spread ≤ max_spread_multiple × 30d median, and order size ≤ max_pct_of_visible_depth of total visible depth.
RESHAPE_REQUIRED
Order size exceeds max_pct_of_visible_depth default (25%) but is below the hard ceiling (60%), or top-of-book is between warning and hard floor — emit constraints.max_size_usd capped at the safe level.
REJECT
Top-of-book is stale (> stale_top_seconds), depth is below the hard floor (min_top_of_book_usd), spread is above the hard multiple (max_spread_multiple × 4.0), order size exceeds 60% of visible depth, or KillSwitch is active.
WARNING_ONLY
Not used — LiquidityGuard has reject authority. Spread between warning and hard multiple emits a log annotation but does not block the order.
13. Standard Decision Output
This bot returns a RiskVote object. See RiskVote schema.
{
"guard_id": "risk.liquidity_guard",
"decision": "RESHAPE_REQUIRED",
"severity": "WARN",
"reason_code": "INSUFFICIENT_VISIBLE_DEPTH",
"message": "Order size 1850 USD exceeded 25% of 5200 USD visible top-of-book depth. Resized to 1300 USD.",
"constraints": {
"max_size_usd": 1300,
"passive_only": false,
"close_only": false
},
"inputs_used": [
"clob.book.top50",
"data_api.spread.median30d",
"internal.killswitch.status"
],
"checked_at": "2026-05-09T05:51:12Z"
}14. Reason Codes
| Code | Severity | Meaning | Action | User-facing message |
|---|---|---|---|---|
KILL_SWITCH_ACTIVE | HARD_REJECT | Global kill switch is active; no orders may proceed. | Immediately return HARD_REJECT without consulting book data. | Trading is currently paused. Please try again later. |
STALE_MARKET_DATA | HARD_REJECT | Book snapshot is older than stale_top_seconds hard limit. | Return HARD_REJECT; wait for fresh book before retrying. | Market data had not updated recently. The order was blocked until a fresh snapshot is available. |
INSUFFICIENT_VISIBLE_DEPTH | HARD_REJECT | Order size exceeds the hard depth ceiling or top-of-book is below the hard floor. | Return HARD_REJECT or RESHAPE_REQUIRED depending on which threshold was breached. | There was not enough resting liquidity to safely place your order at the requested size. |
SPREAD_TOO_WIDE | HARD_REJECT | Current spread exceeds max_spread_multiple times the 30-day median. | Return HARD_REJECT; log spread_multiple value. | The gap between the buy and sell prices was much wider than usual. The order was blocked to protect against unexpectedly high transaction cost. |
LIQUIDITY_GUARD_RESHAPE_DEPTH | RESHAPE | Order size is above the default depth percentage but below the hard ceiling. | Return RESHAPE_REQUIRED with constraints.max_size_usd = visibleDepthUsd * default_pct. | Your order was reduced because filling the full size would have consumed too much of the visible liquidity. |
LIQUIDITY_GUARD_SPREAD_WARN | WARN | Spread is between the warning and hard multiple thresholds. | Attach warning annotation to APPROVE; do not block. | |
LIQUIDITY_GUARD_NEGRISK_THIN_BOOK | WARN | NegRisk market book is thin relative to the requested size, increasing definition-shift exposure. | Attach warning annotation; Strategy may reduce size further. | |
LIQUIDITY_GUARD_TOP_BOOK_RESHAPE | RESHAPE | Top-of-book USD is between the warning and hard floor thresholds. | Return RESHAPE_REQUIRED with constraints.max_size_usd = topOfBookUsd. | The market has very little resting liquidity at the best price. Your order was reduced to the available top-of-book size. |
15. Metrics & Logs
Metrics emitted
| Metric | Type | Unit | Labels | Meaning |
|---|---|---|---|---|
polytraders_risk_liquidityguard_decisions_total | counter | count | decision, reason_code, market_id | Total RiskVote decisions emitted, broken down by decision type and reason. |
polytraders_risk_liquidityguard_book_age_seconds | histogram | seconds | market_id | Age of the book snapshot at evaluation time; alerts when p99 approaches stale_top_seconds. |
polytraders_risk_liquidityguard_visible_depth_usd | gauge | usd | market_id | Total visible USD depth across top-50 levels at the time of last check. |
polytraders_risk_liquidityguard_spread_multiple | gauge | ratio | market_id | Current spread divided by 30-day median spread; triggers WARN above 2.5x. |
polytraders_risk_liquidityguard_reshape_size_usd | histogram | usd | market_id | Size delta (original minus reshaped) for RESHAPE_REQUIRED decisions. |
polytraders_risk_liquidityguard_eval_latency_ms | histogram | seconds | Wall-clock latency from intent receipt to RiskVote emit. |
Alerts
| Alert | Condition | Severity | Runbook |
|---|---|---|---|
LiquidityGuardStaleBook | histogram_quantile(0.99, rate(polytraders_risk_liquidityguard_book_age_seconds_bucket[5m])) > 90 | P1 | #runbook-liquidityguard-stale-book |
LiquidityGuardHighRejectRate | rate(polytraders_risk_liquidityguard_decisions_total{decision='HARD_REJECT'}[5m]) / rate(polytraders_risk_liquidityguard_decisions_total[5m]) > 0.5 | P2 | #runbook-liquidityguard-reject-rate |
LiquidityGuardSpreadSpike | polytraders_risk_liquidityguard_spread_multiple > 3.5 | P2 | #runbook-liquidityguard-spread |
LiquidityGuardHighLatency | histogram_quantile(0.99, rate(polytraders_risk_liquidityguard_eval_latency_ms_bucket[5m])) > 200 | P2 | #runbook-liquidityguard-latency |
Dashboards
- Grafana — Risk overview / LiquidityGuard
- Grafana — Market quality / spread and depth heatmap
Log levels
| Level | What gets logged |
|---|---|
| DEBUG | Per-level depth computation and spread_multiple value on every evaluation. |
| INFO | RiskVote decision emitted (decision, reason_code, market_id, size_usd). |
| WARN | Book age approaching stale threshold; spread_multiple between warning and hard limit. |
| ERROR | CLOB book endpoint returned null or non-200; KillSwitch flag unreadable. |
16. Developer Reporting
{
"bot_id": "risk.liquidity_guard",
"decision": "RESHAPE_REQUIRED",
"reason_code": "INSUFFICIENT_VISIBLE_DEPTH",
"inputs_used": [
"clob.book.top50",
"data_api.spread.median30d"
],
"metrics": {
"visible_depth_usd": 5200,
"requested_size_usd": 1850,
"pct_of_depth": 0.356,
"top_of_book_usd": 820,
"spread_multiple": 1.4,
"book_age_seconds": 12
},
"safe_size_usd": 1300,
"checked_at": "2026-05-09T05:51:12Z"
}17. Plain-English Reporting
| Situation | User-facing explanation |
|---|---|
| Order downsized due to thin book | We reduced your order because filling the full size would have consumed too much of the visible liquidity in this market and moved the price against you. |
| Order blocked — market data too old | We blocked this order because the market data had not updated recently. We wait for a fresh snapshot before allowing new orders to protect you from acting on stale information. |
| Order blocked — spread too wide | The gap between the buy and sell prices was much larger than usual. We blocked this order because the high spread would make it significantly more expensive than expected. |
| Order blocked — book too thin | There was not enough resting liquidity in this market to safely place your order. We blocked it to prevent your trade from moving the price by an unusually large amount. |
| Order blocked — size exceeds hard limit | Your order was larger than what this market can safely absorb. Even after considering a downsize, the remaining liquidity was insufficient. Please try a smaller amount. |
18. Failure-Mode Block
| main_failure_mode | Allowing an oversized order through a thin book, causing significant adverse price impact for the user. |
|---|---|
| false_positive_risk | Downsizing or rejecting a legitimate order on a temporarily quiet but sufficiently deep market, such as early in the trading day before resting liquidity has built up. |
| false_negative_risk | Approving an order against a book that was valid at snapshot time but has since been pulled, if the staleness window is set too wide. |
| safe_fallback | If CLOB book data is absent or older than stale_top_seconds hard limit, always reject with STALE_MARKET_DATA. LiquidityGuard never approves on missing or unverifiable data. |
| required_dependencies | CLOB WebSocket book channel, Data API 30-day median spread, PortfolioGuard ledger (budget remaining), KillSwitch active flag |
19. Failure-Injection Recipes
| Scenario | How to inject | Expected behaviour | Recovery |
|---|---|---|---|
STALE_BOOK | Freeze WS market channel for 130s | All evaluations return HARD_REJECT(STALE_MARKET_DATA) once book_age_seconds > 120 | Returns to APPROVE within 5s of fresh book delivery. |
EMPTY_BOOK | Return empty asks/bids arrays from CLOB mock | topOfBookUsd=0 triggers HARD_REJECT(INSUFFICIENT_VISIBLE_DEPTH) | Immediate on next evaluation with a non-empty book. |
WIDE_SPREAD | Set asks[0].price=0.90, bids[0].price=0.10 so spread_multiple > 4.0 | HARD_REJECT(SPREAD_TOO_WIDE) | Next evaluation where spread_multiple falls below hard limit resumes normally. |
KILL_SWITCH_ON | Set internal.killswitch.status.active = true | HARD_REJECT(KILL_SWITCH_ACTIVE) on every intent without book fetch | Returns to normal pipeline on manual KillSwitch reset. |
CLOB_ENDPOINT_DOWN | Block TCP to clob.polymarket.com | fetchClobPublic returns null; HARD_REJECT(STALE_MARKET_DATA) | Returns to APPROVE within one evaluation cycle after endpoint is reachable. |
20. State & Persistence
LiquidityGuard is stateless per evaluation; it holds no persistent state beyond an in-memory cache of the last book snapshot per market.
State stores
| Name | Kind | Key | Value shape | TTL | Durability |
|---|---|---|---|---|---|
book_cache | in-memory | market_id | { asks: Level[], bids: Level[], updated_at_ms: int } | 120s | best-effort |
Cold-start recovery
On cold start, the cache is empty. The first evaluation for each market_id triggers a fresh CLOB fetch.
On restart
Book snapshots are re-fetched on first evaluation; no durable state is loaded. If the WebSocket reconnects before the first evaluation, snapshots are populated from the reconnection event.
21. Concurrency & Idempotency
| Aspect | Specification |
|---|---|
| Execution model | single-threaded event loop |
| Max in-flight | 200 |
| Idempotency key | intent_id |
| Replay-safe | True |
| Deduplication | by intent_id within a 24h window |
| Ordering guarantees | FIFO per market_id |
| Per-call timeout (ms) | 150 |
| Backpressure strategy | drop newest |
| Locking / mutual exclusion | per-market_id mutex |
22. Dependencies
Depends on (must run first)
| Bot | Why | Contract |
|---|---|---|
| risk.kill_switch | Global brake — checked first before any book data is read. | RiskVote.HARD_REJECT(KILL_SWITCH_ACTIVE) short-circuits all further evaluation. |
| risk.portfolio_guard | Budget remaining for this market caps the reshape ceiling. | Reshape size is min(safe_depth_size, portfolio_budget_remaining). |
Emits to (downstream consumers)
| Bot | Why | Contract |
|---|---|---|
| exec.smart_router | Approved or reshaped RiskVote passes to SmartRouter for ExecutionPlan construction. | APPROVE or RESHAPE_REQUIRED RiskVote is consumed; HARD_REJECT causes SmartRouter to discard the intent. |
Used by (auto-aggregated)
External services
| Service | Endpoint | SLA assumed | On failure |
|---|---|---|---|
| CLOB API (read) | https://clob.polymarket.com | 99.95% / 200ms p99 | HARD_REJECT(STALE_MARKET_DATA) until book is fresh. |
| WS market feed | wss://ws-subscriptions-clob.polymarket.com/ws/market | best-effort / sub-100ms | Falls back to REST poll; if REST also fails, HARD_REJECT. |
| Data API (spread stats) | https://data-api.polymarket.com | 99.9% / 500ms p99 | WARN emitted; evaluation continues with best available spread estimate. |
23. Security Surfaces
LiquidityGuard is read-only and stateless. It never signs orders or holds secrets.
Signing surface
This bot does NOT sign anything.
Abuse vectors considered
- Replaying a stale book snapshot to bypass depth checks
- Injecting artificially large depth values to allow oversized orders
Mitigations
- per-intent_id idempotency prevents replay of the same evaluation
- book.updated_at_ms is checked against wall clock; any snapshot older than stale_top_seconds is rejected regardless of depth values
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 | @polymarket/clob-client-v2 ^2.x |
| Settlement contract | CTFExchangeV2 on Polygon |
| Notes | All depth values are denominated in pUSD (USDC-backed ERC-20). Order fields evaluated here use the V2 schema (timestamp/metadata/builder); nonce and feeRateBps fields are not present. |
API surfaces declared
Networks supported
25. Versioning & Migration
| Field | Value |
|---|---|
| spec | 2.0.0 |
| implementation | 2.1.3 |
| schema | 2 |
| released | 2026-04-28 |
Migration history
| Date | From | To | Reason | Action taken |
|---|---|---|---|---|
| 2026-04-28 | v1 (USDC.e + HMAC builder) | v2 (pUSD + builderCode field) | Polymarket V2 cutover | Migrated SDK, replaced HMAC builder logic with on-order builderCode, removed feeRateBps from order construction. Depth values now denominated in pUSD. |
26. Acceptance Tests
Unit Tests
| Test | Setup | Expected result |
|---|---|---|
| Approve when all thresholds pass | depth_usd=2000, size_usd=400, top_of_book_usd=600, spread_multiple=1.2, book_age_s=10 | APPROVE with no constraints |
| Reshape when size is 30% of depth | depth_usd=1000, size_usd=300, hard=60, default=25 | RESHAPE_REQUIRED with constraints.max_size_usd=250 |
| Reject when size exceeds 60% hard ceiling | depth_usd=1000, size_usd=650 | REJECT with reason_code=INSUFFICIENT_VISIBLE_DEPTH |
| Reject when book age exceeds hard stale limit | book_age_s=130, stale_top_seconds=60 | REJECT with reason_code=STALE_MARKET_DATA |
| Reject when spread_multiple > 4.0 | current_spread=0.08, median_spread=0.01 (multiple=8.0) | REJECT with reason_code=SPREAD_TOO_WIDE |
| Reshape when top-of-book is between warning and hard floor | top_of_book_usd=150, min_top_of_book_usd=250, hard=50 | RESHAPE_REQUIRED with constraints.max_size_usd=150 |
| Reject when top-of-book is below hard floor | top_of_book_usd=30, min_top_of_book_usd hard=50 | REJECT with reason_code=INSUFFICIENT_VISIBLE_DEPTH |
Integration Tests
| Test | Expected result |
|---|---|
| Rejects on stale book snapshot from live WebSocket | REJECT(STALE_MARKET_DATA) when WebSocket book channel has not emitted an update within stale_top_seconds |
| Reshape flows through to ExecutionPlan with reduced size | ExecutionPlan downstream receives constraints.max_size_usd and does not exceed it |
| KillSwitch active causes immediate rejection before book check | REJECT emitted without querying CLOB when KillSwitch active flag is true |
Property Tests
| Property | Required behaviour |
|---|---|
| Missing or absent book data never results in APPROVE | Always true — null or empty book must produce REJECT(STALE_MARKET_DATA) |
| Reshape size is always strictly ≤ requested order size | Always true — constraints.max_size_usd ≤ original order size_usd |
| Approved order size never exceeds max_pct_of_visible_depth of visible depth | Always true — for any APPROVE, size_usd / visible_depth_usd ≤ default threshold |
27. Operational Runbook
LiquidityGuard incidents are typically caused by a stale CLOB book feed or an abnormal spread spike. On-call should first confirm whether the WS market feed is connected before adjusting parameters.
On-call actions
| Alert | First step | Diagnosis | Mitigation | Escalate to |
|---|---|---|---|---|
LiquidityGuardStaleBook | Check WS market feed connection status in the Grafana panel. | If WS is disconnected, check clob.polymarket.com status page. If WS is connected, check for clock skew between the bot host and exchange. | Reconnect WS feed; if clock skew, resync NTP. Do not increase stale_top_seconds without approval. | Risk pod lead if feed is down > 5 minutes. |
LiquidityGuardHighRejectRate | Check reason_code distribution on the HARD_REJECT counter. | If dominated by STALE_MARKET_DATA, follow stale-book runbook. If INSUFFICIENT_VISIBLE_DEPTH, check whether a specific market has thinned unusually. | For thin markets, pause the affected strategy until liquidity recovers. Do not lower depth thresholds. | Risk pod lead if reject rate persists > 10 minutes. |
LiquidityGuardSpreadSpike | Identify which market_id is driving the spread_multiple gauge above 3.5. | Check Gamma API for market metadata; confirm no oracle dispute or resolution event. | If spread is genuine (thin book, not a data error), the guard is working correctly. If a data error, restart the WS subscription for that market. | OracleRiskMonitor on-call if oracle dispute is active. |
LiquidityGuardHighLatency | Check CLOB REST response times in the latency histogram. | If CLOB latency is high, the REST fallback path is being used more than expected. | Confirm WS is connected. Reduce bot concurrency if host is CPU-bound. | Infra on-call if CLOB p99 latency > 500ms sustained. |
Manual overrides
polytraders bot pause risk.liquidity_guard— Stops emitting RiskVotes; all intents fall through to the next guardrail without a liquidity check. Use only during a known feed outage.polytraders bot flush-cache risk.liquidity_guard --market <market_id>— Evicts the in-memory book cache for a specific market, forcing a fresh CLOB fetch on the next evaluation.
Healthcheck
GET /health → 200 if WS market feed is connected and last book update for any tracked market is within stale_top_seconds.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 including all acceptance_tests.unit cases | CI test run | 100% pass |
| Integration test: stale book → HARD_REJECT verified | Integration test suite | Pass |
Promote to Limited live
| Gate | How measured | Threshold |
|---|---|---|
| Shadow mode reject rate matches expected baseline within 10% | Grafana shadow vs live comparison dashboard | < 10% divergence over 48h |
| p99 evaluation latency < 150ms | polytraders_risk_liquidityguard_eval_latency_ms histogram | p99 < 150ms |
Promote to General live
| Gate | How measured | Threshold |
|---|---|---|
| Zero HARD_REJECT(STALE_MARKET_DATA) during normal operating hours over 7 days | LiquidityGuardStaleBook alert history | 0 firings |
| Reshape decisions correctly cap order size in E2E flow | E2E integration tests + manual audit of fill logs | 100% compliance |
29. Developer Checklist
Ready-to-ship score: 27/27 sections complete · 100%
| Requirement | Status |
|---|---|
| Purpose defined | ✓ done |
| Required inputs listed | ✓ done |
| Parameters defined | ✓ done |
| Defaults defined | ✓ done |
| Warning thresholds defined | ✓ done |
| Hard thresholds defined | ✓ done |
| Safe fallback defined | ✓ done |
| Structured output defined | ✓ done |
| Developer log defined | ✓ done |
| Plain-English explanation | ✓ done |
| Unit tests defined | ✓ done |
| Integration tests defined | ✓ done |
| Property tests defined | ✓ done |
| Failure-mode block complete | ✓ done |
| Reference implementation pseudocode | ✓ done |
| Wire examples (input + output) | ✓ done |
| Reason codes listed | ✓ done |
| Metrics & logs defined | ✓ done |
| State & persistence defined | ✓ done |
| Concurrency & idempotency defined | ✓ done |
| Dependencies declared | ✓ done |
| Security surfaces declared | ✓ done |
| Polymarket V2 compatibility declared | ✓ done |
| Version & migration history declared | ✓ done |
| Operational runbook defined | ✓ done |
| Promotion gates defined | ✓ done |
| Failure-injection recipes defined | ✓ done |