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 API keys required
  • Reconnection - Exponential backoff w/ jitter, multi-endpoint failover
  • Wallet filtering - Track specific wallets
  • Batteries - Built-in CLI and Redis support

Installation

pip install ctf-stream

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
ctf stream

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

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

# Use Redis for caching
ctf stream --redis redis://localhost:6379

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

# Test connection
ctf ping

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.2.tar.gz (17.4 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.2-py3-none-any.whl (22.1 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for ctf_stream-0.1.2.tar.gz
Algorithm Hash digest
SHA256 c1949051e4ddb030e73cfeb43eb6ad8a91d055b97820b0315632ee7992a96087
MD5 f02c86f61716fa70bc968f642a3410c0
BLAKE2b-256 91a532d02123281f90739a548daa96e6babcbf986140d753b4b67ced8495969f

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for ctf_stream-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 a30346b5c3b32d888ed0bf42dd101c9367a5d496f5b5dee35dc6a4bbe554f9e2
MD5 b5e1415587563ed6a13005319e7d5c6c
BLAKE2b-256 25e8171f0c39a55859237f1967df51a72b7beb3402f7e6ab021d233253ea9dda

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