Documentation

Everything you need to integrate SettleRisk into your trading system.

Python SDK

Recommended

The Python SDK is the easiest way to use SettleRisk. It handles HMAC-SHA256 signing, automatic retries on rate limits and server errors, and idempotency key generation — so you can focus on your trading logic instead of auth plumbing.

Step 1: Install the SDK

One command, Python 3.10+:

$ pip install settlerisk

View on PyPI · Installs httpx as the only dependency.

Step 2: Get your API credentials

Sign up and go to your dashboard to create an API key. You'll get a key_id and secret. Keep the secret safe — it's shown only once.

Step 3: Get your first risk score

Three lines of code. The SDK signs every request automatically.

from settlerisk import SettleRiskClient

client = SettleRiskClient(
    key_id="vx_yourkey_123",
    secret="your-base64-secret",
)

# Get risk score for any market
score = client.get_risk_score("polymarket", "0xabc123")

print(f"Risk Score: {score['aggregate_risk_score']}/100")
print(f"Tier: {score['risk_tier']}")
print(f"P(Dispute): {score['p_dispute']:.1%}")
print(f"Drivers: {len(score['drivers'])}")
for d in score['drivers']:
    print(f"  - {d['driver_type']}: {d['points_contribution']} pts")

Step 4: Explore more endpoints

The client has methods for all 14 API endpoints:

# Settlement delay estimate
delay = client.get_expected_delay("polymarket", "0xabc123")
print(f"Median delay: {delay['delay_distribution']['p50_hours']}h")
print(f"P90 delay: {delay['delay_distribution']['p90_hours']}h")

# Evaluate custom rules (no existing market needed)
result = client.evaluate_rules({
    "platform": "polymarket",
    "rules_text": "Resolves YES if BTC reaches $100,000 by Dec 31.",
    "resolution_sources": ["https://coingecko.com"],
})
print(f"Risk: {result['aggregate_risk_score']} ({result['risk_tier']})")

# Dispute-adjusted pricing
pricing = client.price({
    "platform": "polymarket",
    "platform_market_id": "0xabc123",
    "mid_price": 0.65,
    "position_side": "YES",
    "position_notional_usd": 10000,
    "annual_capital_cost_apr": 0.12,
})
print(f"Fair price:  {pricing['adjusted_fair_price']:.4f}")
print(f"Risk premium: {pricing['risk_premium']:.4f}")
print(f"Fair spread:  {pricing['fair_spread_bps']} bps")

# Batch — score up to 1,000 markets at once
batch = client.batch_risk_scores([
    {"platform": "polymarket", "platform_market_id": "0xabc"},
    {"platform": "kalshi", "platform_market_id": "KXBTC-26FEB12"},
])

What the SDK handles for you

  • HMAC-SHA256 signing — every request is signed with the correct canonical format, timestamp, and nonce
  • Automatic retries — 429 rate limits and 5xx errors retry with exponential backoff and fresh signatures
  • Idempotency keys — auto-generated for all POST requests, preserved across retries
  • Typed exceptionsRateLimitError, AuthenticationError, ValidationError, etc.
  • Context manager — use with SettleRiskClient(...) as client: for automatic cleanup

Error handling

from settlerisk import (
    SettleRiskClient,
    RateLimitError,
    NotFoundError,
    AuthenticationError,
)

client = SettleRiskClient(key_id="...", secret="...")

try:
    score = client.get_risk_score("polymarket", "0xabc")
except NotFoundError:
    print("Market not in SettleRisk database yet")
except RateLimitError as e:
    print(f"Rate limited. Retry after: {e.retry_after}s")
except AuthenticationError:
    print("Check your key_id and secret")

All SDK methods

MethodDescription
get_risk_score(platform, market_id)Risk score + drivers + delay
get_expected_delay(platform, market_id)Settlement delay distribution
evaluate_rules(request)Score custom rules text (LLM-powered)
batch_risk_scores(markets)Score up to 1,000 markets
batch_expected_delays(markets)Delays for up to 1,000 markets
price(request)Dispute-adjusted pricing
batch_price(items)Price up to 1,000 markets
create_webhook(url, events)Register webhook endpoint
list_webhooks()List your webhook endpoints
delete_webhook(id)Remove a webhook
rotate_webhook_secret(id)Rotate webhook signing secret
list_webhook_deliveries()View delivery attempts
replay_webhook_delivery(id)Replay a past delivery
status()API health check

TypeScript SDK

New

The TypeScript SDK is a 1:1 port of the Python SDK for Node.js and TypeScript projects. Zero runtime dependencies, native fetch, ESM + CJS dual output.

Step 1: Install the SDK

One command, Node 18+:

$ npm install settlerisk

View on npm · Zero runtime dependencies. Uses native fetch and node:crypto.

Step 2: Get your API credentials

Sign up and go to your dashboard to create an API key. You'll get a keyId and secret. Keep the secret safe — it's shown only once.

Step 3: Get your first risk score

Three lines of code. The SDK signs every request automatically.

import { SettleRiskClient } from "settlerisk";

const client = new SettleRiskClient({
  keyId: "vx_yourkey_123",
  secret: "your-base64-secret",
});

// Get risk score for any market
const score = await client.getRiskScore("polymarket", "0xabc123");

console.log(`Risk Score: ${score.aggregate_risk_score}/100`);
console.log(`Tier: ${score.risk_tier}`);
console.log(`P(Dispute): ${(score.p_dispute * 100).toFixed(1)}%`);
console.log(`Drivers: ${score.drivers.length}`);
for (const d of score.drivers) {
  console.log(`  - ${d.driver_type}: ${d.points_contribution} pts`);
}

Step 4: Explore more endpoints

The client has async methods for all 14 API endpoints:

// Settlement delay estimate
const delay = await client.getExpectedDelay("polymarket", "0xabc123");
console.log(`Median delay: ${delay.delay_distribution.p50_hours}h`);
console.log(`P90 delay: ${delay.delay_distribution.p90_hours}h`);

// Evaluate custom rules (no existing market needed)
const result = await client.evaluateRules({
  platform: "polymarket",
  rules_text: "Resolves YES if BTC reaches $100,000 by Dec 31.",
  resolution_sources: ["https://coingecko.com"],
});
console.log(`Risk: ${result.aggregate_risk_score} (${result.risk_tier})`);

// Dispute-adjusted pricing
const pricing = await client.price({
  platform: "polymarket",
  platform_market_id: "0xabc123",
  mid_price: 0.65,
  position_side: "YES",
  position_notional_usd: 10000,
  annual_capital_cost_apr: 0.12,
});
console.log(`Fair price:  ${pricing.adjusted_fair_price.toFixed(4)}`);
console.log(`Risk premium: ${pricing.risk_premium.toFixed(4)}`);
console.log(`Fair spread:  ${pricing.fair_spread_bps} bps`);

// Batch — score up to 1,000 markets at once
const batch = await client.batchRiskScores([
  { platform: "polymarket", platform_market_id: "0xabc" },
  { platform: "kalshi", platform_market_id: "KXBTC-26FEB12" },
]);

What the SDK handles for you

  • HMAC-SHA256 signing — every request is signed with the correct canonical format, timestamp, and nonce
  • Automatic retries — 429 rate limits and 5xx errors retry with exponential backoff and fresh signatures
  • Idempotency keys — auto-generated for all POST requests, preserved across retries
  • Typed errorsRateLimitError, AuthenticationError, ValidationError, etc.
  • Zero dependencies — uses native fetch and node:crypto, nothing to install

Error handling

import {
  SettleRiskClient,
  RateLimitError,
  NotFoundError,
  AuthenticationError,
} from "settlerisk";

const client = new SettleRiskClient({ keyId: "...", secret: "..." });

try {
  const score = await client.getRiskScore("polymarket", "0xabc");
} catch (err) {
  if (err instanceof NotFoundError) {
    console.log("Market not in SettleRisk database yet");
  } else if (err instanceof RateLimitError) {
    console.log(`Rate limited. Retry after: ${err.retryAfter}s`);
  } else if (err instanceof AuthenticationError) {
    console.log("Check your keyId and secret");
  }
}

All SDK methods

MethodDescription
getRiskScore(platform, marketId)Risk score + drivers + delay
getExpectedDelay(platform, marketId)Settlement delay distribution
evaluateRules(request)Score custom rules text (LLM-powered)
batchRiskScores(markets)Score up to 1,000 markets
batchExpectedDelays(markets)Delays for up to 1,000 markets
price(request)Dispute-adjusted pricing
batchPrice(items)Price up to 1,000 markets
createWebhook(url, events)Register webhook endpoint
listWebhooks()List your webhook endpoints
deleteWebhook(id)Remove a webhook
rotateWebhookSecret(id)Rotate webhook signing secret
listWebhookDeliveries()View delivery attempts
replayWebhookDelivery(id)Replay a past delivery
status()API health check

Quick Start (Manual Signing)

Using Python or TypeScript? Skip this section and use the Python SDK or TypeScript SDK instead — they handle all signing automatically. This section is for other languages or if you need to implement signing yourself.

1. Get your API key

Sign up at settlerisk.com/signup and create your first API key from the dashboard. You'll receive a key ID and secret.

2. Make your first request

All requests require HMAC-SHA256 signing. The canonical request format is 7 lines joined by \n:

METHOD\n
PATH\n
QUERY\n
KEY_ID\n
TIMESTAMP\n
NONCE\n
CONTENT_SHA256

Sign with HMAC-SHA256(secret, canonical_string) and include these headers:

  • X-Vellox-Key-Id
  • X-Vellox-Timestamp
  • X-Vellox-Nonce
  • X-Vellox-Content-SHA256
  • X-Vellox-Signature

3. Parse the response

Every risk score response includes the aggregate score, tier, dispute probability, up to 15 drivers with evidence spans, expected delay distribution, and version stamps.

API Endpoints

MethodPathDescription
GET/v1/markets/{platform}/{id}/risk-scoreGet risk score for a market
GET/v1/markets/{platform}/{id}/expected-delayGet expected settlement delay
POST/v1/evaluate-rulesOn-demand LLM rule evaluation
POST/v1/risk-scores:batchBatch risk scores (up to 1,000)
POST/v1/expected-delays:batchBatch expected delays
POST/v1/pricingSingle market pricing
POST/v1/pricing:batchBatch pricing (up to 1,000)
POST/v1/webhooksRegister webhook endpoint
GET/v1/webhooksList webhook endpoints
DELETE/v1/webhooks/{id}Delete webhook endpoint
POST/v1/webhooks/{id}/rotate-secretRotate webhook secret
GET/v1/webhook-deliveriesList delivery attempts
POST/v1/webhook-deliveries/{id}/replayReplay delivery
GET/v1/statusHealth check

Authentication

All API requests are authenticated via HMAC-SHA256 request signing. This provides request integrity verification and replay protection.

Timestamp skew tolerance: 300 seconds. Nonce TTL: 600 seconds. Nonces are checked in Redis (fast path) with Postgres fallback (durable).

POST endpoints additionally require an Idempotency-Key header. Reusing the same key with a different payload returns 409 IDEMPOTENCY_CONFLICT.

gRPC

The gRPC service runs on port 50051 and mirrors the REST API with full parity. Authentication is passed via gRPC metadata using the same header names. Fund tier and above required.

The StreamAlerts RPC provides server-sent streaming of score tier changes and rule updates in real time.

Webhooks

Register endpoints to receive real-time event notifications. Webhooks are signed with HMAC-SHA256 using the format: HMAC-SHA256(secret, timestamp + "\n" + body)

Delivery is at-least-once with exponential backoff. Consumers should deduplicate on event_id (replays create a new delivery_id but preserve the original event_id).

Error Codes

All errors follow a consistent format with error_code, message, and details fields. Key error codes include:

  • AUTH_INVALID_SIGNATURE — HMAC verification failed
  • AUTH_TIMESTAMP_SKEW — timestamp outside 300s window
  • AUTH_NONCE_REPLAY — nonce already used
  • IDEMPOTENCY_CONFLICT — same key, different payload (409)
  • PRICING_MISSING_PRICE_INPUT — neither mid_price nor p_event provided
  • PRICING_MUTUALLY_EXCLUSIVE_INPUT — both mid_price and p_event provided
  • RATE_LIMIT_EXCEEDED — plan RPM limit exceeded (429)
  • MARKET_NOT_FOUND — market not in our database
  • SCORE_STALE — score exceeds staleness SLA