Skip to main content

Python SDK for the Rulebook Company API — exchange fee schedule and rebate data

Project description

Rulebook Python SDK

The official Python client for the Rulebook Company API — access exchange fee schedule and rebate data across US trading venues.

Python 3.11+ License: MIT

Installation

pip install rulebook-python

Usage

from rulebook import Rulebook

client = Rulebook(api_key="your-api-key")

# List all exchanges
exchanges = client.exchanges.list()
for exchange in exchanges:
    print(f"{exchange.name}: {exchange.display_name} ({exchange.record_count} records)")

# Get details for a specific exchange
detail = client.exchanges.retrieve("NYSE")
print(f"Date range: {detail.date_range.earliest} to {detail.date_range.latest}")
print(f"Fee types: {detail.fee_types}")
print(f"Actions: {detail.actions}")

# List fee schedule results (with filtering)
results = client.fee_schedule_results.list(
    exchange_name=["fee_cboe_us_options"],
    fee_type=["Option"],
    latest_only=True,
    page_size=10,
)
for item in results.data:
    print(f"{item.exchange_name} | {item.fee_type} | {item.fee_amount}")

# Get a single fee schedule result
result = client.fee_schedule_results.retrieve("some-uuid")

# Get available filter values
filters = client.fee_schedule_results.get_filters()
print(f"Exchanges: {filters.exchange_names}")
print(f"Fee types: {filters.fee_types}")

# Get results by extraction version
version_results = client.fee_schedule_results.get_results_by_version("version-uuid")

client.close()

Authentication

Pass your API key directly or set the RULEBOOK_API_KEY environment variable:

# Option 1: Pass directly
client = Rulebook(api_key="...")

# Option 2: Environment variable
# export RULEBOOK_API_KEY=...
client = Rulebook()

Async support

Every method has an async counterpart via AsyncRulebook:

import asyncio
from rulebook import AsyncRulebook

async def main():
    async with AsyncRulebook(api_key="your-api-key") as client:
        exchanges = await client.exchanges.list()
        detail = await client.exchanges.retrieve("NYSE")

asyncio.run(main())

Error handling

The SDK raises typed exceptions for all API errors:

from rulebook import Rulebook, NotFoundError, AuthenticationError, RateLimitError

client = Rulebook()

try:
    detail = client.exchanges.retrieve("UNKNOWN")
except NotFoundError:
    print("Exchange not found")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited — retry after: {e.response.headers.get('retry-after')}")

Exception hierarchy:

Exception Status Code Description
BadRequestError 400 Invalid request parameters
AuthenticationError 401 Missing or invalid API key
PermissionDeniedError 403 Insufficient access for this resource
NotFoundError 404 Resource does not exist
UnprocessableEntityError 422 Request validation failed
RateLimitError 429 Too many requests
InternalServerError 5xx Server-side error
APIConnectionError Network failure
APITimeoutError Request timed out

Raw response access

Access HTTP status codes, headers, and the raw response via with_raw_response:

raw = client.exchanges.with_raw_response.retrieve("NYSE")
print(raw.status_code)                      # 200
print(raw.headers.get("content-type"))      # application/json

detail = raw.parse()                        # ExchangeDetail

Client configuration

client = Rulebook(
    api_key="...",
    base_url="https://api.rulebookcompany.com/api/v1",  # default
    timeout=30.0,         # seconds (default: 30)
    max_retries=2,        # retry transient failures (default: 2)
    default_headers={},   # headers sent on every request
)

Per-request overrides

Override timeout or add headers for a single request without modifying the client:

exchanges = client.exchanges.list(
    extra_headers={"X-Request-Id": "abc-123"},
    timeout=60.0,
)

Immutable client copies

Create a new client with different settings using with_options():

slow_client = client.with_options(timeout=120.0)

Retries

The SDK automatically retries transient errors (408, 409, 429, 500, 502, 503, 504) with exponential backoff and jitter. Configure with max_retries:

client = Rulebook(max_retries=5)  # default is 2

Response types

All responses are strongly typed with Pydantic models:

from rulebook.types import (
    Exchange,
    ExchangeDetail,
    DateRange,
    FeeScheduleResult,
    FeeScheduleResultFilters,
    PaginatedResponse,
)

Exchange — returned by list()

Field Type Description
name str Exchange identifier (e.g., "NYSE")
display_name str Full name (e.g., "New York Stock Exchange")
fee_types List[str] Available fee types (e.g., ["Equity", "Option"])
record_count int Total fee schedule records

ExchangeDetail — returned by retrieve()

Field Type Description
name str Exchange identifier
display_name str Full name
date_range DateRange Earliest and latest dates of available data
fee_types List[str] Available fee types
fee_categories List[str] Fee categories (e.g., ["Fee And Rebates"])
actions List[str] Trade actions (e.g., ["Make", "Take", "Open"])
participants List[str] Participant types (e.g., ["Market Maker", "Customer"])
symbol_classifications List[str] Symbol classifications (e.g., ["ETF", "Equity"])
symbol_types List[str] Symbol types (e.g., ["Penny", "Non Penny"])
trade_types List[str] Trade types (e.g., ["Simple Order"])
record_count int Total fee schedule records

Contributors

Requirements

  • Python 3.11+
  • Dependencies: httpx, pydantic, anyio

License

MIT — 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

rulebook_python-0.1.1.tar.gz (73.1 kB view details)

Uploaded Source

Built Distribution

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

rulebook_python-0.1.1-py3-none-any.whl (29.5 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for rulebook_python-0.1.1.tar.gz
Algorithm Hash digest
SHA256 ef5155106e6c32edf852bd0eaa5061f3e2b0384a8f98e1100bb080e1193fa221
MD5 e3490dac54cbb375adf78df6fc8b8eb1
BLAKE2b-256 03b9ac0114383498a094972007295659b924a93f72a4c2e676886e6769a1ceb6

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for rulebook_python-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 580b849777074bfd85827490f7dfa794a88d714fb1dbdf58d4693648dcd07bc8
MD5 ef8e85c5a95cf26648e664114fed2d07
BLAKE2b-256 17e790f2cb568b80110b4c07173076cf3572b5abcf472580c5e16c6377f22760

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