Skip to main content

CTF activity stream SDK for prediction markets.

Project description

CTF Activity Stream

Release Python 3.10+ License: MIT

Simple activity streaming SDK for prediction markets.

Features

  • Fast - Trades arrive as blocks are mined
  • Simple - No extra API
  • Reconnection - Exponential backoff w/ jitter, multi-endpoint failover
  • Wallet filtering - Track specific wallets
  • CLI included - Simple command-line tool

Installation

# Core (no Redis)
pip install ctf-stream

# With Redis cache support
pip install ctf-stream[redis]

# With CLI tools
pip install ctf-stream[cli]

# Everything
pip install ctf-stream[all]

Quick Start

import asyncio
from ctf_stream import ActivityClient

async def main():
    # Initialize client with RPC endpoints
    client = ActivityClient(
        rpc_endpoints=["wss://polygon-bor-rpc.publicnode.com"]
    )
    
    # Option 1: Track specific Safe address
    await client.track_wallet("0x1234567890123456789012345678901234567890")
    # Option 2: Stream all trades
    # client.set_track_all(True)
    
    # Stream trades
    async for trade in client.stream_trades():
        print(f"{trade.side} ${trade.size_usdc:.2f} | {trade.outcome} @ {trade.price:.2%}")
        print(f"  Market: {trade.market_title}")
        print(f"  Wallet: {trade.wallet}")

asyncio.run(main())

With Context Manager

async with ActivityClient(rpc_endpoints=["wss://..."]) as client:
    client.set_track_all(True)
    async for trade in client.stream_trades():
        process(trade)

CLI Usage

# Stream all trades (default endpoints)
ctf stream

# Use specific RPC endpoint
ctf stream --rpc wss://polygon-bor-rpc.publicnode.com

# Track specific Safe address/wallet
ctf stream --wallet 0x1234...

# Save to file (JSONL)
ctf stream --output trades.jsonl

# Test connection
ctf ping --rpc wss://polygon-bor-rpc.publicnode.com

CLI Output

🟥 Running...
Press Ctrl+C to stop

12:34:56 BUY       $500.00 Yes             @ 45.0%  | Will it rain tomorrow?
12:34:58 SELL      $250.00 No              @ 55.0%  | Bitcoin above $100k by March?

API Reference

ActivityClient

Main client for streaming trades.

from ctf_stream import ActivityClient, Config

# Basic initialization
client = ActivityClient(
    rpc_endpoints=["wss://polygon-bor-rpc.publicnode.com"],
    redis_url="redis://localhost:6379",  # Optional
)

# Or with full config
config = Config(
    rpc_endpoints=["wss://polygon-bor-rpc.publicnode.com"],
    ws_idle_timeout=60,
    token_cache_ttl=3600,
)
client = ActivityClient(config=config)

# Methods
await client.track_wallet("0x...")      # Track wallet
await client.untrack_wallet("0x...")    # Untrack wallet
await client.track_wallets(["0x...", "0x..."])  # Track multiple
client.set_track_all(True)              # Stream all trades

# Stream trades
async for trade in client.stream_trades(enrich=True):
    print(trade)

# Get statistics
stats = client.get_stats()
print(stats.websocket.connected)
print(stats.processor.events_processed)

Trade Object

class Trade:
    tx_hash: str
    block_number: int
    timestamp: int
    wallet: str
    token_id: str
    side: str              # "BUY" or "SELL"
    price: float           # 0.0 to 1.0
    size_usdc: float
    size_shares: float
    market_slug: str | None
    market_title: str | None
    outcome: str | None

Config

Config(
    rpc_endpoints=["wss://..."],        # WebSocket RPC endpoints
    redis_url="redis://localhost:6379", # Optional Redis for caching
    ws_idle_timeout=60,                  # Seconds before reconnect
    token_cache_ttl=3600,                # Memory cache TTL
)

RPC Endpoints

The SDK works with any Polygon RPC endpoint that supports WebSocket. Some free options:

Provider Endpoint Notes
publicnode by Allnodes wss://polygon-bor-rpc.publicnode.com Free, reliable
dRPC wss://polygon.drpc.org Free tier available
Alchemy wss://polygon-mainnet.g.alchemy.com/v2/KEY Requires API key
Infura wss://polygon-mainnet.infura.io/ws/v3/KEY Requires API key
ValidationCloud wss://mainnet.polygon.validationcloud.io/v1/KEY Requires API key

Tip: Add multiple endpoints for better reliability:

client = ActivityClient(
    rpc_endpoints=[
        "wss://polygon-bor-rpc.publicnode.com",
        "wss://polygon.drpc.org",
    ]
)

License

MIT License - see LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ctf_stream-0.1.1.tar.gz (17.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ctf_stream-0.1.1-py3-none-any.whl (22.2 kB view details)

Uploaded Python 3

File details

Details for the file ctf_stream-0.1.1.tar.gz.

File metadata

  • Download URL: ctf_stream-0.1.1.tar.gz
  • Upload date:
  • Size: 17.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for ctf_stream-0.1.1.tar.gz
Algorithm Hash digest
SHA256 cde616847d6be50747b0af1570e0c311b4da15bc102ffcb5d2856b6aad789dc1
MD5 d1214176cb7674583d35f9aa36d92612
BLAKE2b-256 3ca9ef2807b1919f0371111cc68875464d05656d199e5e809e4ada5de1c7163c

See more details on using hashes here.

File details

Details for the file ctf_stream-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: ctf_stream-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 22.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for ctf_stream-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 37fdb434e7d5e65367a0033e35d2e33b036836c495a3529a5b6f47e2eeed1fdf
MD5 68e7c3355e1b440a00181cc755d105d6
BLAKE2b-256 7dd4360d58b51aa0595629ff0b39b324df6ab9a0e794309aa7ae07dc7fae52bb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page