Skip to main content

Documentation Index

Fetch the complete documentation index at: https://developer.alterscope.org/llms.txt

Use this file to discover all available pages before exploring further.

This walks a Python 3.10+ developer through install, init, one REST call with the agentic envelope, a real-time stream, a webhook receiver, and how the SDK behaves on errors. Expect about five minutes end-to-end.
The Python SDK is published as alterscope on PyPI at version 2.0.1. It is generated from services/risk-api/docs/openapi.yaml so the typed client and the API reference stay in lockstep.

1. Install

pip install alterscope==2.0.1
The async client uses httpx and ships behind an extras flag:
pip install "alterscope[async]==2.0.1"

2. Initialize the client

import os
from alterscope import AlterscopeClient

client = AlterscopeClient(
    api_key=os.environ["ALTERSCOPE_API_KEY"],
    # base_url defaults to https://dev.alterscope.org/api.
    # Override for prod: ALTERSCOPE_BASE_URL=https://api.alterscope.org
    base_url=os.environ.get("ALTERSCOPE_BASE_URL"),
)
Get a key from the Developer Portal → API Keys. Keys start with sk_live_…. The constructor raises ValueError if api_key is missing.

3. Your first call

The cheapest “is it working?” call is an oracle classification — it always returns a shape that includes the agentic envelope (freshness, confidence, quality verdict) so you can confirm the SDK is wired correctly in one call.
import os
from alterscope import (
    AlterscopeClient,
    extract_agentic_meta,
    freshness_status_of,
)

client = AlterscopeClient(api_key=os.environ["ALTERSCOPE_API_KEY"])

market_id = "0x3a85e619b69e7a0c4dd158d61eb41e95b6f25cf3aa3c0f1e5f6e7d8c9b0a1d2f"

oracle = client.oracles.classify(market_id)

# The agentic envelope lives at response.meta._agentic.
meta = extract_agentic_meta(oracle)
print("freshness:", freshness_status_of(oracle))
if meta:
    print("confidence:", meta.confidence)
    if meta.quality_gate:
        print("quality:", meta.quality_gate.verdict)
Expected first-call output (real shape — values vary per market and run):
freshness: fresh
confidence: 0.94
quality: pass
freshness_status_of() returns one of "realtime", "fresh", "stale", or "unknown". Treat stale as a soft-error in your agent loop — re-fetch before acting on the data.

Async client

import asyncio
from alterscope import AsyncAlterscopeClient, freshness_status_of

async def main() -> None:
    async with AsyncAlterscopeClient(api_key="sk_live_...") as client:
        oracle = await client.oracles.classify(market_id="0x…")
        print(freshness_status_of(oracle))

asyncio.run(main())
The async surface mirrors the sync one — same resources, same return types — but methods are coroutines.

4. Stream events

Risk events are pushed over a WebSocket. The Python SDK does not yet wrap WebSockets — use the websockets package directly.
# pip install websockets
import asyncio
import json
import os
import websockets

async def stream_oracle_failures() -> None:
    api_key = os.environ["ALTERSCOPE_API_KEY"]
    url = f"wss://dev.alterscope.org/ws?token={api_key}"

    async with websockets.connect(url) as ws:
        await ws.send(json.dumps({
            "type": "subscribe",
            "channel": "events",
            "event_types": ["oracle_failure", "exploit"],
        }))

        async for raw in ws:
            msg = json.loads(raw)
            if msg.get("type") == "market_event" and msg.get("event_type") == "oracle_failure":
                print(f"oracle failure on {msg['protocol']}: {msg['title']}")

asyncio.run(stream_oracle_failures())
Event types you can subscribe to: factor_update (channel factors), alert_triggered (alerts), position_update (positions), apy_update (apy), market_event (events — subtypes include oracle_failure, exploit, upgrade, governance, liquidity_crunch). Full protocol reference: WebSockets API.
A typed client.risk_events.subscribe(...) wrapper is on the SDK roadmap — track via the changelog.

5. Receive a webhook

Create the webhook subscription via the SDK, then mount a handler that parses the body:
# One-time: register the endpoint.
client.webhooks.create(
    url="https://your.app/alterscope-webhook",
    events=["alert.triggered", "health_factor.low"],
)
A minimal FastAPI receiver:
from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/alterscope-webhook")
async def receive(request: Request):
    event = await request.json()
    print(event["type"], event["data"])
    return {"ok": True}
Signature verification ships with the GA SDK release (Q2 2026). Until then, restrict the webhook URL to source IPs you control and rotate the secret if it leaks. Track via the changelog.

Errors and retries

The SDK retries 429 and connection-level failures up to max_retries times with exponential backoff (capped at 60s) and honors Retry-After on 429. Defaults: max_retries = 3, timeout = 30 seconds.
from alterscope import (
    AlterscopeClient,
    AuthenticationError,
    NotFoundError,
    RateLimitError,
)

client = AlterscopeClient(
    api_key=os.environ["ALTERSCOPE_API_KEY"],
    max_retries=5,
    timeout=60,
)

try:
    oracle = client.oracles.classify(market_id="0x…")
except AuthenticationError:
    raise          # don't retry bad keys
except NotFoundError:
    oracle = None  # unknown market is not fatal
except RateLimitError as exc:
    print("backed off:", exc.retry_after)
    raise
Other typed exceptions: ForbiddenError, ValidationError, ServerError, plus the base AlterscopeError.

Reference

Next steps

Pricing & quotas

Free, Pro, Pro+, and Enterprise tiers — what each gets you.

Changelog

What changed in the API and SDKs, week by week.

API Reference

Every operation with try-it-out.

Recipes

End-to-end flows: depeg detection, scoring, treasury automation.