openclawv1.0.0

Rekko Skill

Rekko-AI@Rekko-AI⭐ 2 stars· last commit 7mo ago· 0 open issues

Prediction market intelligence from Rekko AI — deep causal research, arbitrage detection, screening, real-time signals, and strategy for autonomous trading agents.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

7.3/10
Verified
Mar 30, 2026

// RATINGS

⭐GitHub Stars
⭐ 2 on GitHubGitHub ↗

New / niche

🟢ProSkills ScoreAI Verified
7.3/10
📍

Not yet listed on ClawHub or SkillsMP

// README

Rekko Skill

License: MIT

Prediction market intelligence skill for AI agents. Deep causal research, arbitrage detection, screening, and strategy signals for Kalshi, Polymarket, and Robinhood.

What is Rekko?

In the OpenClaw ecosystem, three skills work together for autonomous prediction market trading:

SkillRoleWhat it does
Rekko (this skill)The BrainDeep causal research, probability estimates, trading signals
PolyClawThe Hands (Polymarket)Executes trades on Polymarket via CTF minting + CLOB
Kalshi TraderThe Hands (Kalshi)Executes trades on Kalshi

Rekko provides the why behind market movements. Execution skills handle the how.

Install

npx skills add Rekko-AI/rekko-skill

Or copy SKILL.md directly into your agent's skill directory.

Authentication

Two options:

API key (simple)

Get a key at rekko.ai, then set:

export REKKO_API_KEY=rk_free_your_key_here

x402 autopay (for autonomous agents)

Fund an EVM wallet with USDC on Base mainnet, then use the included Python client:

from eth_account import Account
from rekko_tools import RekkoClient

signer = Account.from_key("0x<your-private-key>")
async with RekkoClient(signer=signer) as client:
    markets = await client.list_markets()
    signal = await client.get_strategy("Will the Fed cut rates?")

Or set X402_PRIVATE_KEY in your environment for auto-detection.

Python client

Install dependencies:

pip install -r requirements.txt

The rekko_tools.py module provides RekkoClient — an async HTTP client with x402 payment support:

from rekko_tools import RekkoClient

async with RekkoClient() as client:
    # Browse markets ($0.01/call)
    markets = await client.list_markets(source="kalshi", limit=30)

    # Screen for high-value candidates ($0.10/call)
    screened = await client.screen_markets(platform="kalshi", min_score=50)

    # Deep analysis with strategy signal ($2.00/call)
    signal = await client.get_strategy("Will Bitcoin hit 100K by June?")

    # Cross-platform arbitrage scan ($5.00/call)
    arbs = await client.get_arbitrage(min_spread=0.03)

Example workflow

1. list_markets(source="kalshi", limit=30)
2. screen_markets(platform="kalshi", min_volume_24h=50000, min_score=50)
3. get_strategy(market_query="Will the Fed cut rates?")
4. IF recommendation == "BUY_YES" AND confidence > 0.5:
     -> chain to Kalshi Trader or PolyClaw for execution
5. place_shadow_trade(ticker, side, size_usd)  # track in Rekko portfolio

See SKILL.md for all 6 workflow patterns, complete endpoint reference, and response interpretation guide.

Links

// HOW IT'S BUILT

// FILES

12 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md19 KB36df8fad09b9upstream ↗
    ---
    name: rekko
    description: Prediction market intelligence from Rekko AI — deep causal research, arbitrage detection, screening, real-time signals, and strategy for autonomous trading agents.
    ---
    
    # Rekko — Prediction Market Intelligence
    
    ## What is Rekko?
    
    Rekko AI provides deep causal research for prediction markets on Kalshi, Polymarket, and Robinhood. It is the intelligence layer ("the brain") that sits alongside execution skills:
    
    - **PolyClaw** — executes trades on Polymarket
    - **Kalshi Trader** — executes trades on Kalshi
    - **Rekko** (this skill) — provides the WHY behind market movements
    
    Rekko runs multi-stage research pipelines that analyze prediction market bets, produce probability estimates with confidence levels, and return actionable strategy signals with causal decomposition. You consume finished insights; Rekko handles all research internally.
    
    Payment is per-request via x402 (USDC on Base L2) or through an API key.
    
    ## Setup
    
    ### HTTP Client (recommended)
    
    ```
    Base URL: https://api.rekko.ai/v1
    ```
    
    Authentication options:
    1. **x402** — automatic USDC micropayment per request (recommended for autonomous agents)
    2. **API key** — `Authorization: Bearer <key>` header
    
    #### x402 Autopay Setup
    
    1. Fund an EVM wallet with USDC on **Base mainnet** (chain ID 8453)
    2. Install dependencies: `pip install httpx x402[fastapi] eth-account`
    3. Create a client:
    
    ```python
    from eth_account import Account
    from rekko_tools import RekkoClient
    
    signer = Account.from_key("0x<your-private-key>")
    async with RekkoClient(signer=signer) as client:
        markets = await client.list_markets()
    ```
    
    Or set `X402_PRIVATE_KEY` in your environment for auto-detection:
    
    ```python
    async with RekkoClient() as client:
        markets = await client.list_markets()
    ```
    
    Or use the x402 httpx transport directly:
    
    ```python
    from x402 import x402Client
    from x402.mechanisms.evm.exact.client import ExactEvmScheme
    from x402.http.clients.httpx import wrapHttpxWithPayment
    from x402.http.x402_http_client import x402HTTPClient
    from eth_account import Account
    
    signer = Account.from_key("0x<your-private-key>")
    scheme = ExactEvmScheme(signer)
    x402c = x402Client()
    x402c.register("eip155:8453", scheme)
    http = wrapHttpxWithPayment(x402HTTPClient(x402c), base_url="https://api.rekko.ai")
    
    resp = await http.get("/v1/markets")  # 402 -> sign -> retry handled automatically
    ```
    
    **Network**: `eip155:8453` (Base mainnet). Payment is in USDC (6 decimals).
    
    ### Local MCP (for Claude Code, Cursor, OpenClaw)
    
    Add to your MCP client configuration:
    
    ```json
    {
      "mcpServers": {
        "rekko": {
          "command": "uv",
          "args": ["run", "--directory", "/path/to/rekko-ai", "python", "-m", "rekko_server.mcp"],
          "env": {
            "ANTHROPIC_API_KEY": "sk-ant-...",
            "GOOGLE_API_KEY": "AIza..."
          }
        }
      }
    }
    ```
    
    MCP local mode includes additional tools not available via the HTTP API: `search_markets`, `place_shadow_trade`, `get_portfolio`, `check_resolutions`, `run_scraper`, `get_calibration`.
    
    ## Pricing
    
    Check `/v1/pricing` for current rates. Tier pricing (x402 USDC on Base):
    
    | Tier | Price | Endpoints |
    |---|---|---|
    | Free | $0.00 | `/v1/calibration`, `/v1/pricing`, `/v1/health` |
    | Listing | $0.01 | `/v1/markets`, `/v1/markets/{platform}/{market_id}`, `/v1/markets/{platform}/{market_id}/history`, `/v1/events`, `/v1/events/trending`, `/v1/events/search`, `/v1/events/{slug}`, `/v1/events/{slug}/markets`, `/v1/stream`, `/v1/sentiment`, `/v1/performance`, `/v1/performance/history` |
    | Insight | $0.10 | `/v1/analyses`, `/v1/markets/{platform}/{market_id}/analysis`, `/v1/markets/{platform}/{market_id}/analyze`, `/v1/screen`, `/v1/markets/{platform}/{market_id}/resolution`, `/v1/events/{slug}/analyze`, `/v1/events/{slug}/analysis`, `/v1/events/{slug}/probability-map` |
    | Strategy | $2.00 | `/v1/signals`, `/v1/signals/portfolio`, `/v1/markets/{platform}/{market_id}/execution`, `/v1/trades/report`, `/v1/markets/{platform}/{market_id}/consensus`, `/v1/what-if` |
    | Deep | $5.00 | `/v1/arbitrage`, `/v1/arbitrage/live`, `/v1/correlation`, `/v1/events/{slug}/correlation`, `/v1/webhooks` |
    
    ## Endpoints
    
    ### Free (no auth required)
    
    | Endpoint | Method | Description |
    |---|---|---|
    | `/v1/health` | GET | Health check with data freshness metrics |
    | `/v1/pricing` | GET | Current tier pricing for all endpoints |
    | `/v1/calibration` | GET | Signal accuracy and calibration metrics (Brier score, hit rates) |
    
    ### Market Intelligence (Listing tier)
    
    | Endpoint | Method | Description | Key Parameters |
    |---|---|---|---|
    | `/v1/markets` | GET | Browse current prediction markets | `source` ("kalshi"/"polymarket"/"robinhood"/""), `limit` (1-100) |
    | `/v1/markets/{platform}/{market_id}` | GET | Single market detail | `expand` (e.g. "analysis") |
    | `/v1/markets/{platform}/{market_id}/history` | GET | Price history | `period` ("48h"/"7d"/"30d"), `max_points` |
    
    ### Events (Listing tier)
    
    Events group related individual markets (e.g., "Who will leave the Trump administration?" groups 32 individual outcome markets). Use events to browse thematically and discover markets you wouldn't find by keyword alone.
    
    | Endpoint | Method | Description | Key Parameters |
    |---|---|---|---|
    | `/v1/events` | GET | List prediction market events with aggregate stats | `source` ("kalshi"/"polymarket"/""), `category`, `featured` (bool), `limit` (1-100) |
    | `/v1/events/trending` | GET | Top events by trending score (volume + featured boost) | `limit` (1-50) |
    | `/v1/events/search` | GET | Hybrid full-text + semantic vector search across events | `q` (search query), `limit` (1-50) |
    | `/v1/events/{slug}` | GET | Single event detail with aggregate stats | `expand` (e.g. "markets") |
    | `/v1/events/{slug}/markets` | GET | All individual outcome markets within an event | — |
    
    ### Event Analysis (Insight / Deep tier)
    
    | Endpoint | Method | Description | Tier | Key Parameters |
    |---|---|---|---|---|
    | `/v1/events/{slug}/analyze` | POST | Trigger AI analysis of an entire event (all sub-markets) | Insight | — |
    | `/v1/events/{slug}/analysis` | GET | Get latest event analysis | Insight | `expand` (e.g. "scenarios,causal") |
    | `/v1/events/{slug}/probability-map` | GET | Probability estimates for all sub-markets within an event | Insight | — |
    | `/v1/events/{slug}/correlation` | GET | Cross-market correlation analysis within an event | Deep | — |
    
    ### Screening & Discovery (Insight tier)
    
    | Endpoint | Method | Description | Key Parameters |
    |---|---|---|---|
    | `/v1/analyses` | GET | List recent analyses | `limit` (1-50) |
    | `/v1/markets/{platform}/{market_id}/analysis` | GET | Latest analysis for a market | `expand` (e.g. "scenarios,causal") |
    | `/v1/markets/{platform}/{market_id}/analyze` | POST | Trigger async analysis (returns analysis_id) | — |
    | `/v1/markets/{platform}/{market_id}/analyze/{analysis_id}/status` | GET | Poll analysis status | — |
    | `/v1/screen` | POST | Batch screen markets by score/volume | `market_ids[]`, `platform`, `min_volume_24h`, `min_score`, `limit` |
    | `/v1/markets/{platform}/{market_id}/resolution` | GET | Resolution intelligence (time urgency, mechanism, theta) | — |
    
    ### Strategy (Strategy tier)
    
    | Endpoint | Method | Description | Key Parameters |
    |---|---|---|---|
    | `/v1/signals` | POST | Generate AI strategy signal | `market_query`, `market_id`, `platform`, `force`, `?wait=true`, `?expand=causal` |
    | `/v1/signals/portfolio` | POST | Portfolio-aware signal with correlation analysis | `market_query`, `portfolio[]`, `bankroll_usd`, `max_position_pct` |
    | `/v1/markets/{platform}/{market_id}/execution` | GET | Execution guidance (spread, slippage, timing) | — |
    | `/v1/trades/report` | POST | Report a trade for consensus aggregation | `market_id`, `platform`, `side`, `size_usd`, `price` |
    | `/v1/markets/{platform}/{market_id}/consensus` | GET | Consensus probability from agent trades | `period` ("24h"/"7d"/"30d") |
    | `/v1/what-if` | POST | Scenario analysis — how a hypothetical would affect a market | `market_query`, `hypothesis`, `platform` |
    
    ### Deep Intelligence (Deep tier)
    
    | Endpoint | Method | Description | Key Parameters |
    |---|---|---|---|
    | `/v1/arbitrage` | GET | Cross-platform arb opportunities (cached) | `min_spread` (0.0-0.5) |
    | `/v1/arbitrage/live` | GET | Fresh arbitrage scan (10-30s) | `min_spread` |
    | `/v1/correlation` | POST | Cross-market correlation graph | `market_ids[]`, `platform`, `period` |
    | `/v1/webhooks` | POST | Register webhook for real-time events | `url`, `events[]`, `secret` |
    | `/v1/webhooks` | GET | List registered webhooks | — |
    | `/v1/webhooks/{webhook_id}` | DELETE | Remove a webhook | — |
    
    ### Streaming (Listing tier)
    
    | Endpoint | Method | Description | Key Parameters |
    |---|---|---|---|
    | `/v1/stream` | GET | SSE real-time event stream | `events` ("price_shift,whale_alert,analysis_complete") |
    
    ### Analytics (authenticated)
    
    | Endpoint | Method | Description | Key Parameters |
    |---|---|---|---|
    | `/v1/sentiment` | GET | Market sentiment snapshot (fear/greed, regime, top movers) | — |
    | `/v1/performance` | GET | Trading track record (win rate, P&L, ROI) | `mode` ("shadow"/"live") |
    | `/v1/performance/history` | GET | Daily P&L time series for equity curve | `mode` |
    
    ## Query Parameters
    
    Several endpoints support optional query parameters:
    
    - **`?expand=`** — comma-separated expansions to include additional data:
      - `causal` — include causal decomposition on signals and analyses
      - `scenarios` — include scenario analysis
      - `analysis` — embed latest analysis on market detail
      - `scoring` — include score component breakdown on arbitrage
      - `meta` — include metadata
      - `history` — include price history
    - **`?wait=true`** — on `POST /v1/signals`, blocks until the pipeline completes (30-90s) instead of returning 202
    - **`?force=true`** — on `POST /v1/signals`, bypass the 24h analysis cache
    
    ## Interpreting Responses
    
    ### Recommendation
    
    The `recommendation` field in signal responses uses these values:
    
    - **`BUY_YES`** — market underprices the YES outcome, buy YES contracts
    - **`BUY_NO`** — market overprices the YES outcome, buy NO contracts
    - **`NO_TRADE`** — no actionable edge detected
    
    ### Edge
    
    `edge = estimated_probability - market_price`
    
    - **Positive edge** means the market underprices YES (potential BUY_YES)
    - **Negative edge** means the market overprices YES (potential BUY_NO)
    - Magnitude indicates signal strength (e.g. +0.12 = 12 percentage points of estimated mispricing)
    
    ### Confidence
    
    `confidence` ranges from 0.0 to 1.0:
    
    - **0.0 - 0.3** — low confidence, limited data or high uncertainty
    - **0.3 - 0.6** — moderate confidence, reasonable evidence base
    - **0.6 - 0.8** — high confidence, strong evidence
    - **0.8 - 1.0** — very high confidence, near-certain factors identified
    
    ### Causal Decomposition
    
    Strategy signals include a `causal` object (via `?expand=causal`). Each factor has:
    
    - **`claim`** — the factor statement
    - **`direction`** — `supports_yes`, `supports_no`, or `neutral`
    - **`weight`** — relative importance (top-level factors sum to ~1.0)
    - **`prior`** — base rate probability before evidence
    - **`posterior`** — updated probability after evidence
    - **`evidence`** — source references supporting this factor
    
    ### Arb Score
    
    Arbitrage opportunities include a `score` from 0 to 100:
    
    - **0-30** — minor spread, may not cover fees
    - **30-60** — moderate opportunity, worth monitoring
    - **60-80** — strong opportunity, actionable
    - **80-100** — exceptional spread with good liquidity
    
    The score is a weighted composite: 40% spread magnitude, 20% liquidity, 20% match confidence, 20% execution feasibility.
    
    ### Screen Result
    
    `screen` returns scored markets with:
    
    - **`score`** — composite of volume, movement, and signal quality
    - **`action`** — `"analyze"` (worth a strategy call), `"watch"` (monitor for movement), or `"skip"` (low value)
    
    Use this to filter before calling the more expensive `/v1/signals` endpoint.
    
    ### Execution Guidance
    
    `execution` returns order execution advice:
    
    - **`recommendation`** — `"LIMIT_ORDER"`, `"MARKET_ORDER"`, or `"WAIT"`
    - **`current_spread`** — current bid-ask spread
    - **`estimated_slippage_pct`** — expected slippage for a typical order size
    - **`rationale`** — context on liquidity patterns
    
    ### Resolution Intelligence
    
    `resolution` returns settlement timing context:
    
    - **`time_urgency`** — `"critical"` (< 24h), `"high"` (1-3d), `"medium"` (3-14d), `"low"` (> 14d)
    - **`resolution_mechanism`** — how the market resolves (e.g. "scheduled_data_release", "event_outcome")
    - **`theta_estimate`** — estimated daily time decay rate
    
    ### Consensus View
    
    `consensus` aggregates trades reported by agents:
    
    - **`consensus_probability`** — weighted average probability from reported trades
    - **`sample_size`** — number of trades aggregated
    - **`divergence_signal`** — `"crowd_agrees"`, `"crowd_disagrees"`, `"strong_divergence"`, or `"neutral"`
    
    ### Correlation Graph
    
    `correlation` returns pairwise relationships:
    
    - **`pairs`** — list of `{market_a, market_b, correlation, relationship}` entries
    - **`clusters`** — groups of correlated markets
    - **`concentration_warnings`** — alerts if your requested markets are highly correlated
    
    ### Calibration Metrics
    
    `calibration` returns signal accuracy data:
    
    - **`brier_score`** — lower is better (0.0 = perfect, 0.25 = random)
    - **`confidence_buckets`** — hit rate grouped by confidence level
    - **`total_signals`** — number of signals in the measurement period
    
    ## Workflow Patterns
    
    ### Pattern A: Research then Execute
    
    An agent spots an interesting market, uses Rekko for analysis, then chains to an execution skill.
    
    ```
    1. GET /v1/markets?source=kalshi&limit=30
    2. POST /v1/signals { "market_query": "Will the Fed cut rates?", "platform": "kalshi" } ?wait=true&expand=causal
    3. IF recommendation == "BUY_YES" AND confidence > 0.5:
         -> chain to Kalshi Trader: buy YES at target_price with size_pct of bankroll
    ```
    
    ### Pattern B: Arbitrage Discovery then Execution
    
    ```
    1. GET /v1/arbitrage?min_spread=0.03
    2. FOR each opportunity with score > 60:
         a. Buy YES on the cheaper platform via the appropriate execution skill
         b. POST /v1/trades/report to track for consensus
    3. GET /v1/performance periodically to review track record
    ```
    
    ### Pattern C: Smart Screening
    
    Use batch screening to find markets worth analyzing, then run strategy only on high-score candidates:
    
    ```
    1. POST /v1/screen { "platform": "kalshi", "min_volume_24h": 50000, "min_score": 50, "limit": 50 }
    2. FOR each result WHERE action == "analyze":
         POST /v1/signals { "market_id": result.market_id, "platform": "kalshi" } ?wait=true
    3. IF recommendation != "NO_TRADE" AND confidence > 0.5:
         -> execute via Kalshi Trader or PolyClaw
    ```
    
    This saves 80-90% on strategy costs by filtering out low-value markets first.
    
    ### Pattern D: Portfolio-Aware Trading
    
    Use portfolio context to avoid concentration and size positions correctly:
    
    ```
    1. POST /v1/signals/portfolio {
         "market_query": "Will Bitcoin hit 100K by June?",
         "portfolio": [{"platform": "kalshi", "market_id": "KXBTC-100K", "side": "yes", "size_usd": 250, "entry_price": 0.40}],
         "bankroll_usd": 10000,
         "max_position_pct": 0.05
       }
    2. IF recommendation != "NO_TRADE":
         POST /v1/correlation { "market_ids": [new_market, ...existing_ids], "platform": "kalshi" }
         IF concentration_warnings is empty:
           -> execute trade
    ```
    
    ### Pattern E: Consensus-Enhanced Trading
    
    Report your trades and check whether the crowd agrees:
    
    ```
    1. POST /v1/signals { "market_query": "Will unemployment rise above 4.5?" } ?wait=true
    2. IF recommendation == "BUY_YES":
         -> execute trade
         POST /v1/trades/report { "market_id": "KXUNEMP-4.5", "platform": "kalshi", "side": "yes", "size_usd": 100, "price": 0.45 }
    3. LATER:
         GET /v1/markets/kalshi/KXUNEMP-4.5/consensus?period=7d
         IF divergence_signal == "crowd_agrees": log("Mispricing likely real")
         IF divergence_signal == "crowd_disagrees": log("Reconsider position")
    ```
    
    ### Pattern F: Real-Time Monitoring
    
    Use SSE streaming for live alerts, webhooks for fire-and-forget:
    
    ```
    # Option 1: SSE stream (agent stays connected)
    GET /v1/stream?events=whale_alert,price_shift
      ON whale_alert: POST /v1/signals { "market_query": event.title } ?wait=true
      ON price_shift > 5%: GET /v1/markets/{platform}/{market_id}/execution
    
    # Option 2: Webhooks (async, agent receives POSTs)
    POST /v1/webhooks { "url": "https://my-agent.com/hook", "events": ["whale_alert", "analysis_complete"] }
    ```
    
    ### Pattern G: Event-Level Analysis
    
    Browse events for thematic market groups, then drill into sub-market probabilities:
    
    ```
    1. GET /v1/events/trending?limit=10
    2. FOR each event with market_count > 5:
         GET /v1/events/{slug}?expand=markets
    3. POST /v1/events/{slug}/analyze   (trigger event-level AI analysis)
    4. GET /v1/events/{slug}/probability-map   (ranked sub-market probabilities)
    5. IF any sub-market has high edge:
         POST /v1/signals { "market_id": sub_market.id, "platform": event.platform } ?wait=true
         -> chain to execution skill
    ```
    
    ### Pattern H: What-If Scenario Analysis
    
    Test how hypothetical scenarios would shift a market's probability:
    
    ```
    1. POST /v1/what-if {
         "market_query": "Will the Fed cut rates in June?",
         "hypothesis": "CPI comes in at 4.2%, above consensus",
         "platform": "kalshi"
       }
    2. Response includes: base_probability, scenario_probability, delta, reasoning
    3. Use delta to gauge sensitivity — large swings signal fragile consensus
    ```
    
    ## x402 Payment Flow
    
    When x402 is enabled, the payment handshake works as follows:
    
    ```
    Agent                           Rekko Feed API
      |                                    |
      |  GET /v1/markets                   |
      |  --------------------------------> |
      |                                    |
      |  402 Payment Required              |
      |  payment-required: <base64 JSON>   |
      |  <-------------------------------- |
      |                                    |
      |  [sign USDC EIP-712 payment]       |
      |                                    |
      |  GET /v1/markets                   |
      |  payment-signature: <signed proof> |
      |  --------------------------------> |
      |                                    |
      |  [facilitator verifies + settles]  |
      |                                    |
      |  200 OK                            |
      |  [market data]                     |
      |  <-------------------------------- |
    ```
    
    The `x402` Python package handles this loop automatically when you use `RekkoClient(signer=...)` or `wrapHttpxWithPayment()`. No manual header parsing needed.
    
    ## Risk Limits
    
    When using Rekko signals for trading, enforce these guardrails:
    
    - **Max 5% of bankroll per position** — even when `size_pct` is higher
    - **Shadow trade before live** — validate the strategy with paper trades first
    - **Never trade without edge** — if `recommendation` is `NO_TRADE`, respect it
    - **Check freshness** — strategy signals have an `expires_at` timestamp; do not trade stale signals
    - **Diversify with correlation** — use `/v1/correlation` to check for concentration risk before adding positions
    - **Check execution guidance** — call `/v1/markets/{platform}/{market_id}/execution` before placing large orders to avoid slippage
    - **Respect consensus divergence** — if `divergence_signal` is `"crowd_disagrees"`, reconsider your position
    - **Check calibration periodically** — use `/v1/calibration` to verify signal accuracy before trusting high-confidence calls
    
  • README.md3.1 KBea6c26c835f7upstream ↗
    # Rekko Skill
    
    [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
    
    Prediction market intelligence skill for AI agents. Deep causal research, arbitrage detection, screening, and strategy signals for **Kalshi**, **Polymarket**, and **Robinhood**.
    
    ## What is Rekko?
    
    In the OpenClaw ecosystem, three skills work together for autonomous prediction market trading:
    
    | Skill | Role | What it does |
    |-------|------|-------------|
    | **Rekko** (this skill) | The Brain | Deep causal research, probability estimates, trading signals |
    | **PolyClaw** | The Hands (Polymarket) | Executes trades on Polymarket via CTF minting + CLOB |
    | **Kalshi Trader** | The Hands (Kalshi) | Executes trades on Kalshi |
    
    Rekko provides the *why* behind market movements. Execution skills handle the *how*.
    
    ## Install
    
    ```bash
    npx skills add Rekko-AI/rekko-skill
    ```
    
    Or copy `SKILL.md` directly into your agent's skill directory.
    
    ## Authentication
    
    Two options:
    
    ### API key (simple)
    
    Get a key at [rekko.ai](https://rekko.ai/dashboard), then set:
    
    ```bash
    export REKKO_API_KEY=rk_free_your_key_here
    ```
    
    ### x402 autopay (for autonomous agents)
    
    Fund an EVM wallet with USDC on Base mainnet, then use the included Python client:
    
    ```python
    from eth_account import Account
    from rekko_tools import RekkoClient
    
    signer = Account.from_key("0x<your-private-key>")
    async with RekkoClient(signer=signer) as client:
        markets = await client.list_markets()
        signal = await client.get_strategy("Will the Fed cut rates?")
    ```
    
    Or set `X402_PRIVATE_KEY` in your environment for auto-detection.
    
    ## Python client
    
    Install dependencies:
    
    ```bash
    pip install -r requirements.txt
    ```
    
    The `rekko_tools.py` module provides `RekkoClient` — an async HTTP client with x402 payment support:
    
    ```python
    from rekko_tools import RekkoClient
    
    async with RekkoClient() as client:
        # Browse markets ($0.01/call)
        markets = await client.list_markets(source="kalshi", limit=30)
    
        # Screen for high-value candidates ($0.10/call)
        screened = await client.screen_markets(platform="kalshi", min_score=50)
    
        # Deep analysis with strategy signal ($2.00/call)
        signal = await client.get_strategy("Will Bitcoin hit 100K by June?")
    
        # Cross-platform arbitrage scan ($5.00/call)
        arbs = await client.get_arbitrage(min_spread=0.03)
    ```
    
    ## Example workflow
    
    ```
    1. list_markets(source="kalshi", limit=30)
    2. screen_markets(platform="kalshi", min_volume_24h=50000, min_score=50)
    3. get_strategy(market_query="Will the Fed cut rates?")
    4. IF recommendation == "BUY_YES" AND confidence > 0.5:
         -> chain to Kalshi Trader or PolyClaw for execution
    5. place_shadow_trade(ticker, side, size_usd)  # track in Rekko portfolio
    ```
    
    See `SKILL.md` for all 6 workflow patterns, complete endpoint reference, and response interpretation guide.
    
    ## Links
    
    - [rekko.ai/docs](https://rekko.ai/docs) — Full documentation
    - [OpenClaw integration guide](https://rekko.ai/docs/integrations/openclaw/overview) — Detailed setup
    - [API Reference](https://rekko.ai/docs/api-reference/introduction) — Direct API access
    - [Discord](https://discord.gg/qTPEk9aAZg) — Community
    
  • .github/workflows/context7-refresh.yml571 B5c31fa07b16cupstream ↗
    name: Refresh Context7 index
    
    on:
      push:
        branches: [main]
        paths:
          - "README.md"
          - "SKILL.md"
          - "rekko_tools.py"
          - "examples/**"
          - "context7.json"
    
    jobs:
      refresh:
        runs-on: ubuntu-latest
        steps:
          - name: Trigger Context7 re-index
            run: |
              curl -X POST "https://context7.com/api/v1/refresh" \
                -H "Authorization: Bearer ${{ secrets.CONTEXT7_API_KEY }}" \
                -H "Content-Type: application/json" \
                -d '{"libraryName": "/rekko-ai/rekko-skill"}'
            continue-on-error: true
    
  • .gitignore52 B47a7953dd87eupstream ↗
    __pycache__/
    *.py[cod]
    *$py.class
    .env
    .venv/
    venv/
    
  • context7.json101 B994c1a1483d2upstream ↗
    {
      "url": "https://context7.com/rekko-ai/rekko-skill",
      "public_key": "pk_MfRhTzRGAQOnu20cIktpW"
    }
    
  • examples/causal_decomposition.json2.4 KBe0327d1f892cupstream ↗
    {
      "overall_probability": 0.58,
      "overall_confidence": 0.72,
      "factors": [
        {
          "claim": "Kansas City's offense ranks top-5 in EPA/play this season",
          "direction": "supports_yes",
          "weight": 0.30,
          "confidence": 0.88,
          "prior": 0.50,
          "posterior": 0.72,
          "evidence": [
            "KC ranked #3 in offensive EPA/play through Week 18 (0.142)",
            "Mahomes averaging 8.4 YPA in playoffs, career high",
            "Kelce's target share increased to 31% in postseason"
          ]
        },
        {
          "claim": "Opponent defensive line generates pressure above league average",
          "direction": "supports_no",
          "weight": 0.25,
          "confidence": 0.75,
          "prior": 0.50,
          "posterior": 0.63,
          "evidence": [
            "Opponent pass rush win rate 48% (7th in NFL)",
            "KC offensive line allowed 2.3 sacks/game in playoffs",
            "Interior pressure specifically challenges Mahomes -- 71.2 passer rating when pressured up the middle"
          ]
        },
        {
          "claim": "Historical Super Bowl favorite covers at a reliable rate",
          "direction": "supports_yes",
          "weight": 0.15,
          "confidence": 0.65,
          "prior": 0.52,
          "posterior": 0.56,
          "evidence": [
            "Favorites have won 57% of Super Bowls outright since 2000",
            "3-point or smaller favorites win at 62% historically",
            "Regression concern: small sample size (26 games)"
          ]
        },
        {
          "claim": "Injury report favors Kansas City",
          "direction": "supports_yes",
          "weight": 0.15,
          "confidence": 0.80,
          "prior": 0.50,
          "posterior": 0.61,
          "evidence": [
            "KC has zero players on injury report as questionable or out",
            "Opponent missing starting CB2 (torn ACL Week 17)",
            "Injury edges are well-priced in by Super Bowl week -- limited alpha"
          ]
        },
        {
          "claim": "Coaching and game-planning edge",
          "direction": "supports_yes",
          "weight": 0.15,
          "confidence": 0.68,
          "prior": 0.55,
          "posterior": 0.62,
          "evidence": [
            "Andy Reid 2-week preparation record: 7-2 after bye/extra rest",
            "Reid's halftime adjustments ranked #1 by expected points added in 2nd half",
            "Opponent coaching staff in first Super Bowl -- experience gap is real but hard to quantify"
          ]
        }
      ],
      "method": "weighted_bayesian",
      "generated_at": "2026-02-05T18:00:00Z"
    }
    
  • examples/examples/causal_decomposition.json2.4 KBe0327d1f892cupstream ↗
    {
      "overall_probability": 0.58,
      "overall_confidence": 0.72,
      "factors": [
        {
          "claim": "Kansas City's offense ranks top-5 in EPA/play this season",
          "direction": "supports_yes",
          "weight": 0.30,
          "confidence": 0.88,
          "prior": 0.50,
          "posterior": 0.72,
          "evidence": [
            "KC ranked #3 in offensive EPA/play through Week 18 (0.142)",
            "Mahomes averaging 8.4 YPA in playoffs, career high",
            "Kelce's target share increased to 31% in postseason"
          ]
        },
        {
          "claim": "Opponent defensive line generates pressure above league average",
          "direction": "supports_no",
          "weight": 0.25,
          "confidence": 0.75,
          "prior": 0.50,
          "posterior": 0.63,
          "evidence": [
            "Opponent pass rush win rate 48% (7th in NFL)",
            "KC offensive line allowed 2.3 sacks/game in playoffs",
            "Interior pressure specifically challenges Mahomes -- 71.2 passer rating when pressured up the middle"
          ]
        },
        {
          "claim": "Historical Super Bowl favorite covers at a reliable rate",
          "direction": "supports_yes",
          "weight": 0.15,
          "confidence": 0.65,
          "prior": 0.52,
          "posterior": 0.56,
          "evidence": [
            "Favorites have won 57% of Super Bowls outright since 2000",
            "3-point or smaller favorites win at 62% historically",
            "Regression concern: small sample size (26 games)"
          ]
        },
        {
          "claim": "Injury report favors Kansas City",
          "direction": "supports_yes",
          "weight": 0.15,
          "confidence": 0.80,
          "prior": 0.50,
          "posterior": 0.61,
          "evidence": [
            "KC has zero players on injury report as questionable or out",
            "Opponent missing starting CB2 (torn ACL Week 17)",
            "Injury edges are well-priced in by Super Bowl week -- limited alpha"
          ]
        },
        {
          "claim": "Coaching and game-planning edge",
          "direction": "supports_yes",
          "weight": 0.15,
          "confidence": 0.68,
          "prior": 0.55,
          "posterior": 0.62,
          "evidence": [
            "Andy Reid 2-week preparation record: 7-2 after bye/extra rest",
            "Reid's halftime adjustments ranked #1 by expected points added in 2nd half",
            "Opponent coaching staff in first Super Bowl -- experience gap is real but hard to quantify"
          ]
        }
      ],
      "method": "weighted_bayesian",
      "generated_at": "2026-02-05T18:00:00Z"
    }
    
  • examples/examples/strategy_signal.json2.2 KB531b5e18283eupstream ↗
    {
      "platform": "kalshi",
      "market_id": "KXFED-26MAR19-T4.75",
      "title": "Will the Fed cut rates at the March 2026 meeting?",
      "recommendation": "BUY_YES",
      "target_price": 0.35,
      "edge": 0.12,
      "confidence": 0.78,
      "risk_rating": "medium",
      "size_pct": 0.03,
      "time_horizon": "days",
      "hedge": "Buy NO on KXCPI-26APR-T3.5 at 0.85 as inflation hedge",
      "causal": {
        "overall_probability": 0.47,
        "overall_confidence": 0.78,
        "factors": [
          {
            "claim": "Inflation data supports a cut",
            "direction": "supports_yes",
            "weight": 0.35,
            "confidence": 0.82,
            "prior": 0.30,
            "posterior": 0.55,
            "evidence": [
              "Feb CPI came in at 2.4%, below 2.6% consensus",
              "Core PCE trending down for 3 consecutive months",
              "Shelter inflation decelerating: OER fell to 5.1% from 5.4% YoY"
            ]
          },
          {
            "claim": "Labor market shows signs of softening",
            "direction": "supports_yes",
            "weight": 0.25,
            "confidence": 0.71,
            "prior": 0.25,
            "posterior": 0.42,
            "evidence": [
              "NFP missed at +142K vs +185K expected",
              "Unemployment ticked up to 4.1%",
              "JOLTS openings at lowest since 2021"
            ]
          },
          {
            "claim": "Fed communication signals patience, not urgency",
            "direction": "supports_no",
            "weight": 0.25,
            "confidence": 0.85,
            "prior": 0.60,
            "posterior": 0.68,
            "evidence": [
              "Powell's Feb 28 testimony: 'no need to rush'",
              "Waller speech emphasized data-dependency",
              "March dot plot projections still show 2 cuts in 2026"
            ]
          },
          {
            "claim": "Financial conditions are already accommodative",
            "direction": "supports_no",
            "weight": 0.15,
            "confidence": 0.65,
            "prior": 0.50,
            "posterior": 0.58,
            "evidence": [
              "10Y yield at 3.95%, down 40bps since January",
              "Credit spreads remain tight"
            ]
          }
        ],
        "method": "weighted_bayesian",
        "generated_at": "2026-03-15T14:30:00Z"
      },
      "generated_at": "2026-03-15T14:30:00Z",
      "expires_at": "2026-03-16T14:30:00Z"
    }
    
  • examples/strategy_signal.json2.2 KB531b5e18283eupstream ↗
    {
      "platform": "kalshi",
      "market_id": "KXFED-26MAR19-T4.75",
      "title": "Will the Fed cut rates at the March 2026 meeting?",
      "recommendation": "BUY_YES",
      "target_price": 0.35,
      "edge": 0.12,
      "confidence": 0.78,
      "risk_rating": "medium",
      "size_pct": 0.03,
      "time_horizon": "days",
      "hedge": "Buy NO on KXCPI-26APR-T3.5 at 0.85 as inflation hedge",
      "causal": {
        "overall_probability": 0.47,
        "overall_confidence": 0.78,
        "factors": [
          {
            "claim": "Inflation data supports a cut",
            "direction": "supports_yes",
            "weight": 0.35,
            "confidence": 0.82,
            "prior": 0.30,
            "posterior": 0.55,
            "evidence": [
              "Feb CPI came in at 2.4%, below 2.6% consensus",
              "Core PCE trending down for 3 consecutive months",
              "Shelter inflation decelerating: OER fell to 5.1% from 5.4% YoY"
            ]
          },
          {
            "claim": "Labor market shows signs of softening",
            "direction": "supports_yes",
            "weight": 0.25,
            "confidence": 0.71,
            "prior": 0.25,
            "posterior": 0.42,
            "evidence": [
              "NFP missed at +142K vs +185K expected",
              "Unemployment ticked up to 4.1%",
              "JOLTS openings at lowest since 2021"
            ]
          },
          {
            "claim": "Fed communication signals patience, not urgency",
            "direction": "supports_no",
            "weight": 0.25,
            "confidence": 0.85,
            "prior": 0.60,
            "posterior": 0.68,
            "evidence": [
              "Powell's Feb 28 testimony: 'no need to rush'",
              "Waller speech emphasized data-dependency",
              "March dot plot projections still show 2 cuts in 2026"
            ]
          },
          {
            "claim": "Financial conditions are already accommodative",
            "direction": "supports_no",
            "weight": 0.15,
            "confidence": 0.65,
            "prior": 0.50,
            "posterior": 0.58,
            "evidence": [
              "10Y yield at 3.95%, down 40bps since January",
              "Credit spreads remain tight"
            ]
          }
        ],
        "method": "weighted_bayesian",
        "generated_at": "2026-03-15T14:30:00Z"
      },
      "generated_at": "2026-03-15T14:30:00Z",
      "expires_at": "2026-03-16T14:30:00Z"
    }
    
  • LICENSE1.0 KBf08c45229969upstream ↗
    MIT License
    
    Copyright (c) 2025-2026 Rekko AI
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
    
  • rekko_tools.py23 KB808f0652d3d9upstream ↗
    """Rekko tools -- x402-aware httpx client for the Feed API.
    
    This module provides an async client for the Rekko AI Feed API.
    Authentication is via x402 autopay — the client automatically handles
    402 → sign → retry with USDC on Base. No account or key management needed.
    
    Set ``X402_PRIVATE_KEY`` in the environment (hex EVM private key) and the
    client auto-detects it, or pass a ``signer`` to the constructor.
    """
    from __future__ import annotations
    
    import json
    import logging
    import os
    from typing import Any, AsyncIterator
    
    import httpx
    
    logger = logging.getLogger(__name__)
    
    REKKO_API_BASE = "https://api.rekko.ai"
    
    
    def _make_x402_client(
        signer: Any,
        network: str = "eip155:8453",
        **httpx_kwargs: Any,
    ) -> httpx.AsyncClient:
        """Create an httpx.AsyncClient that handles x402 payments automatically.
    
        Args:
            signer: An EVM signer — either an ``eth_account.LocalAccount`` or
                a ``ClientEvmSigner`` from the x402 package.
            network: CAIP-2 network ID. Default is Base mainnet (eip155:8453).
            **httpx_kwargs: Extra kwargs passed to ``httpx.AsyncClient``.
    
        Returns:
            An ``httpx.AsyncClient`` that intercepts 402 responses, signs the
            USDC payment, and retries automatically.
        """
        from x402 import x402Client
        from x402.http.clients.httpx import wrapHttpxWithPayment
        from x402.http.x402_http_client import x402HTTPClient
        from x402.mechanisms.evm.exact.client import ExactEvmScheme
    
        scheme = ExactEvmScheme(signer)
        client = x402Client()
        client.register(network, scheme)
        http_client = x402HTTPClient(client)
    
        return wrapHttpxWithPayment(http_client, **httpx_kwargs)
    
    
    class RekkoClient:
        """Async client for the Rekko AI Feed API with x402 payment support.
    
        Usage with x402 autopay (recommended):
    
            from eth_account import Account
            signer = Account.from_key("0x...")
            client = RekkoClient(signer=signer)
            markets = await client.list_markets()
            await client.close()
    
        Usage as async context manager:
    
            async with RekkoClient(signer=signer) as client:
                markets = await client.list_markets()
    
        Or set X402_PRIVATE_KEY in env for auto-detection:
    
            async with RekkoClient() as client:
                markets = await client.list_markets()
        """
    
        def __init__(
            self,
            api_key: str = "",
            base_url: str = "",
            signer: Any = None,
            network: str = "eip155:8453",
            timeout: float = 300.0,
        ) -> None:
            self.base_url = base_url or os.environ.get("REKKO_API_URL", REKKO_API_BASE)
            self.api_key = api_key or os.environ.get("REKKO_API_KEY", "")
    
            # Auto-detect x402 signer from env if no signer or API key provided
            if signer is None and not self.api_key:
                x402_key = os.environ.get("X402_PRIVATE_KEY", "")
                if x402_key:
                    from eth_account import Account
    
                    if not x402_key.startswith("0x"):
                        x402_key = f"0x{x402_key}"
                    signer = Account.from_key(x402_key)
    
            if signer is not None:
                # x402 autopay — httpx transport handles 402 retry loop
                self._client = _make_x402_client(
                    signer,
                    network=network,
                    base_url=self.base_url,
                    timeout=timeout,
                )
            else:
                headers: dict[str, str] = {}
                if self.api_key:
                    headers["Authorization"] = f"Bearer {self.api_key}"
                self._client = httpx.AsyncClient(
                    base_url=self.base_url,
                    headers=headers,
                    timeout=timeout,
                )
    
        # -----------------------------------------------------------------
        # Market intelligence
        # -----------------------------------------------------------------
    
        async def list_markets(
            self, source: str = "", limit: int = 30
        ) -> dict[str, Any]:
            """List current prediction markets.
    
            Args:
                source: Filter by platform: "kalshi", "polymarket", or "" for all.
                limit: Maximum number of markets to return (1-100).
            """
            params: dict[str, Any] = {"limit": limit}
            if source:
                params["source"] = source
            return await self._request("GET", "/v1/markets", params=params)
    
        async def get_market(
            self, platform: str, market_id: str, expand: str = ""
        ) -> dict[str, Any]:
            """Get details for a single market.
    
            Args:
                platform: "kalshi" or "polymarket".
                market_id: Platform-specific identifier (ticker or slug).
                expand: Comma-separated expansions (e.g. "analysis").
            """
            params: dict[str, str] = {}
            if expand:
                params["expand"] = expand
            return await self._request(
                "GET", f"/v1/markets/{platform}/{market_id}", params=params
            )
    
        async def get_market_history(
            self,
            platform: str,
            market_id: str,
            period: str = "7d",
            max_points: int = 48,
        ) -> dict[str, Any]:
            """Get price history for a market.
    
            Args:
                platform: "kalshi" or "polymarket".
                market_id: Platform-specific identifier (ticker or slug).
                period: Time window -- "48h", "7d", or "30d".
                max_points: Maximum number of data points to return.
            """
            params: dict[str, Any] = {"period": period, "max_points": max_points}
            return await self._request(
                "GET", f"/v1/markets/{platform}/{market_id}/history", params=params
            )
    
        async def get_resolution(
            self, platform: str, market_id: str
        ) -> dict[str, Any]:
            """Get resolution intelligence for a market."""
            return await self._request(
                "GET", f"/v1/markets/{platform}/{market_id}/resolution"
            )
    
        async def get_execution_guidance(
            self, platform: str, market_id: str
        ) -> dict[str, Any]:
            """Get execution guidance for a market (spread, slippage, timing)."""
            return await self._request(
                "GET", f"/v1/markets/{platform}/{market_id}/execution"
            )
    
        # -----------------------------------------------------------------
        # Events
        # -----------------------------------------------------------------
    
        async def list_events(
            self, source: str = "", category: str = "", featured: bool | None = None, limit: int = 20
        ) -> dict[str, Any]:
            """List prediction market events with aggregate stats.
    
            Args:
                source: Filter by platform: "kalshi", "polymarket", or "" for all.
                category: Filter by category (e.g. "politics", "crypto") or "" for all.
                featured: Only featured events (true) or all (None).
                limit: Maximum number of events to return (1-100).
            """
            params: dict[str, Any] = {"limit": limit}
            if source:
                params["source"] = source
            if category:
                params["category"] = category
            if featured is not None:
                params["featured"] = featured
            return await self._request("GET", "/v1/events", params=params)
    
        async def trending_events(self, limit: int = 20) -> dict[str, Any]:
            """Get top trending prediction market events.
    
            Args:
                limit: Maximum number of trending events to return (1-50).
            """
            return await self._request(
                "GET", "/v1/events/trending", params={"limit": limit}
            )
    
        async def search_events(self, query: str, limit: int = 20) -> dict[str, Any]:
            """Search prediction market events using hybrid full-text + semantic search.
    
            Args:
                query: Search query (supports semantic + keyword matching).
                limit: Maximum number of results to return (1-50).
            """
            return await self._request(
                "GET", "/v1/events/search", params={"q": query, "limit": limit}
            )
    
        async def get_event(
            self, slug: str, expand: str = ""
        ) -> dict[str, Any]:
            """Get detailed information about a single prediction market event.
    
            Args:
                slug: Event slug (e.g. 'kalshi:kxtrumpadminleave-26dec31').
                expand: Comma-separated expansions (e.g. "markets").
            """
            params: dict[str, str] = {}
            if expand:
                params["expand"] = expand
            return await self._request("GET", f"/v1/events/{slug}", params=params)
    
        async def get_event_markets(self, slug: str) -> dict[str, Any]:
            """List all individual outcome markets within an event.
    
            Args:
                slug: Event slug (e.g. 'kalshi:kxtrumpadminleave-26dec31').
            """
            return await self._request("GET", f"/v1/events/{slug}/markets")
    
        async def analyze_event(self, slug: str) -> dict[str, Any]:
            """Trigger an AI analysis of an entire event (all sub-markets).
    
            Returns an analysis_id for polling. The analysis covers the event
            holistically — ranking sub-markets, identifying surprises, and
            producing a probability map.
    
            Args:
                slug: Event slug (e.g. 'kalshi:kxtrumpadminleave-26dec31').
            """
            return await self._request("POST", f"/v1/events/{slug}/analyze")
    
        async def get_event_analysis(
            self, slug: str, expand: str = ""
        ) -> dict[str, Any]:
            """Get the latest AI analysis for an event.
    
            Args:
                slug: Event slug (e.g. 'kalshi:kxtrumpadminleave-26dec31').
                expand: Comma-separated expansions (e.g. "scenarios,causal").
            """
            params: dict[str, str] = {}
            if expand:
                params["expand"] = expand
            return await self._request(
                "GET", f"/v1/events/{slug}/analysis", params=params
            )
    
        async def get_event_probability_map(self, slug: str) -> dict[str, Any]:
            """Get probability estimates for all sub-markets within an event.
    
            Returns a map of market_id → probability with confidence intervals,
            useful for comparing outcomes within a single event.
    
            Args:
                slug: Event slug (e.g. 'kalshi:kxtrumpadminleave-26dec31').
            """
            return await self._request(
                "GET", f"/v1/events/{slug}/probability-map"
            )
    
        async def get_event_correlation(self, slug: str) -> dict[str, Any]:
            """Get cross-market correlation analysis within an event.
    
            Identifies which sub-markets within the event move together,
            concentration risks, and hedge opportunities.
    
            Args:
                slug: Event slug (e.g. 'kalshi:kxtrumpadminleave-26dec31').
            """
            return await self._request(
                "GET", f"/v1/events/{slug}/correlation"
            )
    
        # -----------------------------------------------------------------
        # Screening & discovery
        # -----------------------------------------------------------------
    
        async def screen_markets(
            self,
            market_ids: list[str] | None = None,
            platform: str = "",
            min_volume_24h: float = 0,
            min_score: float = 0,
            limit: int = 50,
        ) -> dict[str, Any]:
            """Batch screen markets by score, volume, or explicit IDs."""
            body: dict[str, Any] = {"limit": limit}
            if market_ids:
                body["market_ids"] = market_ids
            if platform:
                body["platform"] = platform
            if min_volume_24h > 0:
                body["min_volume_24h"] = min_volume_24h
            if min_score > 0:
                body["min_score"] = min_score
            return await self._request("POST", "/v1/screen", json=body)
    
        async def get_calibration(
            self,
            category: str = "",
            period: str = "all",
            mode: str = "shadow",
        ) -> dict[str, Any]:
            """Get signal accuracy and calibration metrics. No auth required."""
            params: dict[str, Any] = {"period": period, "mode": mode}
            if category:
                params["category"] = category
            return await self._request("GET", "/v1/calibration", params=params)
    
        # -----------------------------------------------------------------
        # Real-time signals
        # -----------------------------------------------------------------
    
        def stream_events(
            self, events: str = ""
        ) -> AsyncIterator[httpx.Response]:
            """Connect to the SSE real-time event stream."""
            params: dict[str, str] = {}
            if events:
                params["events"] = events
            return self._client.stream("GET", "/v1/stream", params=params)
    
        # -----------------------------------------------------------------
        # Webhooks
        # -----------------------------------------------------------------
    
        async def create_webhook(
            self, url: str, events: list[str], secret: str = ""
        ) -> dict[str, Any]:
            """Register a webhook for async event notifications."""
            body: dict[str, Any] = {"url": url, "events": events}
            if secret:
                body["secret"] = secret
            return await self._request("POST", "/v1/webhooks", json=body)
    
        async def list_webhooks(self) -> dict[str, Any]:
            """List all registered webhooks."""
            return await self._request("GET", "/v1/webhooks")
    
        async def delete_webhook(self, webhook_id: str) -> dict[str, Any]:
            """Delete a registered webhook."""
            return await self._request("DELETE", f"/v1/webhooks/{webhook_id}")
    
        # -----------------------------------------------------------------
        # Deep research (async pattern)
        # -----------------------------------------------------------------
    
        async def analyze_market(
            self, platform: str, market_id: str
        ) -> dict[str, Any]:
            """Start an async analysis pipeline for a market.
    
            Returns immediately with an analysis_id for polling.
    
            Args:
                platform: "kalshi" or "polymarket".
                market_id: Platform-specific identifier.
            """
            return await self._request(
                "POST", f"/v1/markets/{platform}/{market_id}/analyze"
            )
    
        async def check_analysis_status(
            self, platform: str, market_id: str, analysis_id: str
        ) -> dict[str, Any]:
            """Check whether an async analysis has completed.
    
            Args:
                platform: "kalshi" or "polymarket".
                market_id: Platform-specific identifier.
                analysis_id: ID returned by analyze_market.
            """
            return await self._request(
                "GET",
                f"/v1/markets/{platform}/{market_id}/analyze/{analysis_id}/status",
            )
    
        async def get_analysis(
            self, platform: str, market_id: str, expand: str = ""
        ) -> dict[str, Any]:
            """Get the latest analysis for a market.
    
            Args:
                platform: "kalshi" or "polymarket".
                market_id: Platform-specific identifier.
                expand: Comma-separated expansions (e.g. "scenarios,causal").
            """
            params: dict[str, str] = {}
            if expand:
                params["expand"] = expand
            return await self._request(
                "GET", f"/v1/markets/{platform}/{market_id}/analysis", params=params
            )
    
        async def list_analyses(self, limit: int = 20) -> dict[str, Any]:
            """List recent analyses with summary information.
    
            Args:
                limit: Maximum number of analyses to return (1-50).
            """
            return await self._request(
                "GET", "/v1/analyses", params={"limit": limit}
            )
    
        # -----------------------------------------------------------------
        # Strategy & portfolio
        # -----------------------------------------------------------------
    
        async def get_strategy(
            self,
            market_query: str = "",
            platform: str = "",
            market_id: str = "",
            force: bool = False,
            wait: bool = True,
            expand: str = "",
        ) -> dict[str, Any]:
            """Generate a strategy signal for a market.
    
            By default blocks until the pipeline completes (30-90s).
            Set wait=False for async mode (returns 202 with analysis_id).
    
            Args:
                market_query: Free-text market question (used if market_id not set).
                platform: "kalshi" or "polymarket".
                market_id: Platform-specific identifier.
                force: Bypass 24h analysis cache.
                wait: Block until complete (default True).
                expand: Comma-separated expansions (e.g. "causal").
            """
            body: dict[str, Any] = {}
            if market_query:
                body["market_query"] = market_query
            if platform:
                body["platform"] = platform
            if market_id:
                body["market_id"] = market_id
            if force:
                body["force"] = True
    
            params: dict[str, Any] = {}
            if wait:
                params["wait"] = "true"
            if expand:
                params["expand"] = expand
    
            return await self._request(
                "POST", "/v1/signals", json=body, params=params
            )
    
        async def get_portfolio_strategy(
            self,
            market_query: str,
            portfolio: list[dict[str, Any]] | None = None,
            bankroll_usd: float = 1000,
            max_position_pct: float = 0.10,
        ) -> dict[str, Any]:
            """Get a portfolio-aware strategy signal."""
            body: dict[str, Any] = {
                "market_query": market_query,
                "bankroll_usd": bankroll_usd,
                "max_position_pct": max_position_pct,
            }
            if portfolio is not None:
                body["portfolio"] = portfolio
            return await self._request("POST", "/v1/signals/portfolio", json=body)
    
        async def get_consensus(
            self,
            platform: str,
            market_id: str,
            period: str = "7d",
        ) -> dict[str, Any]:
            """Get consensus probability from aggregated agent trades."""
            params: dict[str, Any] = {"period": period}
            return await self._request(
                "GET",
                f"/v1/markets/{platform}/{market_id}/consensus",
                params=params,
            )
    
        async def what_if(
            self,
            market_query: str,
            hypothesis: str,
            platform: str = "",
        ) -> dict[str, Any]:
            """Analyze how a hypothetical scenario would affect a market's probability.
    
            Args:
                market_query: Market question, ticker, or URL.
                hypothesis: Hypothetical scenario to evaluate (e.g. "Fed cuts rates by 50bps").
                platform: Platform hint: "kalshi" or "polymarket".
            """
            body: dict[str, Any] = {
                "market_query": market_query,
                "hypothesis": hypothesis,
            }
            if platform:
                body["platform"] = platform
            return await self._request("POST", "/v1/what-if", json=body)
    
        # -----------------------------------------------------------------
        # Arbitrage
        # -----------------------------------------------------------------
    
        async def get_arbitrage(
            self, min_spread: float = 0.02
        ) -> dict[str, Any]:
            """Get cross-platform arbitrage opportunities (cached)."""
            return await self._request(
                "GET", "/v1/arbitrage", params={"min_spread": min_spread}
            )
    
        async def get_arbitrage_live(
            self, min_spread: float = 0.02
        ) -> dict[str, Any]:
            """Run a fresh arbitrage scan (may take 10-30s)."""
            return await self._request(
                "GET", "/v1/arbitrage/live", params={"min_spread": min_spread}
            )
    
        # -----------------------------------------------------------------
        # Correlation
        # -----------------------------------------------------------------
    
        async def get_correlation(
            self,
            market_ids: list[str],
            platform: str = "kalshi",
            period: str = "7d",
        ) -> dict[str, Any]:
            """Get cross-market correlation graph."""
            return await self._request(
                "POST",
                "/v1/correlation",
                json={
                    "market_ids": market_ids,
                    "platform": platform,
                    "period": period,
                },
            )
    
        # -----------------------------------------------------------------
        # Consensus trading
        # -----------------------------------------------------------------
    
        async def report_trade(
            self,
            market_id: str,
            platform: str,
            side: str,
            size_usd: float,
            price: float,
        ) -> dict[str, Any]:
            """Report a trade for consensus aggregation."""
            return await self._request(
                "POST",
                "/v1/trades/report",
                json={
                    "market_id": market_id,
                    "platform": platform,
                    "side": side,
                    "size_usd": size_usd,
                    "price": price,
                },
            )
    
        # -----------------------------------------------------------------
        # Analytics
        # -----------------------------------------------------------------
    
        async def get_sentiment(self) -> dict[str, Any]:
            """Get market sentiment snapshot (fear/greed index, regime, top movers)."""
            return await self._request("GET", "/v1/sentiment")
    
        async def get_performance(self, mode: str = "shadow") -> dict[str, Any]:
            """Get aggregate trading performance statistics."""
            return await self._request(
                "GET", "/v1/performance", params={"mode": mode}
            )
    
        async def get_performance_history(
            self, mode: str = "shadow"
        ) -> dict[str, Any]:
            """Get daily P&L time series for equity curve charting."""
            return await self._request(
                "GET", "/v1/performance/history", params={"mode": mode}
            )
    
        # -----------------------------------------------------------------
        # Free endpoints (no auth required)
        # -----------------------------------------------------------------
    
        async def get_pricing(self) -> dict[str, Any]:
            """Get current tier pricing for all endpoints. No auth required."""
            return await self._request("GET", "/v1/pricing")
    
        async def get_health(self) -> dict[str, Any]:
            """Health check. No auth required."""
            return await self._request("GET", "/v1/health")
    
        # -----------------------------------------------------------------
        # Internal
        # -----------------------------------------------------------------
    
        async def _request(
            self, method: str, path: str, **kwargs: Any
        ) -> dict[str, Any]:
            """Make a request. x402 payment is handled by the transport layer."""
            resp = await self._client.request(method, path, **kwargs)
    
            if resp.status_code == 402:
                # No signer configured (or payment failed)
                payment_details = self._parse_payment_required(resp)
                return {
                    "error": "payment_required",
                    "status": 402,
                    "detail": "x402 payment needed -- configure a signer (set X402_PRIVATE_KEY env var)",
                    "payment": payment_details,
                }
    
            resp.raise_for_status()
            return resp.json()  # type: ignore[no-any-return]
    
        @staticmethod
        def _parse_payment_required(resp: httpx.Response) -> dict[str, Any]:
            """Extract x402 payment requirements from a 402 response."""
            import base64
    
            raw = resp.headers.get("payment-required", "")
            if raw:
                try:
                    decoded = base64.b64decode(raw)
                    return json.loads(decoded)
                except Exception:
                    return {"raw": raw}
    
            return {}
    
        async def close(self) -> None:
            """Close the underlying HTTP client."""
            await self._client.aclose()
    
        async def __aenter__(self) -> "RekkoClient":
            return self
    
        async def __aexit__(self, *args: Any) -> None:
            await self.close()
    
  • requirements.txt38 Bf26c02ac5afaupstream ↗
    httpx>=0.27
    x402[fastapi]
    eth-account
    

Plain-text copy, no login: /skill-bundles/rekko-skill.md

// REPO STATS

2 stars
0 open issues
Last commit: 7mo ago