Skip to content

Paradex Python SDK

Warning

Experimental SDK, library API is subject to change

paradex_py.paradex.Paradex

Bases: _ClientBase

Paradex class to interact with Paradex REST API.

Parameters:

Name Type Description Default
env Environment

Environment

required
l1_address str

L1 address. Defaults to None.

None
l1_private_key str

L1 private key. When auto_auth onboards a new account it also signs a SIWE message linking the L1 wallet as the account's parent. Defaults to None.

None
l1_private_key_from_ledger bool

Derive L2 key from Ledger hardware wallet. When auto_auth onboards a new account, the Ledger signs the parent link message too. Defaults to False.

False
l2_private_key str

L2 private key. Onboarding with only this key sends no parent link. Defaults to None.

None
logger Logger

Logger. Defaults to None.

None
ws_timeout int

WebSocket read timeout in seconds. Defaults to None (uses default).

None
http_client HttpClient

Custom HTTP client for injection. Defaults to None.

None
api_base_url str

Custom API base URL override. Defaults to None.

None
default_timeout float

Default HTTP request timeout in seconds. Defaults to None.

None
retry_strategy RetryStrategy

Custom retry/backoff strategy. Defaults to DefaultRetryStrategy (rate-limit-aware retries). Pass None to disable retries.

_UNSET
request_hook RequestHook

Hook for request/response observability. Defaults to None.

None
enable_http_compression bool

Enable HTTP compression (gzip, deflate, br). Defaults to True.

True
auto_start_ws_reader bool

Whether to automatically start WS message reader. Defaults to True.

True
ws_connector WebSocketConnector

Custom WebSocket connector for injection. Defaults to None.

None
ws_url_override str

Custom public WebSocket URL override. Defaults to None.

None
ws_direct_url_override str

Custom direct (authenticated) WebSocket URL override. Defaults to None.

None
ws_reader_sleep_on_error float

WebSocket reader sleep duration after errors. Defaults to 1.0.

1.0
ws_reader_sleep_on_no_connection float

WebSocket reader sleep when no connection. Defaults to 1.0.

1.0
validate_ws_messages bool

Enable JSON-RPC message validation. Defaults to False. Applies to JSON text frames only, which an SBE connection still carries for some channels (see ws_sbe_enabled).

False
ping_interval float

WebSocket ping interval in seconds. Defaults to None.

None
disable_reconnect bool

Disable automatic WebSocket reconnection. Defaults to False.

False
enable_ws_compression bool

Enable WebSocket per-message compression (RFC 7692). Defaults to True.

True
ws_sbe_enabled bool

Use SBE binary encoding on both ws_client and ws_direct_client. Defaults to True: the Paradex WebSocket endpoints require SBE and answer a plain JSON connect with HTTP 400. Pass False only for an endpoint that still serves JSON. Callbacks receive SBE-decoded models dumped to dicts, and some field names differ (trade_id_str/seq_no/order_type for JSON id/seq/type; order_book gives bids/asks rather than inserts/updates/deletes). On trades, use trade_id_str: the int64 trade_id is deprecated and holds only the low 64 bits of the real id. Public market data always arrives as SBE, but private channels (orders, fills, positions, account) arrive as SBE or JSON depending on the account, and channels without an SBE form (e.g. balance_events, transfers) stay JSON. Each message carries message["encoding"] ("sbe" or "json") so a callback can tell which field names it got.

True
auto_auth bool

Whether to automatically handle onboarding/auth. Defaults to True. Initializing an account still calls GET /onboarding when this is False, unless server_derive_address=False.

True
auth_provider AuthProvider

Custom authentication provider. Defaults to None.

None
auth_params dict

Extra query parameters sent with every /auth request (initial and refresh). For example, {"token_usage": "interactive"} for 0-fee JWT. Defaults to None.

None
signer Signer

Custom order signer for submit/modify/batch operations. Defaults to None.

None
rpc_version str

RPC version (e.g., "v0_9"). If provided, constructs URL as {base_url}/rpc/{rpc_version}. Defaults to None.

None
config SystemConfig

System configuration. If provided, uses this config instead of fetching from API. Defaults to None. Initializing an account still calls GET /onboarding unless server_derive_address=False.

None
server_derive_address bool

Fetch the L2 address from GET /onboarding (one public request when the account is initialized) rather than computing it locally. The server's address is right for accounts created with either the legacy proxy class or the current class; local derivation computes the legacy proxy-class address, which is wrong for accounts created with the current class (such as new accounts onboarded in the Paradex app). Also caches the exists flag so POST /onboarding is skipped when the account is already onboarded. If the request fails, account initialization raises ValueError rather than falling back. Pass False to derive the address locally. Defaults to True.

True

Examples:

>>> from paradex_py import Paradex
>>> from paradex_py.environment import Environment
>>> paradex = Paradex(env=Environment.TESTNET)
>>> # With custom timeout
>>> paradex = Paradex(env=Environment.TESTNET, ws_timeout=30)
>>> # With simulator-friendly injection (high-frequency, no sleeps)
>>> paradex = Paradex(env=Environment.TESTNET, auto_start_ws_reader=False,
...                   http_client=custom_client, ws_connector=custom_connector,
...                   ws_reader_sleep_on_error=0, ws_reader_sleep_on_no_connection=0)

auth_level: AuthLevel property

Reflects the current authentication state.

Returns AuthLevel.FULL when an account is initialized, AuthLevel.AUTHENTICATED when only an auth_provider is set (token present, no signing key), or AuthLevel.UNAUTHENTICATED when neither is available.

Paradex can be constructed without keys and initialized later via init_account(), so this property reflects the current state.

can_trade: bool property

True when account is initialized — L2 key is available for signing.

can_withdraw: bool property

True when account is initialized — full account key, all on-chain operations available (deposit, withdraw, transfer).

is_authenticated: bool property

True when an account is initialized or an auth_provider is set.

is_onboarded: bool | None property

Cached onboarding state from GET /onboarding.

Returns True / False when GET /onboarding populated the cache at account initialization (the default), None when the server omitted it or with server_derive_address=False (the SDK then learns onboarding status lazily via the NOT_ONBOARDED auth-retry flow).

__init__(env, l1_address=None, l1_private_key=None, l1_private_key_from_ledger=False, l2_private_key=None, logger=None, ws_timeout=None, http_client=None, api_base_url=None, default_timeout=None, retry_strategy=_UNSET, request_hook=None, enable_http_compression=True, auto_start_ws_reader=True, ws_connector=None, ws_url_override=None, ws_direct_url_override=None, ws_reader_sleep_on_error=1.0, ws_reader_sleep_on_no_connection=1.0, validate_ws_messages=False, ping_interval=None, disable_reconnect=False, enable_ws_compression=True, ws_sbe_enabled=True, auto_auth=True, auth_provider=None, auth_params=None, signer=None, rpc_version=None, config=None, server_derive_address=True)

init_account(l1_address, l1_private_key=None, l1_private_key_from_ledger=False, l2_private_key=None, rpc_version=None)

Initialize paradex account with l1 or l2 private keys. Cannot be called if account is already initialized.

Parameters:

Name Type Description Default
l1_address str

L1 address

required
l1_private_key str

L1 private key

None
l1_private_key_from_ledger bool

Derive L2 key from Ledger hardware wallet. Defaults to False.

False
l2_private_key str

L2 private key

None
rpc_version str

RPC version (e.g., "v0_9"). If provided, constructs URL as {base_url}/rpc/{rpc_version}. Defaults to None.

None

L2-Only Authentication (Subkeys)

For users who only have L2 credentials (subkeys) and don't need L1 onboarding:

paradex_py.paradex_subkey.ParadexSubkey

Bases: ParadexL2

Registered subkey authentication — trade-scoped subclass of ParadexL2 with trade-scoped capabilities (no withdrawals).

Subkeys are registered signing keys scoped to order management only. Use ParadexL2 directly when authenticating with a main account key.

Parameters:

Name Type Description Default
env Environment

Environment

required
l2_private_key str

The subkey's L2 private key (required)

required
l2_address str

The main account address this subkey is registered under. This is not the subkey's own derived address — it must be the address of the parent account that registered this subkey.

required
logger Logger

Logger. Defaults to None.

None
ws_timeout int

WebSocket read timeout in seconds. Defaults to None.

None
ws_enabled bool

Whether to create a WebSocket client. Defaults to True.

True
ws_sbe_enabled bool

Use SBE binary encoding on the WebSocket. Defaults to True, which the Paradex endpoints require; pass False only for an endpoint that still serves JSON.

True

Examples:

>>> from paradex_py import ParadexSubkey
>>> from paradex_py.environment import TESTNET
>>> paradex = ParadexSubkey(
...     env=TESTNET,
...     l2_private_key="0x<subkey-private-key>",
...     l2_address="0x<main-account-address>",  # parent account, not subkey address
... )
>>> paradex.can_trade
True
>>> paradex.can_withdraw
False

auth_level: AuthLevel property

AuthLevel.TRADING — subkey can sign orders but not withdrawals.

can_withdraw: bool property

Always False — subkeys can only sign orders; direct on-chain operations (deposit, withdraw, transfer) require the full account key.

Usage Examples

L1 + L2 Authentication (Traditional):

from paradex_py import Paradex
from paradex_py.environment import Environment

# Requires both L1 and L2 credentials
paradex = Paradex(
    env=Environment.TESTNET,
    l1_address="0x...",
    l1_private_key="0x..."
)

L2-Only Authentication (Subkeys):

from paradex_py import ParadexSubkey
from paradex_py.environment import Environment

# Only requires L2 credentials - no L1 needed
paradex = ParadexSubkey(
    env=Environment.TESTNET,
    l2_private_key="0x...",
    l2_address="0x..."
)

# Use exactly like regular Paradex
await paradex.init_account()  # Already initialized
markets = await paradex.api_client.get_markets()

WebSocket Usage:

The WebSocket clients connect with SBE binary encoding by default, which the Paradex endpoints require; frames are decoded to dicts before your callback runs.

async def on_message(ws_channel, message):
    print(ws_channel, message)

await paradex.ws_client.connect()
await paradex.ws_client.subscribe(ParadexWebsocketChannel.MARKETS_SUMMARY, callback=on_message)

When to Use Each Approach

Use Paradex (L1 + L2) when: - You have both L1 (Ethereum) and L2 (Starknet) credentials - You have never logged in to Paradex using this account before - You need to perform on-chain operations (transfers, withdrawals)

Use ParadexSubkey (L2-only) when: - You only have L2 credentials - The account has already been onboarded (You have logged in to Paradex before) - You do not need on-chain operations (withdrawals, transfers)

Key Differences

Feature Paradex ParadexSubkey
Authentication L1 + L2 L2-only
Onboarding ✅ Supported ❌ Blocked
On-chain Operations ✅ Supported ❌ Blocked
API Access ✅ Full access ✅ Full access
WebSocket ✅ Supported ✅ Supported
Order Management ✅ Supported ✅ Supported

Session Keys (Experimental)

Warning

Experimental. The session endpoints are live, but this SDK API may still change.

An account owner signs one SessionGrant that lets a scoped, expiring Stark session key trade the anchor account and any listed sub-accounts. A session can never withdraw. register_session takes an EVM (EIP-712) owner signature; SessionGrant also renders SNIP-12 typed data for Stark-key owners, but the SDK does not register those yet. Paradex enables sessions per account: until it does, register_session raises SESSIONS_DISABLED (only once the owner's signature verifies). SessionAccounts then keeps a JWT (at most 15 minutes, never past the session's expiry), a REST client and a websocket per account, routes calls by account, and drops every account at once when the session expires or is revoked. session.revoke() also cancels the session's resting orders, TWAPs and untriggered stops. With revoke(cancel_orders=False), a grant with no builder signs out and its orders keep working, and the revoked key can no longer cancel them; a builder grant still has its TWAPs and untriggered stops cancelled and keeps only its resting orders.

Every grant states each limit: a positive decimal, or "none" for no cap from this session. markets lists symbols or patterns, or is ["*"] for every permitted market. Empty values are refused before signing. Limits(), the default, states no caps: every limit "none" and markets ["*"]. While the server enforces no session limits, that is the only form it accepts, for grants that approve a builder too. A grant that approves a builder can't include trade:block or account:settings. Limits.caps can refuse limits above your own ceilings before signing; there are none by default, and the server enforces its own.

When you show a grant to the owner before they sign, describe its risk in plain words. Limits.loss_wording() gives "Cannot withdraw; can lose up to USD by trading", or, when maxLoss is "none", "Cannot withdraw; trading losses are not capped by this session".

A wallet with no Paradex account can open one with its first grant, so one signature both onboards and starts the session. Name the account the wallet would onboard to (fetch_onboarding({"account_signer_type": "eip191", "eth_address": wallet})["address"]) and list no sub-accounts. Only an EOA can do this, and the account is deployed when it is first funded. register_session takes the onboarding fields referral_code, marketing_code and utm, which the owner does not sign, and a privy_access_token; they are used only when the grant opens an account. Such a request can also be refused with the onboarding errors, such as INSUFFICIENT_MIN_CHAIN_BALANCE, PARENT_ADDRESS_ALREADY_ONBOARDED, or HTTP 429 ONBOARDING_RATE_LIMITED (raised as Rate limit exceeded: ONBOARDING_RATE_LIMITED).

A grant can list the owner wallet's own EVM sub-accounts: fetch_evm_subaccounts(eth_address) lists them without a login, and the owner creates one with create_evm_subaccount() from its own ParadexEvm login. Paradex enables EVM sub-accounts per account. Before the owner signs, register_session refuses any listed sub-account that is not among them, which the server would refuse with ACCOUNT_NOT_ELIGIBLE. It needs the owner's address for that: LocalOwnerSigner has one; for another signer, pass owner_address. Without the address, or when the listing cannot be read, the check is skipped and the server refuses such a grant after the owner signs.

RFQ create, execute and drafts accept a session only when its grant includes trade:rfq, caps nothing (Limits()), approves no builder, and Paradex has enabled RFQ sessions for the account. Otherwise they answer HTTP 403 REQUEST_NOT_ALLOWED. An account not yet deployed on chain gets 400 NOT_ONBOARDED from every RFQ route. A 403 is a refused action, never a revocation signal, so it does not drop the session.

A session can deposit into its own account: POST /v1/deposit-addresses, and Layerswap swaps into Paradex with use_deposit_address (no source_address). A swap out of Paradex gets HTTP 403.

A passkey registered for the Paradex app (no builder) may grant trade, trade:rfq and account:settings; a builder's passkey grants trade only.

from paradex_py import SessionAccounts
from paradex_py.message.session import SessionGrant
from paradex_py.session_accounts import LocalOwnerSigner, new_session_key, register_session

session_private_key, session_public_key = new_session_key()
grant = SessionGrant.new(
    paradex_chain="PRIVATE_SN_PARACLEAR_TESTNET",
    environment="testnet",
    account="0x<main-account>",
    subaccounts=["0x<sub-account>"],
    session_key=session_public_key,
    label="my bot",
    scopes=["trade"],
    ttl_seconds=7 * 24 * 3600,
)
# Any OwnerSigner works here, e.g. an MPC service that signs the EIP-712 typed data itself.
grant_id = register_session("testnet", grant, LocalOwnerSigner("0x<owner-eth-key>"))["grant_id"]
# The grant id is the grant's hash, so a restart needs this exact grant: keep grant.to_message() and
# grant_id with the session key, and rebuild with SessionGrant.from_message(saved_message).
saved_message = grant.to_message()

session = SessionAccounts(
    env="testnet", grant=grant, session_private_key=session_private_key, grant_id=grant_id
)
session.submit_order("0x<sub-account>", order)
await session.connect_ws()

paradex_py.session_accounts.SessionAccounts

One session key, its grant, and a JWT, REST client and websocket per listed account.

.. warning:: Experimental; see the module docstring.

Parameters:

Name Type Description Default
env Environment

Environment.

required
grant SessionGrant

The owner-signed grant (already registered with the server).

required
session_private_key str

The session's Stark private key; its public key must be grant.session_key.

required
grant_id str

The id register_session returned for grant (a hash of it, so it is checked); used to check and revoke the grant.

required
config SystemConfig | None

Pre-fetched system configuration; fetched once if omitted.

None
logger Logger | None

Logger.

None
auth_params dict | None

Extra /auth query parameters. token_usage is refused: the server decides it.

None
http_client_factory Callable[[], Client] | None

Builds the HTTP client for each account (each holds its own JWT header).

None
api_base_url str | None

Optional /v1 base URL override for every account's client, as in register_session.

None
retry_strategy RetryStrategy | None

Optional retry strategy for every account's client (e.g. DefaultRetryStrategy).

None
ws_enabled bool

Whether to create a websocket client per account.

True
ws_connector WebSocketConnector | None

Optional websocket connector, passed to every websocket client.

None
on_dropped Callable[[str], None] | None

Called once with the reason when the session is dropped.

None
clock Callable[[], float]

Time source in seconds, for tests.

time
sleep Callable[[float], None]

Blocking sleep used between /auth retries, for tests.

sleep

Examples:

>>> grant_id = register_session(TESTNET, grant, owner_signer)["grant_id"]
>>> session = SessionAccounts(env=TESTNET, grant=grant, session_private_key=key, grant_id=grant_id)
>>> session.submit_order(sub_account, order)          # routed to that account's JWT
>>> await session.connect_ws()                        # one socket per account
>>> await session.ws(sub_account).subscribe(...)

is_live: bool property

Whether the session is neither dropped nor past its expiry.

api(account)

The REST client authenticated as account.

close() async

Drop the session (if live) and release every connection.

connect_ws() async

Connect and authenticate one websocket per account, and drop everything at expiry.

If a socket fails to connect, the ones already connected are closed again.

drop(reason)

Drop every account at once: clear JWTs, close sockets, refuse further calls. Idempotent.

revoke(cancel_orders=True)

Revoke the grant on the server (DELETE /v2/sessions/{grant_id}), then drop every account.

With cancel_orders (the default) the server also cancels the session's resting orders, TWAPs and untriggered stops on every account. Without it, a grant with no builder signs out: its resting orders, TWAPs and stops keep working, and this key can no longer cancel them. A builder grant still has its TWAPs and untriggered stops cancelled, and keeps only its resting orders.

The session drops only when the server confirms: success, or 404 for a grant it no longer has. Otherwise it stays live and :class:SessionRevokeError is raised, so the call can be retried. After a 5xx the grant may already be revoked with its orders still working: a retry is then refused and drops the session, and only the owner's revoke with cancel_orders cancels them. Call it before :meth:close: a dropped session no longer logs in, so it cannot revoke.

submit_order(account, order)

Sign order with the session key and submit it as account.

ws(account)

The websocket client authenticated as account.

paradex_py.api.protocols.OwnerSigner

Bases: Protocol

Protocol for the account owner's signature over session typed data.

register_session gets the owner's signature on a session grant through this hook, so a wallet, hardware device or MPC service can sign the EIP-712 typed data itself; the SDK never needs the owner's key. LocalOwnerSigner is the in-process implementation.

signature_chain_id: int property

The EVM chain id the signer signs on; it becomes the EIP-712 domain chainId.

sign_typed_data(typed_data)

Sign EIP-712 typed data (eth_signTypedData_v4 semantics).

Parameters:

Name Type Description Default
typed_data dict[str, Any]

Full typed data: types, primaryType, domain and message

required

Returns:

Type Description
str

The 65-byte 0x r||s||v signature

paradex_py.message.session.SessionGrant dataclass

Bases: _TypedMessage

An owner's grant letting a Stark session key trade the named accounts.

Parameters:

Name Type Description Default
paradex_chain str

Paradex chain id string, e.g. "PRIVATE_SN_PARACLEAR_MAINNET".

required
environment str

"mainnet" or "testnet" (see :func:grant_environment); checked by the server.

required
account str

The anchor account address; its owner signs the grant.

required
session_key str

The session's Stark public key.

required
label str

The front end's own label. Display uses the builder's registered name, not this.

required
scopes Sequence[str]

Granted scopes, from :data:GRANTABLE_SCOPES. Empty is a read-only session.

required
limits Limits

Trading limits; Limits() (no caps) by default.

Limits()
builder Builder

Builder approval; Builder() for none.

Builder()
subaccounts Sequence[str]

Sub-account addresses the session also covers. Empty means the anchor only.

()
nonce str

128-bit random 0x hex, chosen by the client (see :func:new_nonce).

new_nonce()
issued_at int

Seconds since the epoch.

lambda: int(time())()
expires_at int

Seconds since the epoch; the server caps it per scope.

0

accounts: list[str] property

Every account the session covers: the anchor first, then the listed sub-accounts.

from_message(message) classmethod

Rebuild a grant from :meth:to_message output (or the EIP-712 typed data's message).

Save grant.to_message() with the session key and the grant id: a session restarted later needs this exact grant, since the grant id is its hash.

grant_ids()

The ids the server gives this grant: (evm_id, stark_id).

For an EVM owner the id is the EIP-712 struct hash of the message, the same on every chain; for a Stark owner it is the SNIP-12 message hash. Both are 0x and 64 lowercase hex digits.

new(*, ttl_seconds, **kwargs) classmethod

Build a grant issued now, expiring ttl_seconds later, with a fresh nonce.

issuedAt is stamped a minute early, so a client clock ahead of the server's cannot push a grant at a lifetime cap over it.

to_message()

Validate and render the message, refusing what the server would refuse.

Builder approvals

An EVM owner can approve a builder's fee without opening a session: BuilderApproval names the builder, its max_fee_rate (above 0 and at most 8 decimal places; the server sets the highest rate) and a required expires_at at most 180 days out, and register_builder_approval has the owner sign it with EIP-712 and sends it to POST /v2/builders/approvals, which needs no JWT. The server refuses an issuedAt in its future, so take it from the server's clock. The owner revokes the approval with DELETE /v2/builders/approvals/{builder_account}.

from paradex_py.api.api_client import ParadexApiClient
from paradex_py.message.session import Builder, BuilderApproval
from paradex_py.session_accounts import LocalOwnerSigner, register_builder_approval

server_time = int(ParadexApiClient(env="testnet").fetch_system_time()["server_time"]) // 1000
approval = BuilderApproval.new(
    server_time=server_time,
    ttl_seconds=30 * 24 * 3600,
    paradex_chain="PRIVATE_SN_PARACLEAR_TESTNET",
    environment="testnet",
    account="0x<main-account>",
    builder=Builder("0x<builder-account>", "0.0005"),
)
register_builder_approval("testnet", approval, LocalOwnerSigner("0x<owner-eth-key>"))

paradex_py.message.session.BuilderApproval dataclass

Bases: _TypedMessage

An EVM owner's standalone approval of a builder's fee, outside any session grant.

Register it with :func:paradex_py.session_accounts.register_builder_approval. It is signed with EIP-712 only; the server refuses Stark-key owners.

Parameters:

Name Type Description Default
paradex_chain str

Paradex chain id string, e.g. "PRIVATE_SN_PARACLEAR_MAINNET".

required
environment str

"mainnet" or "testnet" (see :func:grant_environment).

required
account str

The anchor account; its owner signs the approval.

required
builder Builder

The builder and its fee cap. expires_at is required and at most :data:BUILDER_APPROVAL_MAX_SECONDS after issued_at. max_fee_rate is above 0 and has at most 8 decimal places.

required
subaccounts Sequence[str]

Sub-accounts the approval also covers. Empty means the anchor only.

()
nonce str

128-bit random 0x hex (see :func:new_nonce).

new_nonce()
issued_at int

Seconds since the epoch, by the server's clock. The server refuses an issuedAt in its future, so take it from the server (see :meth:new), not the local clock.

required

from_message(message) classmethod

Rebuild an approval from :meth:to_message output.

new(*, server_time, ttl_seconds, **kwargs) classmethod

Build an approval issued at server_time (seconds), expiring ttl_seconds later.

kwargs carries the other fields; builder gives the account and fee rate, and its expires_at is set here. issuedAt is server_time as is: the server refuses an approval issued before the builder's last revoke, so a backdated one could not re-approve a builder just revoked.

sign_snip12(stark_private_key)

Not supported: the server accepts builder approvals signed with EIP-712 only.

to_message()

Validate and render the message, refusing what the server would refuse.

The owner lists its approvals with ParadexApiClient.fetch_builder_approvals() (live ones, newest first; include_inactive=True adds revoked and expired ones, for the history) and revokes one with revoke_builder_approval(builder_account), which also cancels the resting orders naming the builder on the account and its sub-accounts. Both need the owner's main-key login; a session or subkey JWT is refused, and listing is also refused for an account Paradex has not enabled sessions for. Each approval reports its status (active, revoked or expired), max_fee_rate and its expires_at, approved_at and revoked_at times in milliseconds.

Builder Codes stats

fetch_builder_stats(builder_account) and fetch_builder_leaderboard(window) are public. Stats come per window (24h, 7d, 30d, all): fees_paid is what traders paid the builder in USDC, before any protocol share, with volume, users and fills. The leaderboard ranks builders by fees_paid over one window (7d by default). Stats lag the fills they count. The server answers 404 for a builder with no recorded stats, and while it has none to serve at all.

client = ParadexApiClient(env="testnet")
client.fetch_builder_stats("0x<builder-account>")["results"]
client.fetch_builder_leaderboard("30d")["results"][0]["rank"]  # 1

Full details for REST API & WebSocket JSON-RPC API can be found at the following links:

paradex_py.api.api_client.ParadexApiClient

Bases: BlockTradesMixin, HttpClient

Class to interact with Paradex REST API. Initialized along with Paradex class.

After any REST call, rate limit info from the last response is available as :attr:last_rate_limit (limit, remaining, reset, window from x-ratelimit-* headers). Use it to back off before hitting 429 or to wait after one.

Parameters:

Name Type Description Default
env Environment

Environment

required
logger Logger

Logger. Defaults to None.

None
http_client HttpClient

Custom HTTP client for injection. Defaults to None.

None
api_base_url str

Custom base URL override. Defaults to None.

None
auto_auth bool

Whether to automatically handle onboarding/auth. Defaults to True.

True
auth_provider AuthProvider

Custom authentication provider. Defaults to None.

None
signer Signer

Custom order signer for submit/modify/batch operations. Defaults to None.

None
on_token_expired Callable[[], str | None]

Called when a manually-injected token (set via set_token()) expires. Expiry is detected from the JWT exp claim when present; falls back to a 4-minute window for opaque tokens. Should return a fresh token string, or None if unavailable. Only meaningful when auto_auth=False. Defaults to None.

None
auth_params dict

Extra query parameters sent with every /auth request (initial and refresh). For example, {"token_usage": "interactive"} to obtain a 0-fee JWT token. Defaults to None.

None

Examples:

>>> from paradex_py import Paradex
>>> from paradex_py.environment import Environment
>>> paradex = Paradex(env=Environment.TESTNET)

activate_subkey(payload)

Activate a pending subkey via Starknet signature. Private endpoint requires authorization.

The signature must be [r, s] over pedersen(timestamp, eph_public_key), produced by the main account's Starknet key.

Parameters:

Name Type Description Default
payload dict

ActivateSubkey fields — account_id, public_key, timestamp, signature, name.

required

Returns:

Type Description
dict

ActivateSubkeyResponse dict (may include encrypted_key)

auth_evm(params=None)

Obtain a JWT for an EVM account via POST /v2/auth (SIWE).

cancel_algo_order(algo_order_id)

Cancel an algo order. Private endpoint requires authorization.

Parameters:

Name Type Description Default
algo_order_id str

Algo order ID

required

cancel_all_orders(params=None)

Cancel all open orders for specific market or for all markets. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

market: Market Name

None

cancel_order(order_id)

Cancel open order previously sent to Paradex from this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
order_id str

Order Id

required

cancel_order_by_client_id(client_id)

Cancel open order previously sent to Paradex from this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
client_id str

Order id as assigned by a trader.

required

cancel_orders_batch(order_ids=None, client_order_ids=None)

Cancel batch of orders by order IDs or client order IDs. Private endpoint requires authorization.

Parameters:

Name Type Description Default
order_ids list[str] | None

List of order IDs assigned by Paradex

None
client_order_ids list[str] | None

List of client-assigned order IDs

None

Returns:

Name Type Description
results list

List of cancellation results for each order

create_evm_subaccount()

Create the next sub-account of the logged-in EVM-owned (EIP-191) main account.

.. warning:: Experimental: this SDK API may still change. Paradex enables EVM sub-accounts per account; until it does, the server answers 403 REQUEST_NOT_ALLOWED.

POST /v2/account/subaccounts. Needs the owner's own login (ParadexEvm's SIWE JWT); a session or subkey JWT is refused. The server picks the index and derives the address. A session that should trade the new sub-account needs a new grant listing it.

Returns:

Type Description
dict

dict with the new sub-account's address and index.

create_subkey(payload)

Register a new subkey for this account. Private endpoint requires authorization.

The server requires the main key's approval of the new subkey: siwe_message and evm_signature for an EIP-191 (EVM) account, which EvmAccount.subkey_registration_fields builds, or signature, signature_timestamp and signature_expiry for a Starknet account.

Parameters:

Name Type Description Default
payload dict

CreateSubkey fields — name, public_key, state ('active' or 'pending'), encrypted_key and eph_public_key (required when state='pending'), and the main key's approval above.

required

Returns:

Type Description
None

None (the server responds with 201 and no body on success)

create_token(payload)

Create a new authentication token (JWT or API key). Private endpoint requires authorization.

Parameters:

Name Type Description Default
payload dict

CreateToken fields — name, token_type, expiry_duration (seconds).

required

Returns:

Type Description
dict

ApiToken response dict

delete_mmp_config(base_asset)

Remove the Market Maker Protection config for a base asset, turning MMP off for it. Succeeds when there is no config. Private endpoint requires authorization.

Stays available when MMP is not enabled for the account, so a config that is still enforced can be removed.

Parameters:

Name Type Description Default
base_asset str

Base asset of the config to remove, e.g. "BTC".

required

fetch_account_info()

Fetch profile for this account. Private endpoint requires authorization.

fetch_account_profile()

Fetch profile for this account. Private endpoint requires authorization.

fetch_account_summary()

Fetch current summary for this account. Private endpoint requires authorization.

fetch_algo_orders(params=None)

Fetch algo orders for the account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

market: Market name

status: Algo order status

None

Returns:

Name Type Description
results list

List of algo orders

fetch_balances()

Fetch all coin balances for this account. Private endpoint requires authorization.

Returns:

Name Type Description
results list

List of Balances

fetch_bbo(market)

Fetch best bid/offer for specific market.

Parameters:

Name Type Description Default
market str

Market Name

required

fetch_builder_approvals(include_inactive=False)

List the builders the logged-in account has approved (Builder Codes).

.. warning:: Experimental: this SDK API may still change.

GET /v2/builders/approvals. Needs the account owner's main-key login; a session or subkey JWT is refused, and so is an account Paradex has not enabled sessions for (403). Live approvals are listed newest first.

Parameters:

Name Type Description Default
include_inactive bool

Also list revoked and expired approvals, for the approval history.

False

Returns:

Type Description
dict

dict with results: a list of approvals, each with builder (account, name),

dict

status (active, revoked or expired), max_fee_rate, and expires_at,

dict

approved_at and revoked_at in milliseconds (revoked_at is 0 while not revoked).

fetch_builder_leaderboard(window=None)

Fetch builders ranked by the builder fees traders paid them. Public endpoint.

.. warning:: Experimental: this SDK API may still change.

GET /v1/builders/leaderboard, ranked by fees_paid and then by volume. The server answers 404 while it has no stats to serve.

Parameters:

Name Type Description Default
window str | None

24h, 7d, 30d or all; the server's default is 7d, and it answers 400 for any other value.

None

Returns:

Type Description
dict

dict with results: rows as :meth:fetch_builder_stats returns them, each with a

dict

rank (1 for the builder paid the most).

fetch_builder_stats(builder_account)

Fetch a builder's Builder Codes stats. Public endpoint.

.. warning:: Experimental: this SDK API may still change.

GET /v1/builders/{builder_account}/stats: one row per window (24h, 7d, 30d, all). fees_paid is what traders paid the builder in USDC, before any protocol share. A window with no paid fill, or with too few paying users, is zeros, and stats lag the fills they count. The server answers 404 for a builder it has no stats for (none recorded yet), and while it has no stats to serve at all.

Parameters:

Name Type Description Default
builder_account str

The builder's account address.

required

Returns:

Type Description
dict

dict with results: rows with builder (account, name), window,

dict

fees_paid, volume, users, fills and as_of (milliseconds).

fetch_evm_subaccounts(eth_address)

List the sub-accounts of the EVM-owned (EIP-191) main account of a wallet.

.. warning:: Experimental: this SDK API may still change.

GET /v2/onboarding/subaccounts. Public endpoint, no authentication required, so a client can list these sub-accounts in a session grant before it holds a JWT. Sub-accounts the owner archived are left out, and a wallet with no Paradex account has none.

Parameters:

Name Type Description Default
eth_address str

The owner wallet's Ethereum address.

required

Returns:

Type Description
dict

dict with results: a list of {"address", "index"}, lowest index first.

fetch_fills(params=None)

Fetch history of fills for this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

cursor: Returns the next paginated page

end_at: End Time (unix time millisecond)

market: Market for the fills

page_size: Limit the number of responses in the page

start_at: Start Time (unix time millisecond)

None

Returns:

Name Type Description
next str

The pointer to fetch next set of records (null if there are no records left)

prev str

The pointer to fetch previous set of records (null if there are no records left)

results list

List of Fills

fetch_funding_data(params=None)

List historical funding data by market

Parameters:

Name Type Description Default
params dict | None

cursor: Returns the next paginated page

end_at: End Time (unix time millisecond)

market: Market for which funding payments are queried

page_size: Limit the number of responses in the page

start_at: Start Time (unix time millisecond)

None

Returns:

Name Type Description
next str

The pointer to fetch next set of records (null if there are no records left)

prev str

The pointer to fetch previous set of records (null if there are no records left)

results list

List of Funding Payments

fetch_funding_payments(params=None)

Fetch history of funding payments for this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

cursor: Returns the next paginated page

end_at: End Time (unix time millisecond)

market: Market for which funding payments are queried

page_size: Limit the number of responses in the page

start_at: Start Time (unix time millisecond)

None

Returns:

Name Type Description
next str

The pointer to fetch next set of records (null if there are no records left)

prev str

The pointer to fetch previous set of records (null if there are no records left)

results list

List of Funding Payments

fetch_insurance_fund()

Fetch insurance fund information

fetch_klines(symbol, resolution, start_at, end_at, price_kind=None)

Fetch OHLCV candlestick data for a symbol.

Parameters:

Name Type Description Default
symbol str

Symbol of the market pair

required
resolution str

Resolution in minutes: 1, 3, 5, 15, 30, 60

required
start_at int

Start time for klines in milliseconds

required
end_at int

End time for klines in milliseconds

required
price_kind str | None

Which price to use for the klines (optional)

None

Returns:

Type Description
dict

List of OHLCV candlestick data

fetch_liquidations(params=None)

Fetch history of liquidations for this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

start (int): start time in milliseconds since epoch. end (int): end time in milliseconds since epoch.

None

Returns:

Name Type Description
results list

List of Liquidations

fetch_markets(params=None)

Fetch all markets information.

Parameters:

Name Type Description Default
params dict | None

market: Market Name

None

Returns:

Name Type Description
results list

List of Markets

fetch_markets_summary(params=None)

Fetch ticker information for specific market.

Parameters:

Name Type Description Default
params dict | None

end: End Time (unix time millisecond)

market: Name of the market for which summary is requested (for all available markets use ALL)

start: Start Time (unix time millisecond)

None

Returns:

Name Type Description
results list

List of Market Summaries

fetch_mmp_configs(params=None)

Fetch Market Maker Protection configs for this account, one per base asset. Private endpoint requires authorization.

Available whether or not MMP is enabled for the account: when enabled is False the configs listed are still enforced, and can only be removed.

Parameters:

Name Type Description Default
params dict | None

base_asset: Only return the config for this base asset

None

Returns:

Type Description
AccountMmpConfigs

AccountMmpConfigs with account, enabled and results

fetch_onboarding(params=None)

Check whether an account has been onboarded.

Public endpoint — no authentication required.

Parameters:

Name Type Description Default
params dict | None

Query parameters. One of the following forms:

Starknet account (account_signer_type="starknet")::

{"account_signer_type": "starknet", "public_key": "0x<l2_pubkey>"}

EVM account (account_signer_type="eip191")::

{"account_signer_type": "eip191", "eth_address": "0x<evm_address>"}

Note: public_key is ignored by the server for EIP-191 accounts.

EIP-191 accounts additionally accept vault_operator_index (int) to resolve the address and existence of the N-th EVM vault operator sub-account of that eth key's main account (0-based; requires the server's EVM vault operators feature flag)::

{"account_signer_type": "eip191", "eth_address": "0x<evm_address>",
 "vault_operator_index": 0}
None

Returns:

Type Description
dict

dict with address, exists (bool), account_signer_type, and

dict

derivation_info.

fetch_order(order_id)

Fetch a state of specific order sent from this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
order_id str

order's id as assigned by Paradex.

required

fetch_order_by_client_id(client_id)

Fetch a state of specific order sent from this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
client_id str

order's client_id as assigned by a trader.

required

fetch_orderbook(market, params=None)

Fetch order-book for specific market.

Parameters:

Name Type Description Default
market str

Market Name

required
params dict | None

depth: Depth

None

fetch_orders(params=None)

Fetch open orders for the account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

market: Market for the order

None

Returns:

Name Type Description
results list

Orders list

fetch_orders_history(params=None)

Fetch history of orders for the account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

client_id: Unique ID of client generating the order

cursor: Returns the next paginated page

end_at: End Time (unix time millisecond)

market: Market for the order

page_size: Limit the number of responses in the page

side: Order side

start_at: Start Time (unix time millisecond)

status: Order status

type: Order type

None

Returns:

Name Type Description
next str

The pointer to fetch next set of records (null if there are no records left)

prev str

The pointer to fetch previous set of records (null if there are no records left)

results list

List of Orders

fetch_points_data(market, program)

Fetch points program data for specific market. Private endpoint requires authorization.

Parameters:

Name Type Description Default
market str

Market Name

required
program str

Program Name - example: Maker, Fee

required

Returns:

Name Type Description
results list

List of points data

fetch_portfolio_margin_config(params=None)

Fetch Portfolio Margin configuration (per underlying).

The response is the input expected by :func:paradex_py.margin.compute when margin_methodology="portfolio_margin" — it contains the live scenario set, vol-shock parameters, and hedged/unhedged margin factors that the engine refuses to default locally.

Examples:

>>> paradex.api_client.fetch_portfolio_margin_config()
>>> { "results": [{"base_asset": "BTC", "scenarios": [...], ...}] }

Returns:

Name Type Description
results list

One entry per underlying.

fetch_positions()

Fetch all derivatives positions for this account. Private endpoint requires authorization.

Returns:

Name Type Description
next str

The pointer to fetch next set of records (null if there are no records left)

prev str

The pointer to fetch previous set of records (null if there are no records left)

results list

List of Positions

fetch_subaccounts()

Fetch list of sub-accounts for this account. Private endpoint requires authorization.

fetch_subkey(public_key)

Fetch a specific subkey by its public key. Private endpoint requires authorization.

Parameters:

Name Type Description Default
public_key str

Public key of the subkey to fetch.

required

fetch_subkeys(params=None)

List all subkeys for this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

include_revoked: Include revoked subkeys in results

None

Returns:

Name Type Description
results list

List of Subkeys

fetch_system_config()

Fetch Paradex system config.

Examples:

>>> paradex.api_client.fetch_system_config()
>>> { ..., "paraclear_decimals": 8, ... }

fetch_system_state()

Fetch Paradex system status.

Examples:

>>> paradex.api_client.fetch_system_state()
>>> { "status": "ok" }

fetch_system_time()

Fetch Paradex system time.

Examples:

>>> paradex.api_client.fetch_system_time()
>>> { "server_time": "1710956478221" }

Returns:

Name Type Description
server_time dict

Paradex Server time

fetch_tokens(params=None)

List authentication tokens for this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

kind: Filter by token kind ('jwt' or 'api_key')

None

Returns:

Name Type Description
results list

List of ApiToken entries

fetch_tradebusts(params=None)

Fetch history of tradebusts for this account.

Parameters:

Name Type Description Default
params dict | None

cursor: Returns the next paginated page

end_at: End Time (unix time millisecond)

page_size: Limit the number of responses in the page

start_at: Start Time (unix time millisecond)

None

Returns:

Name Type Description
next str

The pointer to fetch next set of records (null if there are no records left)

prev str

The pointer to fetch previous set of records (null if there are no records left)

results list

List of Tradebusts

fetch_trades(params)

Fetch Paradex exchange trades for specific market.

Parameters:

Name Type Description Default
params dict

market: Market Name

required

Returns:

Name Type Description
next str

The pointer to fetch next set of records (null if there are no records left)

prev str

The pointer to fetch previous set of records (null if there are no records left)

results list

List of Trades

fetch_transactions(params=None)

Fetch history of transactions initiated by this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

cursor: Returns the next paginated page

end_at: End Time (unix time millisecond)

page_size: Limit the number of responses in the page

start_at: Start Time (unix time millisecond)

None

Returns:

Name Type Description
next str

The pointer to fetch next set of records (null if there are no records left)

prev str

The pointer to fetch previous set of records (null if there are no records left)

results list

List of Transactions

fetch_transfers(params=None)

Fetch history of transfers initiated by this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
params dict | None

cursor: Returns the next paginated page

end_at: End Time (unix time millisecond)

page_size: Limit the number of responses in the page

start_at: Start Time (unix time millisecond)

status: none

None

Returns:

Name Type Description
next str

The pointer to fetch next set of records (null if there are no records left)

prev str

The pointer to fetch previous set of records (null if there are no records left)

results list

List of Transfers

init_account_evm(account)

Initialize an EVM account and run the v2 onboarding/auth flow.

modify_order(order_id, order, signer=None)

Modify an open order previously sent to Paradex from this account. Private endpoint requires authorization.

Parameters:

Name Type Description Default
order_id str

Order Id

required
order Order

Order update

required
signer Signer | None

Optional custom signer. Uses instance signer or account signer if None.

None

onboarding_evm()

Onboard an EVM account via POST /v2/onboarding (SIWE).

reset_mmp(base_asset=None)

Clear a Market Maker Protection freeze and its window. Private endpoint requires authorization.

The only way to lift a freeze without deleting the config, and the only way out of one configured with frozen_time_ms=0.

A reset within the first second of a freeze is refused with 400 MMP_MIN_FREEZE_NOT_ELAPSED, so the cancel sweep can catch up. When no base asset is given, that refusal is partial: the server names the base assets it refused and those it reset anyway. A failure here therefore does not mean nothing was reset, and retrying the whole reset spends the per-account reset limit on base assets already cleared. Those lists are only readable as text today, in the raised ValueError, because every non-2xx raises ValueError(str(ApiError)); reading them as data waits on a typed API error.

Parameters:

Name Type Description Default
base_asset str | None

Base asset to reset, e.g. "BTC". Every base asset with MMP enabled when omitted. An empty string is rejected rather than treated as omitted, since resetting every base asset is rarely what an unset variable was meant to do.

None

Returns:

Type Description
AccountMmpReset

AccountMmpReset with results, one entry per base asset reset

revoke_builder_approval(builder_account)

Revoke the logged-in account's approval of a builder (Builder Codes).

.. warning:: Experimental: this SDK API may still change.

DELETE /v2/builders/approvals/{builder_account}. Needs the account owner's main-key login. New orders naming the builder are refused at once, on the account and its sub-accounts, and the resting orders naming it on them are cancelled. The server answers 404 when the account has no live approval of the builder.

Parameters:

Name Type Description Default
builder_account str

The builder's account address.

required

revoke_subkey(public_key)

Revoke a subkey permanently. Private endpoint requires authorization.

Parameters:

Name Type Description Default
public_key str

Public key of the subkey to revoke.

required

revoke_token(lookup_id)

Revoke an authentication token by its lookup ID. Private endpoint requires authorization.

Parameters:

Name Type Description Default
lookup_id str

Lookup ID of the token to revoke.

required

set_mmp_config(base_asset, interval_ms, frozen_time_ms, size_limit=None, delta_limit=None, vega_limit=None, protect_block_trades=None)

Replace the Market Maker Protection config for a base asset. Private endpoint requires authorization.

This is a full replacement, not a patch: an omitted limit is sent as 0, which disables that check. At least one limit must be greater than 0. The base asset must have dated option or perpetual markets, and MMP must be enabled for the account (otherwise the server answers 403 MMP_NOT_ENABLED). Use delete_mmp_config to turn MMP off for a base asset; there is no interval that removes a config.

Parameters:

Name Type Description Default
base_asset str

Base asset the config applies to, e.g. "BTC". It covers every dated option and the perpetual on that asset.

required
interval_ms int

Sliding window length in milliseconds, between MMP_MIN_INTERVAL_MS and MMP_MAX_INTERVAL_MS.

required
frozen_time_ms int

How long a trip freezes MMP orders, in milliseconds, between MMP_MIN_FROZEN_TIME_MS and MMP_MAX_FROZEN_TIME_MS. 0 does not mean "no freeze": it freezes until reset_mmp is called.

required
size_limit Decimal | str | int | None

Trips when the sum of fill sizes in the window exceeds it, in base asset units. 0 disables it.

None
delta_limit Decimal | str | int | None

Trips when the absolute net delta of fills in the window exceeds it, in base asset units. 0 disables it.

None
vega_limit Decimal | str | int | None

Trips when the absolute net vega of fills in the window exceeds it, in USD. 0 disables it. It counts dated option fills only, so it cannot be the only limit on a base asset with no dated option markets.

None
protect_block_trades bool | None

Opt this base asset's block trade legs, RFQ executions included, into MMP -- only the legs where the account is the maker. Unlike the limits, this is not replaced when omitted: leaving it None keeps whatever is stored, and only sending False turns protection off. The flag is stamped when a block trade is created, so turning it off applies to blocks created afterwards.

None

Every limit must be a multiple of MMP_LIMIT_MIN_INCREMENT (0.0001).

Returns:

Type Description
MmpConfig

MmpConfig as stored

set_token(jwt)

Inject a JWT token directly, bypassing the standard onboarding/auth flow.

Used by ParadexApiKey to supply a pre-generated token, and also useful for testing/simulation scenarios.

Parameters:

Name Type Description Default
jwt str

JWT token string

required

submit_algo_order(order, algo_type, duration_seconds, frequency=None, signer=None)

Submit an algo order (e.g. TWAP) to Paradex. Private endpoint requires authorization.

Parameters:

Name Type Description Default
order Order

Order with type=MARKET, price=0, containing market/side/size, and no builder.

required
algo_type str

Algo type (e.g. "TWAP").

required
duration_seconds int

Duration in seconds (30-86400, multiple of 30).

required
frequency int | None

Interval in seconds between child orders (default: 30).

None
signer Signer | None

Optional custom signer. Uses instance signer or account signer if None.

None

Returns:

Type Description
dict

Algo order response dict.

submit_order(order, signer=None)

Send order to Paradex. Private endpoint requires authorization.

Parameters:

Name Type Description Default
order Order

Order containing all required fields.

required
signer Signer | None

Optional custom signer. Uses instance signer or account signer if None.

None

submit_orders_batch(orders, signer=None)

Send batch of orders to Paradex. Private endpoint requires authorization.

Parameters:

Name Type Description Default
orders list[Order]

List of orders containing all required fields.

required
signer Signer | None

Optional custom signer. Uses instance signer or account signer if None.

None

Returns:

Name Type Description
orders list

List of Orders

errors list

List of Errors

update_subkey(public_key, payload)

Update a subkey (e.g. rename it). Private endpoint requires authorization.

Parameters:

Name Type Description Default
public_key str

Public key of the subkey to update.

required
payload dict

UpdateSubkey fields — name.

required

update_subkey_allowed_cidrs(public_key, allowed_cidrs)

Replace the IP CIDR allowlist for a subkey. Private endpoint requires authorization.

Only callable with the main account; subkeys cannot widen their own allowlist. Pass an empty list to clear the allowlist (unrestricted).

Parameters:

Name Type Description Default
public_key str

Public key of the subkey to update.

required
allowed_cidrs list[str]

Full replacement list of CIDR strings (e.g. ["203.0.113.0/24", "198.51.100.42/32"]).

required

Returns:

Type Description
dict

Updated Subkey dict.

paradex_py.api.ws_client.ParadexWebsocketChannel

Bases: Enum

Enum class to define the channels for Paradex Websocket API.

Attributes:

Name Type Description
ACCOUNT str

Private websocket channel for receiving updates of account status

BALANCE_EVENTS str

Private websocket channel to receive PnL calculation data

BBO str

Public websocket channel for tick updates of orderbook best bid/ask prices and amounts

BLOCK_TRADES str

Private websocket channel to receive block trade updates

FILLS str

Private websocket channel to receive details of fills for specific account

FUNDING_DATA str

Public websocket channel to receive funding data updates

FUNDING_PAYMENTS str

Private websocket channel to receive funding payments of an account

FUNDING_RATE_COMPARISON str

Public websocket channel for hourly funding rates across venues

MARKETS_SUMMARY str

Public websocket channel for updates of available markets

MMP str

Private websocket channel for Market Maker Protection state changes on the account

ORDERS str

Private websocket channel to receive order updates

ORDER_BOOK str

Public websocket channel for the orderbook. The default feed_type "snapshot" sends snapshots every refresh_rate (50ms or 100ms, default 100ms), optionally grouped by price_tick (production only; 0.1, "0.1" and "0_1" all mean a 0.1 tick). feed_type "interactive" does the same with a refresh_rate of 100ms, 200ms or 400ms (default 100ms). feed_type "deltas" sends incremental updates and "interactive_deltas" is its interactive counterpart; neither takes a refresh_rate or price_tick. Both interactive feeds include RPI orders. One SBE session carries at most one orderbook feed per market

POSITIONS str

Private websocket channel to receive updates when position is changed

TRADES str

Public websocket channel to receive updates on trades in particular market

TRADEBUSTS str

Private websocket channel to receive fills that are busted by a blockchain

TRANSACTIONS str

Private websocket channel for receiving transaction details of fills

TRANSFERS str

Websocket channel for receiving transfer updates

paradex_py.api.ws_client.WsRpcError

Bases: Exception

Raised when a WebSocket JSON-RPC response contains an error.

paradex_py.api.ws_client.ParadexWebsocketClient

Class to interact with Paradex WebSocket JSON-RPC API. Initialized along with Paradex class.

Parameters:

Name Type Description Default
env Environment

Environment

required
logger Optional[Logger]

Logger. Defaults to None.

None
ws_timeout Optional[int]

WebSocket read timeout in seconds. Defaults to 20s.

None
auto_start_reader bool

Whether to automatically start the message reader. Defaults to True.

True
connector Optional[WebSocketConnector]

Custom WebSocket connector for injection. Defaults to None.

None
ws_url_override Optional[str]

Custom WebSocket URL override. Defaults to None.

None
reader_sleep_on_error float

Sleep duration after connection errors. Set to 0 for no sleep. Defaults to 1.0.

1.0
reader_sleep_on_no_connection float

Sleep duration when no connection. Set to 0 for no sleep. Defaults to 1.0.

1.0
validate_messages bool

Enable pydantic message validation. Requires pydantic. Defaults to False. Applies to JSON text frames only; SBE frames are already decoded into pydantic models. An SBE connection still carries JSON frames for channels the server does not encode in SBE, such as balance_events and transfers, and for private channels on accounts not yet served SBE.

False
ping_interval float

WebSocket ping interval in seconds. None uses websockets default. Defaults to None.

None
disable_reconnect bool

Disable automatic reconnection for tight simulation control. Defaults to False.

False
enable_compression bool

Enable WebSocket per-message compression (RFC 7692). Defaults to True.

True
api_client Optional[Any]

Reference to ParadexApiClient for token refresh. Defaults to None.

None
direct bool

Connect to the direct WebSocket endpoint (ws.api.{env}.paradex.trade) instead of the default public one (ws-public.api.{env}.paradex.trade). Ignored when ws_url_override is provided. Defaults to False.

False
sbe_enabled bool

Negotiate SBE binary encoding on connect. Defaults to True: the Paradex WebSocket endpoints require it and answer a plain JSON connect with HTTP 400. Pass False only for an endpoint (e.g. a ws_url_override) that still serves JSON. Public market data always arrives as SBE. Private channels (orders, fills, positions, account) arrive as SBE or JSON depending on the account, on the same connection, and the two use different field names (e.g. order_id vs id). Every message passed to a callback carries message["encoding"], "sbe" or "json", so a callback can tell which shape it got.

True

Examples:

>>> from paradex_py import Paradex
>>> from paradex_py.environment import Environment
>>> paradex = Paradex(env=Environment.TESTNET)
>>> paradex.ws_client.connect()
>>> # With custom timeout
>>> from paradex_py.api.ws_client import ParadexWebsocketClient
>>> ws_client = ParadexWebsocketClient(env=Environment.TESTNET, ws_timeout=30)
>>> # With manual pumping disabled
>>> ws_client = ParadexWebsocketClient(env=Environment.TESTNET, auto_start_reader=False)
>>> # High-frequency simulator mode (no sleeps)
>>> ws_client = ParadexWebsocketClient(env=Environment.TESTNET,
...                                   reader_sleep_on_error=0, reader_sleep_on_no_connection=0)
>>> # With typed message validation (JSON text frames only)
>>> ws_client = ParadexWebsocketClient(env=Environment.TESTNET, validate_messages=True)
>>> # With API client for automatic token refresh on reconnect
>>> from paradex_py import Paradex
>>> paradex = Paradex(env=Environment.TESTNET, l1_address="0x...", l1_private_key="0x...")
>>> # WebSocket client automatically refreshes expired tokens when reconnecting

cancel_all_orders(market=None) async

Cancel all open orders over WebSocket (order.cancel_all).

Mirrors :meth:paradex_py.api.api_client.ParadexApiClient.cancel_all_orders.

Parameters:

Name Type Description Default
market str | None

If provided, cancel only orders in this market.

None

Returns:

Type Description
dict

Server result dict containing status.

Raises:

Type Description
WsRpcError

On server-side error.

cancel_on_disconnect(enabled) async

Toggle Cancel-on-Disconnect for this WebSocket session (order.cancel_on_disconnect).

Off by default. Each new WebSocket session starts with CoD disabled. Call cancel_on_disconnect(True) after connecting and authenticating to arm it for the session.

When enabled, the server automatically cancels all orders that were submitted via this session if the WebSocket connection drops. The tracking set is managed entirely server-side and is scoped to the current connection — it resets on every reconnect, so re-enable CoD after each reconnect if needed.

Parameters:

Name Type Description Default
enabled bool

True to enable CoD, False to disable.

required

Returns:

Type Description
dict

Server result dict containing enabled confirming the new state.

Raises:

Type Description
WsRpcError

If the server rejects the request.

Examples:

>>> async def main():
...     paradex = Paradex(env=TESTNET, l1_address="0x...", l1_private_key="0x...")
...     await paradex.ws_client.connect()
...     # Arm cancel-on-disconnect for this session
...     await paradex.ws_client.cancel_on_disconnect(True)
...     # Orders submitted now will be cancelled if the connection drops
...     order = Order(market="BTC-USD-PERP", ...)
...     result = await paradex.ws_client.submit_order(order)
...     # Disable CoD when no longer needed
...     await paradex.ws_client.cancel_on_disconnect(False)

cancel_order(order_id) async

Cancel an order by ID over WebSocket (order.cancel).

Mirrors :meth:paradex_py.api.api_client.ParadexApiClient.cancel_order.

Parameters:

Name Type Description Default
order_id str

Paradex-assigned order ID.

required

Returns:

Type Description
dict

Server result dict containing order_id and status.

Raises:

Type Description
WsRpcError

If the order cannot be cancelled.

cancel_order_by_client_id(client_id, market) async

Cancel an order by client ID over WebSocket (order.cancel).

Mirrors :meth:paradex_py.api.api_client.ParadexApiClient.cancel_order_by_client_id.

Parameters:

Name Type Description Default
client_id str

Trader-assigned client order ID.

required
market str

Market the order belongs to (required by the server).

required

Returns:

Type Description
dict

Server result dict containing order_id and status.

Raises:

Type Description
WsRpcError

If the order cannot be cancelled.

cancel_orders_batch(order_ids) async

Cancel a batch of orders by ID over WebSocket (order.cancel_batch).

Mirrors :meth:paradex_py.api.api_client.ParadexApiClient.cancel_orders_batch.

Parameters:

Name Type Description Default
order_ids list[str]

List of Paradex-assigned order IDs to cancel.

required

Returns:

Type Description
dict

Server result dict containing per-order cancellation outcomes.

Raises:

Type Description
WsRpcError

On server-side error.

close() async

Close the WebSocket connection and clean up resources.

This method should be called when done using the WebSocket client to properly clean up connections and background tasks.

Examples:

>>> import asyncio
>>> from paradex_py.api.ws_client import ParadexWebsocketClient
>>> from paradex_py.environment import Environment
>>> async def main():
...     ws_client = ParadexWebsocketClient(env=Environment.TESTNET)
...     try:
...         await ws_client.connect()
...         # Use websocket client
...     finally:
...         await ws_client.close()
>>> asyncio.run(main())

connect() async

Connect to Paradex WebSocket API.

Returns:

Name Type Description
bool bool

True if connection is successful.

Examples:

>>> from paradex_py import Paradex
>>> from paradex_py.environment import TESTNET
>>> async def main():
...     paradex = Paradex(env=TESTNET)
...     await paradex.ws_client.connect()
>>> import asyncio
>>> asyncio.run(main())

get_subscriptions()

Get current subscription map.

Returns:

Type Description
dict[str, bool]

Dictionary mapping channel names to subscription status

inject(message) async

Inject a raw message string into the message processing pipeline.

Parameters:

Name Type Description Default
message str

Raw JSON string to process as if received from WebSocket.

required

modify_order(order_id, order, signer=None) async

Modify an open order over WebSocket (order.modify).

Mirrors :meth:paradex_py.api.api_client.ParadexApiClient.modify_order.

Parameters:

Name Type Description Default
order_id str

ID of the order to modify.

required
order Order

Order object carrying the updated fields and a fresh signature.

required
signer Signer | None

Optional custom signer. Falls back to the account signer.

None

Returns:

Type Description
dict

Server result dict containing the updated order.

Raises:

Type Description
WsRpcError

If the server rejects the modification.

pump_once() async

Manually pump one message from the WebSocket connection.

Returns:

Name Type Description
bool bool

True if a message was processed, False if no message available or connection closed.

pump_until(predicate, timeout_s=10.0) async

Deterministic consumption helper for simulators.

Pumps messages until predicate returns True or timeout is reached. Useful for waiting for specific message conditions in tests.

Parameters:

Name Type Description Default
predicate Callable[[dict], bool]

Function that takes a message dict and returns True to stop

required
timeout_s float

Maximum time to wait in seconds

10.0

Returns:

Type Description
int

Number of messages processed before predicate was satisfied or timeout

Examples:

Wait for BBO message with specific price

count = await ws_client.pump_until( lambda msg: msg.get('params', {}).get('channel', '').startswith('bbo') and float(msg.get('data', {}).get('bid', 0)) > 50000, timeout_s=5.0 )

submit_order(order, signer=None) async

Create an order over WebSocket (order.create).

Mirrors :meth:paradex_py.api.api_client.ParadexApiClient.submit_order. The connection must be authenticated before calling this method.

Parameters:

Name Type Description Default
order Order

Order to submit.

required
signer Signer | None

Optional custom signer. Falls back to the account signer.

None

Returns:

Type Description
dict

Server result dict containing order, created_at, received_at.

Raises:

Type Description
WsRpcError

If the server rejects the order.

submit_orders_batch(orders, signer=None) async

Create a batch of orders over WebSocket (order.create_batch).

Parameters:

Name Type Description Default
orders list[Order]

Orders to submit.

required
signer Signer | None

Optional custom signer. Falls back to the account signer.

None

Returns:

Type Description
dict

Server result dict containing per-order outcomes.

Raises:

Type Description
WsRpcError

If the server rejects the batch.

subscribe(channel, callback, params=None) async

Subscribe to a websocket channel with optional parameters. Callback function is invoked when a message is received.

Parameters:

Name Type Description Default
channel ParadexWebsocketChannel

Channel to subscribe

required
callback Callable

Callback function

required
params Optional[dict]

Parameters for the channel. Defaults to None.

None

Returns:

Name Type Description
str str

The channel name subscribed to, which can differ from the params (a 0.1 price_tick is sent as 0_1). Pass it to unsubscribe_by_name.

Examples:

from paradex_py import Paradex from paradex_py.environment import TESTNET from paradex_py.api.ws_client import ParadexWebsocketChannel, ParadexWebsocketClient async def main(): ... async def on_message(ws_channel, message): ... print(ws_channel, message) ... paradex = Paradex(env=TESTNET) ... await paradex.ws_client.connect() ... await paradex.ws_client.subscribe(ParadexWebsocketChannel.MARKETS_SUMMARY, callback=on_message) import asyncio asyncio.run(main())

subscribe_by_name(channel_name, callback=None) async

Subscribe to a channel by exact name string.

This is useful for simulation tooling where you want to subscribe to channels with exact names without using the enum formatting.

Parameters:

Name Type Description Default
channel_name str

Exact channel name (e.g., "bbo.BTC-USD-PERP")

required
callback Callable | None

Optional callback function. If provided, registers the callback.

None

unsubscribe_by_name(channel_name) async

Unsubscribe from a channel by exact name string.

Symmetric with subscribe_by_name for complete channel lifecycle control.

Parameters:

Name Type Description Default
channel_name str

Exact channel name (e.g., "bbo.BTC-USD-PERP")

required

paradex_py.account.account.ParadexAccount

Class to generate and manage Paradex account. Initialized along with Paradex class.

Parameters:

Name Type Description Default
config SystemConfig

SystemConfig

required
l1_address str

Ethereum address

required
l1_private_key Optional[str]

Ethereum private key. Defaults to None.

None
l2_private_key Optional[str]

Paradex private key. Defaults to None.

None
rpc_version Optional[str]

RPC version (e.g., "v0_9"). If provided, constructs URL as {base_url}/rpc/{rpc_version}. Defaults to None.

None
env Optional[Environment]

Environment, which selects the SIWE domain of the parent link proof sent when onboarding a new account. Without it no proof is sent. Defaults to None.

None

Examples:

>>> from paradex_py import Paradex
>>> from paradex_py.environment import Environment
>>> paradex = Paradex(env=Environment.TESTNET, l1_address="0x...", l1_private_key="0x...")
>>> paradex.account.l2_address
>>> paradex.account.l2_public_key
>>> paradex.account.l2_private_key

build_block_trade_offer_signature(offer)

Sign a BlockTradeOffer and return the full BlockTradeSignature.

For the offerer to attach to a BlockOfferRequest.signature. Auto-populates signer_public_key with the account's signing key (main or active subkey).

build_block_trade_signature(block_trade)

Sign a BlockTrade and return the full BlockTradeSignature ready to attach to a BlockTradeRequest / BlockOfferRequest / BlockExecuteRequest.

Auto-populates signer_public_key with the account's signing key (main account or subkey, depending on which account class instantiated this). The server uses this hint to look up the right pubkey for verification.

Refuses a block with no trade leaves. The trades slice signs as a merkle tree, and an empty one raises "Cannot build Merkle tree from an empty list of leaves" deep inside the typed-data library, naming leaves rather than the block that had none. A block arrives here empty when its response could not be parsed and was reduced to its id, or when every leg lacks both orders and trade constraints. Every caller signs through here, so the check sits here rather than at each of them.

build_executor_signature_for_block(block_response, nonce=None, expiration_minutes=5)

Build the executor-side signature for a DIRECT block trade execute.

Pass the BlockTradeDetailFullResponse returned by get_block_trade(). Returns a dict ready to assign to BlockExecuteRequest.signatures — keyed by block_id with a single entry. The executor (this account) signs the merkle root of the block's trades using a fresh nonce/expiration.

Use this for direct block trades. For offer-based blocks, use build_executor_signatures_for_offers instead.

build_executor_signatures_for_offers(offer_responses, nonce=None, expiration_minutes=5)

Build executor-side signatures for an OFFER-BASED block trade execute.

Pass a list of BlockTradeDetailFullResponse objects (one per offer being accepted, fetched via get_block_trade_offer()). Returns a dict keyed by offer_id with one signature per offer — each commits the executor (this account) to that specific offer's trade fills.

sign_block_offer_request(request, block_trade_id, expiration_minutes=5)

Attach this account's signature to a BlockOfferRequest in place.

block_trade_id is the parent block trade ID (URL path parameter of the API call) and binds the offer signature to that specific parent. The expiration window applies to the offer signature only — the request's offer body has no expiration field of its own.

sign_block_trade(block_trade_data)

Sign a BlockTrade and return the flattened "[r,s]" signature string.

Lower-level entrypoint. Most callers should use build_block_trade_signature which returns a complete BlockTradeSignature with metadata fields populated.

sign_block_trade_offer(offer)

Sign a BlockTradeOffer and return the flattened "[r,s]" signature string.

Lower-level entrypoint. Most callers should use build_block_trade_offer_signature which returns a complete BlockTradeSignature with metadata fields populated.

sign_block_trade_request(request)

Attach this account's signature to a BlockTradeRequest in place.

Reconstructs the signing BlockTrade from request.trades / request.nonce / request.block_expiration, signs it, and inserts the resulting BlockTradeSignature into request.signatures keyed by this account's address. Returns the request (mutated) for chaining.

take_request_headers()

Headers the last signature needs on the request that carries it. A local key needs none.

paradex_py.account.subkey_account.SubkeyAccount

Bases: ParadexAccount

Subkey account for L2-only API authentication (no on-chain operations).

This account type is designed for subkey usage where only L2 credentials are available and no L1 onboarding is required.

Parameters:

Name Type Description Default
config SystemConfig

SystemConfig

required
l2_private_key str

L2 private key (required)

required
l2_address str

L2 address of the main account (required)

required

Examples:

>>> from paradex_py.account.subkey_account import SubkeyAccount
>>> from paradex_py.environment import Environment
>>> account = SubkeyAccount(
...     config=config,
...     l2_private_key="0x...",
...     l2_address="0x..."
... )

onboarding_headers()

Override to prevent onboarding for subkeys.

transfer_on_l2(target_l2_address, amount_decimal)

Override to prevent on-chain operations for subkeys.

Signing with a Key Held Elsewhere

ExternalSignerAccount signs through an ExternalSigner, so the L2 private key never enters this process. HeaderSigner is the signer for a signing proxy that sits between the client and Paradex. For each signed request it sends the message hash, base64-encoded, in a header you name, and puts a stand-in where the signature goes. The proxy signs the hash and swaps in the real signature.

The header carries only the hash. A proxy that needs to know what it is signing has to rebuild the hash from the request body.

from paradex_py.account import ExternalSignerAccount, HeaderSigner
from paradex_py.api.api_client import ParadexApiClient
from paradex_py.environment import TESTNET

client = ParadexApiClient(env=TESTNET, api_base_url="https://your-signing-proxy/v1")
account = ExternalSignerAccount(
    config=client.fetch_system_config(),
    l2_address="0x...",
    l2_public_key="0x...",
    signer=HeaderSigner(header="X-Sign-Hash", signature="PROXY_SIGNATURE"),
)
client.init_account(account)
client.submit_order(order)

The account must already be onboarded, and on-chain operations are not supported.

A signer that returns headers, such as HeaderSigner, has three more limits:

  • It signs REST requests only. A WebSocket order has no headers, so the WebSocket client refuses it.
  • Each request carries one signature. A batch of several orders, or an execute that accepts several offers, is refused before anything is sent.
  • Share one account across threads only if they never sign and send at the same time.

paradex_py.account.external_signer_account.ExternalSignerAccount

Bases: ParadexAccount

An L2 account that signs through an ExternalSigner and holds no private key.

Like a subkey account it is for API use only: no onboarding and no on-chain operations.

A signer that returns headers, such as HeaderSigner, has three more limits. It signs REST requests only, because a WebSocket order has no headers to carry them. Each request carries one signature, so a request needing several is refused. Threads must not share the account, because signing and sending a request must not interleave with another.

Parameters:

Name Type Description Default
config SystemConfig

SystemConfig

required
l2_address str

L2 address of the account

required
l2_public_key str

public key of the key the signer holds

required
signer ExternalSigner

produces the signature for each message hash

required

Examples:

>>> from paradex_py.account import ExternalSignerAccount, HeaderSigner
>>> account = ExternalSignerAccount(
...     config=config,
...     l2_address="0x...",
...     l2_public_key="0x...",
...     signer=HeaderSigner(header="X-Sign-Hash", signature="PROXY_SIGNATURE"),
... )

onboarding_headers()

No onboarding: the account must already exist.

transfer_on_l2(target_l2_address, amount_decimal)

No on-chain operations: the account holds no key to send a transaction.

paradex_py.account.external_signer_account.HeaderSigner

Signer for a signing proxy that sits between this client and Paradex.

Each request carries the 32-byte message hash, base64-encoded, in header, and signature wherever the "[r,s]" string goes. The proxy signs the hash and replaces signature with the real one before forwarding the request.

The header carries only the hash. A proxy that needs to know what it is signing has to rebuild the hash from the request body.

Parameters:

Name Type Description Default
header str

name of the header that carries the message hash

required
signature str

stand-in the proxy replaces with the real signature

required

Examples:

>>> signer = HeaderSigner(header="X-Sign-Hash", signature="PROXY_SIGNATURE")

sign_hash(message_hash)

Return the stand-in signature and the hash header for one request.

Parameters:

Name Type Description Default
message_hash int

typed-data message hash for the account's address

required

Returns:

Name Type Description
ExternalSignature ExternalSignature

the stand-in signature and the header carrying the hash