Polytraders Dev Guide
internal
v3 spine Phase 1 · Shared contracts 9 demo-wired · 0 shadow-ready · 0 production-live · 100 pending · 109 total 15/33 infra tasks the plan status board
HomeBy LayerRisk1.3 OracleRiskMonitor

1.3 OracleRiskMonitor

Risk Guardrail RejectReshape LIVE General live capital · Direct P4 · Core risk pending flagship reference bot

OracleRiskMonitor watches the UMA Optimistic Oracle queue for proposals and active disputes on markets where open positions exist. When a market enters a resolution proposal or a dispute window, the bot can block new orders on that market, require reduced size, or flag a position for review. It protects against the scenario where a trade is submitted into a market moments before a contested resolution flips the outcome. It never overrides the strategy intent or changes the direction of an order — it only controls whether and how much the order is permitted to proceed.

v3 readiness

Docs27/27
donehow scored
Impl0/15
pendinghow scored
Backtest0/4
pendinghow scored
Runtime0/8
pendinghow scored

A bot is done when all four scores are. What does done mean?

1. Bot Identity

LayerRisk  Risk
Bot classGuardrail
AuthorityRejectReshape
StatusLIVE
ReadinessGeneral live
Runs beforeExecutionPlan emit
Runs afterStrategy OrderIntent
Applies toEvery OrderIntent on markets that use the UMA Optimistic Oracle for resolution
Default modegeneral_live
User-visibleAdvanced details only
Developer ownerPolytraders core — Risk pod

Operational profile

Modes supportedquarantine

2. Purpose

OracleRiskMonitor watches the UMA Optimistic Oracle queue for proposals and active disputes on markets where open positions exist. When a market enters a resolution proposal or a dispute window, the bot can block new orders on that market, require reduced size, or flag a position for review. It protects against the scenario where a trade is submitted into a market moments before a contested resolution flips the outcome. It never overrides the strategy intent or changes the direction of an order — it only controls whether and how much the order is permitted to proceed.

3. Why This Bot Matters

  • Trading into an active oracle dispute

    A position opened after a dispute was filed may be immediately underwater if the dispute resolves against the expected outcome; the resolution risk was not priced in.

  • Holding a full position through the proposal window

    Markets entering their proposal phase have uncertain resolution timing. Holding full size through this window increases exposure to a binary outcome that cannot be hedged once the proposal is live.

  • Stale oracle status

    If the oracle queue feed is unavailable, a strategy could open or increase a position without knowing a dispute is already active. The safe behaviour is to block, not to approve on missing data.

  • Neg-risk market definition shift during proposal

    On neg-risk markets, the 'Other' outcome definition can shift if a proposal is disputed, potentially invalidating the expected payout structure.

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

InputSourceRequired?Use
Market resolution-source flag and dispute window metadataGamma APIYesIdentify whether the market uses the UMA oracle and retrieve the resolution window start and end times.
UMA Optimistic Oracle on-chain proposal and dispute eventsUMA Optimistic OracleYesDetect when a proposal has been submitted or a dispute has been filed for a market relevant to open positions or pending orders.
Open position list with market identifiersData APIYesCross-reference oracle events against markets where the account currently holds a position, to determine which events require action.
Neg-risk flag per marketGamma APINoApply stricter reduce_at_proposal_pct on neg-risk markets, as definition shifts can affect multiple related markets simultaneously.

5. Required Internal Inputs

InputSourceRequired?Use
Current position size per marketPortfolioGuardYesCalculate the maximum allowed position size after applying reduce_at_proposal_pct during the proposal window.
KillSwitch active flagKillSwitchYesIf KillSwitch is active, reject all orders without checking oracle status.

6. Parameter Guide

ParameterDefaultWarningHardWhat it controls
reduce_at_proposal_pct5070100Maximum allowed position size, expressed as a percentage of the configured per-market limit, when a market has an active UMA proposal but no dispute yet.
block_disputedTrueNoneNoneWhen true, reject all new orders on any market where a UMA dispute is currently active.
max_dispute_window_h4872168Maximum duration in hours that a dispute window is considered 'recent' for monitoring purposes. Disputes older than this limit are treated as stale and require a manual review flag.
downgrade_size_by_confidenceTrueNoneNoneWhen true, apply an additional proportional reduction to the allowed order size based on the elapsed fraction of the proposal window. As the window progresses, less new size is permitted.

7. Detailed Parameter Instructions

reduce_at_proposal_pct

What it means

Maximum allowed position size, expressed as a percentage of the configured per-market limit, when a market has an active UMA proposal but no dispute yet.

Default

{ "reduce_at_proposal_pct": 50 }

Why this default matters

Cutting position size to 50% during a proposal window limits exposure to a binary outcome while still allowing strategies to maintain partial coverage.

Threshold logic

ConditionAction
No proposal activeAPPROVE at full size
Proposal active, size ≤ 50% of limitAPPROVE
Proposal active, size > 50% of limitRESHAPE_REQUIRED — cap to 50% of per-market limit
reduce_at_proposal_pct = 100 (locked)REJECT all new orders on that market during proposal window

Developer check

if (proposalActive && orderSize > limit * (p.default / 100)) return reshape({ max_size_usd: limit * (p.default / 100) });

User-facing English

This market is currently in its resolution proposal window. We limited your order size to reduce exposure while the outcome is being confirmed.

block_disputed

What it means

When true, reject all new orders on any market where a UMA dispute is currently active.

Default

{ "block_disputed": true }

Why this default matters

An active dispute means the resolution outcome is genuinely uncertain and contested on-chain. Adding exposure during a live dispute is inconsistent with sound risk management.

Threshold logic

ConditionAction
block_disputed=true AND dispute activeREJECT — ORACLE_DISPUTE_ACTIVE
block_disputed=false AND dispute activeWARN only — allow with annotation

Developer check

if (p.block_disputed && disputeActive) return reject('ORACLE_DISPUTE_ACTIVE');

User-facing English

This market has an active resolution dispute. We blocked this order while the dispute is ongoing.

max_dispute_window_h

What it means

Maximum duration in hours that a dispute window is considered 'recent' for monitoring purposes. Disputes older than this limit are treated as stale and require a manual review flag.

Default

{ "max_dispute_window_h": 48 }

Why this default matters

UMA disputes typically resolve within 48 hours. Tracking disputes beyond 168 hours (one week) adds noise without meaningful risk signal.

Threshold logic

ConditionAction
Dispute age ≤ 48 hBlock (block_disputed applies)
Dispute age 48–168 hWARN — flag for manual review
Dispute age > 168 hTreat as resolved; escalate to incident commander

Developer check

const ageH = (Date.now() - disputeStartMs) / 3600000; if (ageH > p.hard) escalate('DISPUTE_OVERDUE');

User-facing English

This market has had an unresolved dispute for an unusually long time. New orders are paused until the situation is reviewed.

downgrade_size_by_confidence

What it means

When true, apply an additional proportional reduction to the allowed order size based on the elapsed fraction of the proposal window. As the window progresses, less new size is permitted.

Default

{ "downgrade_size_by_confidence": true }

Why this default matters

Risk increases as a market moves deeper into its resolution window. Tapering size over time reflects rising uncertainty without requiring a hard binary block.

Threshold logic

ConditionAction
downgrade_size_by_confidence=true, proposal fraction < 0.5Use reduce_at_proposal_pct as-is
downgrade_size_by_confidence=true, proposal fraction ≥ 0.5Halve the allowed size cap proportionally to elapsed window fraction
downgrade_size_by_confidence=falseUse reduce_at_proposal_pct flat regardless of elapsed time

Developer check

if (p.downgrade_size_by_confidence) cap = cap * (1 - proposalFraction * 0.5);

User-facing English

The resolution window for this market is well underway. We reduced the maximum order size further to account for the increased uncertainty.

8. Default Configuration

{
  "bot_id": "risk.oracle_risk_monitor",
  "version": "1.0.0",
  "mode": "hard_guard",
  "defaults": {
    "reduce_at_proposal_pct": 50,
    "block_disputed": true,
    "max_dispute_window_h": 48,
    "downgrade_size_by_confidence": true
  },
  "locked": {
    "block_disputed": {
      "immutable": true
    },
    "max_dispute_window_h": {
      "max": 168
    }
  }
}

9. Implementation Flow

  1. Receive OrderIntent from Strategy layer including market_id, side, and size_usd.
  2. Check KillSwitch active flag; if active, return REJECT with KILL_SWITCH_ACTIVE immediately.
  3. Fetch market resolution-source metadata from Gamma API for the target market_id to confirm UMA oracle is used.
  4. Subscribe to or poll UMA Optimistic Oracle on-chain events to detect any active proposal or dispute for this market.
  5. If a dispute is active and block_disputed=true, return REJECT with reason_code=ORACLE_DISPUTE_ACTIVE.
  6. If a proposal is active (but no dispute), retrieve the current position size for this market from PortfolioGuard.
  7. Apply reduce_at_proposal_pct to compute the maximum allowed size. If downgrade_size_by_confidence=true, further reduce the cap based on elapsed fraction of the proposal window.
  8. If order.size_usd > computed cap, return RESHAPE_REQUIRED with constraints.max_size_usd set to the computed cap.
  9. If the market is neg-risk, apply a 20% additional reduction to the cap due to potential definition-shift risk.
  10. Return APPROVE if all checks pass, with inputs_used and checked_at timestamp.

10. Reference Implementation

Polls the UMA Optimistic Oracle for active proposals and disputes on the target market, then applies proposal-window size caps or hard rejects, depending on dispute status and the elapsed fraction of the proposal window.

Pseudocode is language-agnostic. FETCH = read input. EMIT = produce output. Translate to TS/Python/Go/Rust.

FUNCTION evaluateOracleRisk(intent):
  // --- 0. KillSwitch gate ---
  ks = FETCH internal.killswitch.status
  IF ks.active:
    EMIT RiskVote(decision=HARD_REJECT, reason=KILL_SWITCH_ACTIVE)
    RETURN

  // --- 1. Fetch market resolution metadata ---
  marketMeta = fetchClobPublic('/markets/' + intent.market_id)
  IF marketMeta IS NULL OR isStale(marketMeta, params.stale_top_seconds):
    EMIT RiskVote(decision=HARD_REJECT, reason=STALE_MARKET_DATA)
    RETURN

  IF marketMeta.resolution_source != 'UMA':
    // Non-UMA markets pass through without oracle checks
    EMIT RiskVote(decision=APPROVE)
    RETURN

  // --- 2. Fetch UMA oracle state ---
  oracleState = FETCH onchain.uma.proposal_status(intent.market_id)
  // oracleState: { proposalActive, disputeActive, proposalStartMs, challengeWindowMs }
  // $750 pUSD proposer bond; 2h challenge window; disputed → DVM 24-48h

  // --- 3. Hard reject on active dispute ---
  IF oracleState.disputeActive AND params.block_disputed:
    EMIT RiskVote(decision=HARD_REJECT, reason=ORACLE_DISPUTE_ACTIVE)
    RETURN

  // --- 4. Proposal window size cap ---
  IF oracleState.proposalActive:
    position = FETCH internal.portfolio_guard.market_position(intent.market_id)
    proposalFraction = (now_ms() - oracleState.proposalStartMs)
                       / oracleState.challengeWindowMs
    cap = position.per_market_limit * (params.reduce_at_proposal_pct / 100)
    IF params.downgrade_size_by_confidence AND proposalFraction >= 0.5:
      cap = cap * (1 - proposalFraction * 0.5)
    // NegRisk: apply extra 20% reduction
    IF marketMeta.neg_risk:
      cap = cap * 0.80
    cap = toUsdcUnits(cap)
    IF intent.size_usd > cap:
      EMIT RiskVote(decision=RESHAPE_REQUIRED,
                    reason=ORACLE_RESOLUTION_PENDING,
                    constraints={ max_size_usd: cap })
      RETURN

  // --- 5. Bond check ---
  IF oracleState.proposerBondPUsd < 750:
    EMIT RiskVote(decision=HARD_REJECT, reason=ORACLE_PROPOSER_BOND_BELOW_MIN)
    RETURN

  // --- 6. Happy path ---
  EMIT RiskVote(decision=APPROVE, checked_at=now_iso())

Helpers used

HelperSignaturePurpose
fetchClobPublicfetchClobPublic(path: str) -> JSONUnauthenticated GET against https://clob.polymarket.com; returns parsed JSON or null on error.
isStaleisStale(snapshot: any, maxAgeS: int) -> boolReturns true if snapshot._fetched_at_ms is older than maxAgeS seconds.
toUsdcUnitstoUsdcUnits(rawUsd: float) -> intRounds a raw pUSD float to the integer unit used by CTFExchangeV2 (6 decimals).
platformFeeplatformFee(notional: float, prob: float, feeRate: float) -> floatComputes platform fee C * feeRate * p * (1-p); used for cost estimation during proposal window.

SDK calls used

  • fetchClobPublic('/markets/0xabc123...')
  • fetchClobPublic('/book?market=0xabc123...')
  • onchain.uma.proposal_status('0xabc123...')
  • internal.killswitch.status()
  • internal.portfolio_guard.market_position('0xabc123...')

Complexity: O(1) per intent — single market oracle state lookup

11. Wire Examples

Input — what arrives on the wire

OrderIntent on UMA-resolved market in active disputeinternal

{
  "intent_id": "int_9c2e4d6f8a0b1c3e",
  "market_id": "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b",
  "side": "BUY",
  "outcome": "YES",
  "size_usd": 600,
  "neg_risk": false,
  "generated_at": "2026-05-09T07:00:00Z"
}

UMA oracle state (on-chain)clob_public

{
  "market_id": "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b",
  "resolution_source": "UMA",
  "proposal_active": true,
  "dispute_active": true,
  "proposal_start_ms": 1746770400000,
  "challenge_window_ms": 7200000,
  "proposer_bond_pusd": 750,
  "dispute_filed_at": "2026-05-09T07:00:00Z",
  "neg_risk": false
}

Output — what the bot emits

RiskVote — HARD_REJECT (active dispute)

{
  "guard_id": "risk.oracle_risk_monitor",
  "decision": "HARD_REJECT",
  "severity": "HARD",
  "reason_code": "ORACLE_DISPUTE_ACTIVE",
  "message": "Market 0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b has an active UMA resolution dispute filed at 2026-05-09T07:00:00Z. New orders are blocked until the dispute resolves.",
  "constraints": {},
  "inputs_used": [
    "gamma_api.market.resolution_source",
    "onchain.uma.dispute_events",
    "internal.killswitch.status"
  ],
  "checked_at": "2026-05-09T07:02:00Z"
}

RiskVote — RESHAPE_REQUIRED (proposal window, no dispute)

{
  "guard_id": "risk.oracle_risk_monitor",
  "decision": "RESHAPE_REQUIRED",
  "severity": "WARN",
  "reason_code": "ORACLE_RESOLUTION_PENDING",
  "message": "Market is in UMA proposal window (fraction=0.40). Max size capped to 1000 pUSD.",
  "constraints": {
    "max_size_usd": 1000,
    "passive_only": false,
    "close_only": false
  },
  "inputs_used": [
    "gamma_api.market.resolution_source",
    "onchain.uma.proposal_events",
    "internal.portfolio_guard.position"
  ],
  "checked_at": "2026-05-09T08:00:00Z"
}

Reproduce locally

curl 'https://clob.polymarket.com/markets/0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b'

12. Decision Logic

APPROVE

No active proposal and no active dispute for the target market, or proposal is active and order size is within the reduce_at_proposal_pct cap after downgrade adjustment.

RESHAPE_REQUIRED

Market is in proposal window and order size exceeds the reduce_at_proposal_pct cap — emit constraints.max_size_usd at the computed safe level.

REJECT

Active UMA dispute and block_disputed=true (ORACLE_DISPUTE_ACTIVE), oracle feed is unavailable or stale (STALE_MARKET_DATA), or KillSwitch is active (KILL_SWITCH_ACTIVE).

WARNING_ONLY

Not used as primary path — OracleRiskMonitor has reject authority. Spread-style anomalies and overdue disputes emit log annotations but the hard guard path is always reject or reshape.

13. Standard Decision Output

This bot returns a RiskVote object. See RiskVote schema.

{
  "guard_id": "risk.oracle_risk_monitor",
  "decision": "REJECT",
  "severity": "HARD",
  "reason_code": "ORACLE_DISPUTE_ACTIVE",
  "message": "Market CLOB:0xabc123 has an active UMA resolution dispute filed at 2026-05-08T14:00:00Z. New orders are blocked until the dispute resolves.",
  "constraints": {},
  "inputs_used": [
    "gamma_api.market.resolution_source",
    "uma.oracle.dispute_events",
    "internal.killswitch.status"
  ],
  "checked_at": "2026-05-09T07:00:00Z"
}

14. Reason Codes

CodeSeverityMeaningActionUser-facing message
KILL_SWITCH_ACTIVEHARD_REJECTGlobal kill switch is active.Immediately return HARD_REJECT without oracle lookup.Trading is currently paused. Please try again later.
STALE_MARKET_DATAHARD_REJECTOracle feed or market metadata is older than the staleness threshold.Return HARD_REJECT; retry on next fresh fetch.Oracle status could not be verified. The order was blocked until a fresh status is available.
ORACLE_DISPUTE_ACTIVEHARD_REJECTAn active UMA dispute is filed for this market; outcome is contested on-chain.Return HARD_REJECT if block_disputed=true.This market has an active resolution dispute. Orders are blocked while the dispute is ongoing.
ORACLE_RESOLUTION_PENDINGRESHAPEMarket is in the 2-hour UMA proposal window but no dispute has been filed yet.Return RESHAPE_REQUIRED with cap = reduce_at_proposal_pct * per_market_limit.This market is in its resolution window. Your order size was reduced to limit exposure while the outcome is being confirmed.
ORACLE_PROPOSER_BOND_BELOW_MINHARD_REJECTThe UMA proposer bond for this market is below the required 750 pUSD minimum, indicating a misconfigured or suspicious market.Return HARD_REJECT; log market_id and observed bond amount.This market could not be verified for safe trading. The order was blocked.
ORACLE_RESOLUTION_CONFIDENCE_DOWNGRADERESHAPEMarket is more than 50% through its proposal window; size cap is further reduced proportionally.Apply downgrade formula: cap = cap * (1 - proposal_fraction * 0.5).This market is well into its resolution window. The maximum order size was reduced further due to the increased uncertainty.
ORACLE_NEGRISK_PROPOSAL_REDUCTIONRESHAPENegRisk market in proposal window; extra 20% size reduction applied due to definition-shift risk.Apply 0.8 multiplier to cap before emitting RESHAPE_REQUIRED.This is a neg-risk market in its resolution phase. An additional size reduction was applied.
ORACLE_DISPUTE_OVERDUEWARNDispute age exceeds max_dispute_window_h; escalation required.Emit WARN annotation and escalate to incident commander; continue blocking per block_disputed.

15. Metrics & Logs

Metrics emitted

MetricTypeUnitLabelsMeaning
polytraders_risk_oracleriskmonitor_decisions_totalcountercountdecision, reason_code, market_idTotal RiskVote decisions broken down by decision type and reason.
polytraders_risk_oracleriskmonitor_dispute_age_hoursgaugesecondsmarket_idAge of the active dispute for markets currently in dispute; triggers alert when approaching max_dispute_window_h.
polytraders_risk_oracleriskmonitor_proposal_fractiongaugeratiomarket_idElapsed fraction of the UMA 2-hour proposal window; drives confidence-downgrade logic.
polytraders_risk_oracleriskmonitor_oracle_fetch_latency_mshistogramsecondsLatency of UMA on-chain oracle state fetch.
polytraders_risk_oracleriskmonitor_markets_in_proposalgaugecountNumber of markets currently in an active UMA proposal window.
polytraders_risk_oracleriskmonitor_markets_in_disputegaugecountNumber of markets currently in an active UMA dispute.

Alerts

AlertConditionSeverityRunbook
OracleRiskMonitorDisputeActivepolytraders_risk_oracleriskmonitor_markets_in_dispute > 0P1#runbook-oracle-dispute-active
OracleRiskMonitorDisputeOverduepolytraders_risk_oracleriskmonitor_dispute_age_hours > 48P0#runbook-oracle-dispute-overdue
OracleRiskMonitorStaleFeedrate(polytraders_risk_oracleriskmonitor_decisions_total{reason_code='STALE_MARKET_DATA'}[5m]) > 0.1P1#runbook-oracle-stale-feed
OracleRiskMonitorHighRejectRaterate(polytraders_risk_oracleriskmonitor_decisions_total{decision='HARD_REJECT'}[5m]) / rate(polytraders_risk_oracleriskmonitor_decisions_total[5m]) > 0.3P2#runbook-oracle-reject-rate

Dashboards

  • Grafana — Risk overview / OracleRiskMonitor
  • Grafana — UMA oracle status / proposal and dispute tracker

Log levels

LevelWhat gets logged
DEBUGproposalFraction value, cap computation, and bond amount on every evaluation.
INFORiskVote decision emitted (decision, reason_code, market_id).
WARNDispute age approaching max_dispute_window_h; oracle feed latency elevated.
ERRORUMA on-chain feed unreachable; market metadata fetch returned null.

16. Developer Reporting

{
  "bot_id": "risk.oracle_risk_monitor",
  "decision": "REJECT",
  "reason_code": "ORACLE_DISPUTE_ACTIVE",
  "inputs_used": [
    "gamma_api.market.resolution_source",
    "uma.oracle.dispute_events"
  ],
  "metrics": {
    "market_id": "CLOB:0xabc123",
    "dispute_filed_at": "2026-05-08T14:00:00Z",
    "dispute_age_h": 17.0,
    "block_disputed": true,
    "proposal_active": true,
    "proposal_fraction_elapsed": 0.63
  },
  "checked_at": "2026-05-09T07:00:00Z"
}

17. Plain-English Reporting

SituationUser-facing explanation
Order blocked — oracle dispute activeThis market currently has a contested resolution. Someone has challenged the proposed outcome on-chain. We blocked your order while this dispute is active because the final result is genuinely uncertain.
Order downsized — market in proposal windowThis market has entered its resolution phase. We reduced your order size to limit your exposure while the outcome is being confirmed.
Order further reduced — late in proposal windowThis market is well into its resolution window. We reduced the maximum allowed order size further because the uncertainty increases as the resolution deadline approaches.
Order blocked — oracle feed unavailableWe could not verify the current oracle status for this market. Rather than proceed without this information, we blocked the order until a fresh oracle status is available.
Neg-risk market — order reduced for definition-shift riskThis is a neg-risk market currently in proposal. We applied an additional size reduction because the outcome definition for related markets can shift during the proposal period.

18. Failure-Mode Block

main_failure_modeApproving a trade into a market with an active dispute, resulting in a position that is exposed to a binary resolution outcome the strategy did not price in.
false_positive_riskBlocking or downsizing orders on a market where a proposal has been filed but is very likely to pass uncontested, causing unnecessary missed exposure.
false_negative_riskApproving an order against stale oracle data that was up-to-date at fetch time but has since entered a dispute, if the polling interval is too wide.
safe_fallbackIf the UMA oracle event feed is unavailable or the last event fetch is older than stale_top_seconds, reject all orders on affected markets with STALE_MARKET_DATA. Never approve on missing oracle status.
required_dependenciesUMA Optimistic Oracle on-chain event feed, Gamma API market metadata, PortfolioGuard per-market position ledger, KillSwitch active flag

19. Failure-Injection Recipes

ScenarioHow to injectExpected behaviourRecovery
DISPUTE_ACTIVESet mock oracle state disputeActive=true for a target marketAll evaluations on that market return HARD_REJECT(ORACLE_DISPUTE_ACTIVE)Returns to APPROVE when disputeActive=false in oracle state.
STALE_ORACLE_FEEDFreeze oracle state cache for 90s (TTL=30s)HARD_REJECT(STALE_MARKET_DATA) on every evaluationReturns to normal within one evaluation after fresh oracle fetch.
LOW_PROPOSER_BONDSet mock proposerBondPUsd=500 (below 750 floor)HARD_REJECT(ORACLE_PROPOSER_BOND_BELOW_MIN)Returns to APPROVE once bond is at or above 750 pUSD.
PROPOSAL_WINDOW_LATESet proposalFraction=0.85 and downgrade_size_by_confidence=trueRESHAPE_REQUIRED with cap significantly below reduce_at_proposal_pct baselineCap returns to baseline once proposal resolves.
KILL_SWITCH_ONSet internal.killswitch.status.active=trueHARD_REJECT(KILL_SWITCH_ACTIVE) on every intent without oracle fetchReturns to normal pipeline on manual KillSwitch reset.

20. State & Persistence

Maintains a short-lived in-memory cache of oracle state per market_id to avoid redundant on-chain calls within the same evaluation window.

State stores

NameKindKeyValue shapeTTLDurability
oracle_state_cachein-memorymarket_id{ proposalActive: bool, disputeActive: bool, proposalStartMs: int, challengeWindowMs: int, proposerBondPUsd: float }30sbest-effort

Cold-start recovery

On cold start, the cache is empty. The first evaluation for each market triggers a fresh on-chain fetch.

On restart

Oracle state is re-fetched on first evaluation; no durable state is loaded.

21. Concurrency & Idempotency

AspectSpecification
Execution modelsingle-threaded event loop
Max in-flight100
Idempotency keyintent_id
Replay-safeTrue
Deduplicationby intent_id within a 24h window
Ordering guaranteesFIFO per market_id
Per-call timeout (ms)250
Backpressure strategydrop newest
Locking / mutual exclusionper-market_id mutex

22. Dependencies

Depends on (must run first)

BotWhyContract
risk.kill_switchGlobal brake — checked first before any oracle fetch.RiskVote.HARD_REJECT(KILL_SWITCH_ACTIVE) short-circuits.
risk.portfolio_guardPer-market position limit is needed to compute the proposal-window size cap.cap = portfolio_guard.per_market_limit * reduce_at_proposal_pct.

Emits to (downstream consumers)

BotWhyContract
exec.smart_routerApproved or reshaped RiskVote passes to SmartRouter.HARD_REJECT on ORACLE_DISPUTE_ACTIVE causes SmartRouter to discard the intent.

Used by (auto-aggregated)

3.11

External services

ServiceEndpointSLA assumedOn failure
UMA Optimistic Oracle (on-chain)Polygon RPC / UMA oracle contractbest-effort / chain-dependentHARD_REJECT(STALE_MARKET_DATA) until oracle state is readable.
Gamma APIhttps://gamma-api.polymarket.com99.9% / 500ms p99HARD_REJECT(STALE_MARKET_DATA) if market metadata is unavailable.
CLOB API (read)https://clob.polymarket.com99.95% / 200ms p99Falls back to Gamma API for market metadata.

23. Security Surfaces

OracleRiskMonitor is read-only. It never signs orders or holds private keys.

Signing surface

This bot does NOT sign anything.

Abuse vectors considered

  • Feeding a stale or forged oracle state to bypass dispute detection
  • Manipulating proposalFraction to reduce the size cap during a proposal window

Mitigations

  • Oracle state has a 30s TTL; stale data triggers HARD_REJECT rather than pass-through
  • proposalFraction is computed from on-chain timestamps, not from any mutable local state

24. Polymarket V2 Compatibility

AspectValue
CLOB versionv2
Collateral assetpUSD
EIP-712 Exchange domain version2
Aware of builderCode fieldno
Aware of negative-risk marketsyes
Multi-chain readyno
SDK used@polymarket/clob-client-v2 ^2.x
Settlement contractCTFExchangeV2 on Polygon
NotesUMA proposer bond is 750 pUSD (replaces 750 USDC.e from v1). Dispute challenge window is 2 hours; escalated disputes go to DVM voting (24-48h debate + ~48h voting). NegRisk markets carry extra size reduction during proposal window due to potential definition shifts.

API surfaces declared

clob_publicgamma_apidata_api

Networks supported

polygon

25. Versioning & Migration

FieldValue
spec2.0.0
implementation2.1.3
schema2
released2026-04-28

Migration history

DateFromToReasonAction taken
2026-04-28v1 (USDC.e + HMAC builder)v2 (pUSD + builderCode field)Polymarket V2 cutoverMigrated SDK. Proposer bond check now validates 750 pUSD instead of 750 USDC.e. No structural change to oracle dispute logic; removed feeRateBps references.

26. Acceptance Tests

Unit Tests

TestSetupExpected result
Approve when no proposal and no disputeproposalActive=false, disputeActive=falseAPPROVE with no constraints
Reshape when proposal active and size exceeds capproposalActive=true, reduce_at_proposal_pct=50, per_market_limit=2000, size_usd=1200RESHAPE_REQUIRED with constraints.max_size_usd=1000
Reject when dispute active and block_disputed=truedisputeActive=true, block_disputed=trueREJECT with reason_code=ORACLE_DISPUTE_ACTIVE
Allow when dispute active and block_disputed=falsedisputeActive=true, block_disputed=falseAPPROVE with warning annotation ORACLE_DISPUTE_ACTIVE
Downgrade cap further when proposal fraction > 0.5proposalActive=true, proposal_fraction=0.8, reduce_at_proposal_pct=50, downgrade_size_by_confidence=trueRESHAPE_REQUIRED with cap reduced below standard 50% level
Reject when oracle feed is staleoracle_feed_age_s=200, stale_top_seconds=60REJECT with reason_code=STALE_MARKET_DATA
Neg-risk market applies additional 20% reductionproposalActive=true, neg_risk=true, reduce_at_proposal_pct=50, per_market_limit=2000RESHAPE_REQUIRED with constraints.max_size_usd=800 (50% × 0.8)

Integration Tests

TestExpected result
Live UMA oracle event triggers block on in-flight OrderIntentREJECT(ORACLE_DISPUTE_ACTIVE) emitted within one polling cycle after dispute filed on-chain
Position size from PortfolioGuard correctly caps reshape size end-to-endReshape constraint is consistent with PortfolioGuard ledger values
Oracle feed outage causes reject-safe fallback across all affected marketsAll orders on UMA-resolved markets return REJECT(STALE_MARKET_DATA) when feed is down

Property Tests

PropertyRequired behaviour
Missing oracle feed data never results in APPROVEAlways true — null or stale oracle status produces REJECT(STALE_MARKET_DATA)
Reshape size is always ≤ requested order sizeAlways true — downgrade adjustments only reduce the cap, never increase it
block_disputed=true always results in REJECT when disputeActive=trueAlways true regardless of order size or market state

27. Operational Runbook

OracleRiskMonitor incidents are driven by active UMA disputes or stale oracle feed. Disputes are expected events; on-call must validate the dispute is legitimate before considering any override.

On-call actions

AlertFirst stepDiagnosisMitigationEscalate to
OracleRiskMonitorDisputeActiveIdentify which market_id is in dispute from the Grafana panel.Check UMA oracle on-chain for dispute details. Verify the dispute was filed legitimately (not a griefing attempt with insufficient bond).If legitimate, the guard is working correctly — do not override. If suspicious, escalate to Risk pod lead.Risk pod lead immediately for any P1 dispute event.
OracleRiskMonitorDisputeOverdueCheck dispute age on the Grafana panel. Escalate immediately if > 48h.DVM vote may be stalled. Check UMA DVM governance interface for vote status.Maintain HARD_REJECT on affected market until DVM resolves. Do not reduce block_disputed.Incident commander + Risk pod lead within 15 minutes of alert.
OracleRiskMonitorStaleFeedCheck Polygon RPC connectivity and oracle contract read latency.If RPC is degraded, oracle state fetch is timing out and falling back to reject-safe.Switch to backup RPC endpoint. The guard's reject-safe default protects positions.Infra on-call if RPC is down > 5 minutes.
OracleRiskMonitorHighRejectRateCheck reason_code breakdown. If dominated by ORACLE_DISPUTE_ACTIVE, normal guard behaviour.If STALE_MARKET_DATA is dominant, follow stale-feed runbook.Pause affected strategies if the rejection is blocking all orders unnecessarily.Risk pod lead after 15 minutes of sustained high reject rate.

Manual overrides

  • polytraders bot pause risk.oracle_risk_monitor — Stops emitting RiskVotes. Use only during a known feed outage with explicit Risk pod lead sign-off.
  • polytraders bot flush-cache risk.oracle_risk_monitor --market <market_id> — Evicts the oracle state cache for a specific market, forcing a fresh on-chain fetch.

Healthcheck

GET /health → 200 if on-chain oracle state fetch latency < 500ms and no market has been in dispute for > max_dispute_window_h.

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

GateHow measuredThreshold
Unit tests pass including all acceptance_tests.unit casesCI test run100% pass
Integration test: active dispute → HARD_REJECT verified end-to-endIntegration test suite with mock oraclePass

Promote to Limited live

GateHow measuredThreshold
Oracle feed latency p99 < 250ms over 48hpolytraders_risk_oracleriskmonitor_oracle_fetch_latency_ms histogramp99 < 250ms
No false-positive HARD_REJECT during normal (no-dispute) operationShadow vs live comparison0 false positives

Promote to General live

GateHow measuredThreshold
Successfully blocked at least one synthetic dispute injection in stagingFailure injection test logPass
Proposal-window reshape correctly reduces size in E2E flowE2E test + fill log audit100% compliance

29. Developer Checklist

Ready-to-ship score: 27/27 sections complete · 100%

RequirementStatus
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