Skip to main content

Typed Core

Shared core types and utilities for Typed Clients

PyPI version License

Every Typed Client builds its core on top of this package. Prefer it over a client-local copy of the same logic — a client's own core/ should hold only what's genuinely venue-specific (envelope extraction, error mapping, signing, wire quirks), not a reimplementation of transport, timestamps, or error types.

Installation

pip install typed-core

What it provides

module contents
typed_core.exceptions Error, NetworkError, ValidationError, ApiError (BadRequest, AuthError, RateLimited), LogicError
typed_core.http async HTTP client and response helpers
typed_core.ws websocket socket, streams, JSON-RPC, streams-over-RPC
typed_core.grpc GrpcClient/GrpcEndpoint, wrap_exceptions for unary calls and server_stream (a StreamManager) for server-streaming ones, mapping grpclib failures to the errors above by gRPC status (requires the grpc extra)
typed_core.times TimeConverter, EpochConverter, IsoConverter — parse/dump between a venue's wire timestamp and a real datetime
typed_core.util RateLimit, paging and stream helpers
from typed_core.times import EpochConverter, IsoConverter

timestamp_millis = EpochConverter.milliseconds()  # epoch, milliseconds
timestamp_iso = IsoConverter()                    # RFC 3339, Z-suffixed

A wire value carrying no offset is read as UTC, matching what dump already assumes of a naive datetime; pass tz=None to keep it naive instead. Every converter raises ValueError on a value of the wrong kind, so a null on a non-nullable field arrives as an ordinary validation error rather than an AttributeError.

HTTP configuration

from typed_core.http import HttpClient

async with HttpClient(timeout=30, proxy="http://localhost:8080") as http:
  response = await http.request("GET", "https://example.com")
  response = await http.request("GET", "https://example.com", timeout=120)

timeout defaults to five seconds of network inactivity; None disables timeouts. Use httpx.Timeout for separate connect, read, write, and pool limits. Per-request timeout overrides the client default. Requests are single-attempt, with retries left to the caller.

proxy accepts a URL or an httpx.Proxy, including authenticated proxies. When omitted, HTTPX uses HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and NO_PROXY from the environment. An explicit proxy overrides environment proxy routing, including NO_PROXY. For an HTTPS destination, an http:// proxy URL commonly works by tunneling the TLS connection. trust_env=False ignores HTTPX environment settings (proxies and certificate locations), but still uses an explicit proxy. See HTTPX environment variables.

limits continues to control connection pooling. The existing default disables keepalive when uppercase HTTP_PROXY or HTTPS_PROXY is present; pass explicit httpx.Limits to override it, including when using trust_env=False.

All construction settings apply when the underlying HTTPX client is lazily created. An existing client supplied through the legacy _client field keeps its own configuration. A Typed client accepting http=... manages that transport's cleanup when its context exits; use separate transports for independently managed client lifetimes.

Paging

Every generated <method>_paged returns a PaginatedResponse: awaitable (every row, flattened) and async-iterable (one page of rows at a time). Each page is one pure next(state) call, so a caller can retry or resume a single page rather than the whole walk.

from typed_core import PaginatedResponse

paging = client.market.kline_paged(symbol='BTCUSDT', interval='1', start=start, end=end)
candles = await paging                       # every row, flattened
async for rows in paging: ...                # one page at a time
async for page in paging.pages():            # Page(rows, state, next), for checkpointing
  checkpoint(page.next)
paging.resume(saved_state)                   # restart from a checkpointed state
paging.via(retried)                          # route every page fetch through a middleware

via(call) hands each page fetch to call as one zero-argument coroutine function, so a retry or logging layer wraps a page without unrolling the loop by hand.

WebSocket connection drops

Streams and requests are bound to the connection they were made on. When it drops, or the client is closed, everything bound to it raises NetworkError:

  • a stream raises right away if it is being iterated, otherwise on its next read (after any message it had already received); it never reconnects on its own
  • a request waiting for its reply raises

Leaving a stream whose connection is gone (async with exit or unsubscribe()) does nothing: no frame, no reconnect, no exception, so the stream's own NetworkError is what surfaces. A new subscription or request after a drop simply opens a fresh connection. Resubscribing is up to the caller:

from typed_core.exceptions import NetworkError

while True:
  try:
    async with socket.subscribe('trades') as trades:
      async for trade in trades:
        ...
  except NetworkError:
    await asyncio.sleep(1)  # then subscribe again, on a fresh connection

WebSocket handshake headers

A venue that authenticates a socket only when it opens (a session cookie, an account id) takes them as headers, sent with the opening handshake. They are read on every connect, so replacing them applies to the next connection, not to the one already open:

socket = MyStreams(url, headers={'Cookie': f'session={token}'})
...
socket.headers = {'Cookie': f'session={new_token}'}  # used from the next connect on

Large messages

A socket accepts incoming messages up to 1 MiB, websockets' default. A larger one closes the connection with code 1009, failing the work bound to it. A venue that pushes bigger frames (a full order book or protocol-state snapshot) raises the limit with max_size, in bytes, or lifts it with None:

socket = MyStreams(url, max_size=8 * 2**20)

Keep-latest subscriptions

By default a stream delivers every message, in order. For a channel whose every message is a full snapshot (best bid/ask, partial depth, mark price), subscribe(..., keep_latest=True) delivers only the newest one: a message arriving before the previous one was read replaces it, and stream.skipped counts the replaced ones. Never use it for diffs, trades, fills or account events.

A transport that can tell which subscription a frame belongs to without decoding it implements route_raw; such frames are kept raw and only parsed (and validated) if they are still the newest when read. Otherwise frames are decoded to route them as usual, and only validation is skipped for the replaced ones.

async with socket.subscribe('btcusdt@bookTicker', keep_latest=True) as book:
  async for ticker in book:
    ...
    log.debug('skipped %d stale tickers so far', book.skipped)

Closing is cancellation-safe. Cancelling one caller waiting for a connection never affects the other callers or the connect itself. The owner's exit never waits for a connect in flight. Instead, that connect closes its own connection once it completes, and the work that joined it before the exit raises NetworkError. Work that joined only after the exit reconnects once. An exit cancelled mid-close aborts the connection instead of leaving it half-open, and an HttpClient exit that is cancelled still closes its client.

Clients re-export the exceptions users are expected to catch from their own package root, so from kraken import AuthError works while implementation imports still come from typed_core. Route those re-exports through lazy_loader.attach_stub, not a plain from typed_core.exceptions import ... in an __init__.py — the latter breaks type-checking for every downstream consumer of a py.typed package.

License

MIT — see LICENSE.

Metadata

Release files for typed-core 0.14.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for typed-core 0.14.0
File Size Uploaded Provenance Actions
typed_core-0.14.0.tar.gz 59.5 kB With provenance Details for typed_core-0.14.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for typed-core 0.14.0
File Interpreter ABI Platform Actions
typed_core-0.14.0-py3-none-any.whl Python 3 none any Details for typed_core-0.14.0-py3-none-any.whl

Total release size: 100.0 kB

Release files / typed_core-0.14.0.tar.gz

Download URL typed_core-0.14.0.tar.gz
Size 59.5 kB
Tags Source
SHA-256 checksum
How to use checksums
b678a54577f050d88d35eb77aa2713cb5c6e4a9784b43cd006e7ea89d5837425
BLAKE2b-256 checksum
How to use checksums
0e28087046cf388ceccaf5f6b0b1f74a0b7aad21d77643a43b0d90cd999e3a48
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.

Transparency log

Release files / typed_core-0.14.0-py3-none-any.whl

Download URL typed_core-0.14.0-py3-none-any.whl
Size 40.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6ede1c1499351580660af3899adb02f83197d4788ae07db931e384b7daba20ba
BLAKE2b-256 checksum
How to use checksums
67e5e227483fe1b3795b1e0df2aef3cea8b681c821157e2b704246827ddf1612
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.

Transparency log

Security for typed-core 0.14.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for typed_core-0.14.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.14.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page