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.0.tar.gz (73.5 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.0-py3-none-any.whl (29.7 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for rulebook_python-0.1.0.tar.gz
Algorithm Hash digest
SHA256 0476b5e836b57eac5a73da09ad1fa1d9bc7a0affcacb5c0cea7797920e63ed06
MD5 069da683296b1d7d95eae578be5d63be
BLAKE2b-256 91c1af27f4a490faa4b23098386d30456079c9d552cb6e15a02d77c10f9805fb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for rulebook_python-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2cbfd980c34645d52a36ccd96cb8ac73b16448d8cbecf44e0cbb8b89f1edb5c7
MD5 ae3338910a01f6ea376da21a39e5b480
BLAKE2b-256 341dedaf6ecd5774f4040015ca6ddda6e96f7551a04dad6315020dea0453b15b

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