docs/integrations/bitmex.md
Founded in 2014, BitMEX (Bitcoin Mercantile Exchange) is a cryptocurrency derivatives trading platform offering spot, perpetual contracts, traditional futures, prediction markets, and other advanced trading products. This integration supports live market data ingest and order execution with BitMEX.
This adapter is implemented in Rust, with optional Python bindings for ease of use in Python-based workflows. It does not require external BitMEX client libraries; the core components are compiled as a static library and linked automatically during the build.
You can find live example scripts here.
This guide assumes a trader is setting up for both live market data feeds, and trade execution. The BitMEX adapter includes multiple components, which can be used together or separately depending on the use case.
BitmexHttpClient: Low-level HTTP API connectivity.BitmexWebSocketClient: Low-level WebSocket API connectivity.BitmexInstrumentProvider: Instrument parsing and loading functionality.BitmexDataClient: A market data feed manager.BitmexExecutionClient: An account management and trade execution gateway.BitmexLiveDataClientFactory: Factory for BitMEX data clients (used by the trading node builder).BitmexLiveExecClientFactory: Factory for BitMEX execution clients (used by the trading node builder).:::note Most users will define a configuration for a live trading node (as below), and won't need to necessarily work with these lower level components directly. :::
BitMEX provides extensive documentation for users:
It's recommended you refer to the BitMEX documentation in conjunction with this NautilusTrader integration guide.
| Product Type | Data Feed | Trading | Notes |
|---|---|---|---|
| Spot | ✓ | ✓ | Limited pairs, unified wallet with derivatives. |
| Perpetual Swaps | ✓ | ✓ | Inverse and linear contracts available. |
| Stock Perpetuals | - | - | Not yet supported. Currently on testnet only. |
| Futures | ✓ | ✓ | Traditional fixed expiration contracts. |
| Quanto Futures | ✓ | ✓ | Settled in different currency than underlying. |
| Prediction Markets | ✓ | ✓ | Event‑based contracts, 0-100 pricing, USDT settled. |
| Options | - | - | Not provided by BitMEX. |
:::note BitMEX has discontinued their options products to focus on their core derivatives and spot offerings. :::
BitMEX uses CFI (Classification of Financial Instruments) codes following the ISO 10962 standard. The adapter recognizes the following instrument type codes:
| Code | Type | Status | Description |
|---|---|---|---|
FFWCSX | Perpetual Contract | Supported | Crypto‑based perpetual swaps (e.g., XBTUSD). |
FFWCSF | Perpetual FX | Supported | FX‑based perpetual contracts. |
FFCCSX | Futures | Supported | Calendar futures with fixed expiration. |
FFICSX | Prediction Market | Supported | Event‑based prediction contracts. |
IFXXXP | Spot | Supported | Spot trading pairs. |
FFSCSX | Stock Perpetual | Unsupported | Stock/equity‑based perpetuals. Testnet only. |
SRMCSX | Swap Rate | Unsupported | Yield‑based swap products (historical). |
MR**** | Index | Reference | BitMEX indices (non‑tradeable, for price ref). |
See BitMEX Typ Values for more details.
BitMEX uses a specific naming convention for its trading symbols. Understanding this convention is crucial for correctly identifying and trading instruments.
BitMEX symbols typically follow these patterns:
XBT/USDT, ETH/USDT).XBTUSD, ETHUSD).XBTM24, ETHH25).P_ prefix + Event identifier + Expiry code (e.g., P_POWELLK26, P_FTXZ26).:::info
BitMEX uses XBT as the symbol for Bitcoin instead of BTC. This follows the ISO 4217
currency code standard where "X" denotes non-national currencies. XBT and BTC refer to
the same asset - Bitcoin.
:::
Futures contracts use standard futures month codes:
F = JanuaryG = FebruaryH = MarchJ = AprilK = MayM = JuneN = JulyQ = AugustU = SeptemberV = OctoberX = NovemberZ = DecemberFollowed by the year (e.g., 24 for 2024, 25 for 2025).
Within NautilusTrader, BitMEX instruments are identified using the native BitMEX symbol directly, combined with the venue identifier:
from nautilus_trader.model.identifiers import InstrumentId
# Spot pairs (note: no slash in the symbol)
spot_id = InstrumentId.from_str("XBTUSDT.BITMEX") # XBT/USDT spot
eth_spot_id = InstrumentId.from_str("ETHUSDT.BITMEX") # ETH/USDT spot
# Perpetual contracts
perp_id = InstrumentId.from_str("XBTUSD.BITMEX") # Bitcoin perpetual (inverse)
linear_perp_id = InstrumentId.from_str("ETHUSDT.BITMEX") # Ethereum perpetual (linear)
# Futures contract (June 2024)
futures_id = InstrumentId.from_str("XBTM24.BITMEX") # Bitcoin futures expiring June 2024
# Prediction market contracts
prediction_id = InstrumentId.from_str("P_XBTETFV23.BITMEX") # Bitcoin ETF SEC approval prediction expiring October 2023
:::note
BitMEX spot symbols in NautilusTrader don't include the slash (/) that appears in the
BitMEX UI. Use XBTUSDT instead of XBT/USDT.
:::
BitMEX reports spot and derivative quantities in contract units. The actual asset size per contract is exchange-specific and published on the instrument definition:
lotSize – minimum number of contracts you can trade.underlyingToPositionMultiplier – number of contracts per unit of the underlying asset.For example, the SOL/USDT spot instrument (SOLUSDT) exposes lotSize = 1000 and
underlyingToPositionMultiplier = 10000, meaning one contract represents 1 / 10000 = 0.0001
SOL, and the minimum order (lotSize * contract_size) is 0.1 SOL. The adapter now derives the
contract size directly from these fields and scales both inbound market data and outbound orders
accordingly, so quantities in Nautilus are always expressed in base units (SOL, ETH, etc.).
See the BitMEX API documentation for details on these fields: https://www.bitmex.com/app/apiOverview#Instrument-Properties.
The BitMEX integration supports the following order types and execution features.
| Order Type | Supported | Notes |
|---|---|---|
MARKET | ✓ | Executed immediately at current market price. Quote quantity not supported. |
LIMIT | ✓ | Executed only at specified price or better. |
STOP_MARKET | ✓ | Supported (set trigger_price). |
STOP_LIMIT | ✓ | Supported (set price and trigger_price). |
MARKET_IF_TOUCHED | ✓ | Supported (set trigger_price). |
LIMIT_IF_TOUCHED | ✓ | Supported (set price and trigger_price). |
TRAILING_STOP_MARKET | ✓ | Supported (set trailing_offset). Price offset type only. |
| Instruction | Supported | Notes |
|---|---|---|
post_only | ✓ | Supported via ParticipateDoNotInitiate execution instruction on LIMIT orders. |
reduce_only | ✓ | Supported via ReduceOnly execution instruction. |
:::note
Post-only orders that would cross the spread are canceled by BitMEX rather than rejected. The
integration surfaces these as rejections with due_post_only=True so strategies can handle them
consistently.
:::
BitMEX supports multiple reference prices to evaluate stop/conditional order triggers for:
STOP_MARKETSTOP_LIMITMARKET_IF_TOUCHEDLIMIT_IF_TOUCHEDChoose the trigger type that matches your strategy and/or risk preferences.
| Reference price | Nautilus TriggerType | BitMEX value | Notes |
|---|---|---|---|
| Last trade | LAST_PRICE | LastPrice | BitMEX default; triggers on the last traded price. |
| Mark price | MARK_PRICE | MarkPrice | Recommended for many stop‑loss use cases to reduce stop‑outs from price spikes. |
| Index price | INDEX_PRICE | IndexPrice | Tracks the external index; useful for some contracts. |
trigger_type is provided, BitMEX uses its venue default (LastPrice).Example:
from nautilus_trader.model.enums import TriggerType
order = self.order_factory.stop_market(
instrument_id=instrument_id,
order_side=order_side,
quantity=qty,
trigger_price=trigger,
trigger_type=TriggerType.MARK_PRICE, # Use BitMEX Mark Price as reference
)
ExecTester example configuration also demonstrates setting stop_trigger_type=TriggerType.MARK_PRICE
in examples/live/bitmex/bitmex_exec_tester.py.
BitMEX supports trailing stop orders that automatically adjust the stop price as the market moves
favorably. The adapter maps TRAILING_STOP_MARKET orders to BitMEX's pegged orders with
TrailingStopPeg price type.
Limitations:
PRICE trailing offset type is supported (absolute price offset, not basis points or ticks).Example:
from nautilus_trader.model.enums import TrailingOffsetType
order = self.order_factory.trailing_stop_market(
instrument_id=instrument_id,
order_side=OrderSide.SELL,
quantity=qty,
trailing_offset=Decimal("100"), # $100 trailing offset
trailing_offset_type=TrailingOffsetType.PRICE,
trigger_type=TriggerType.LAST_PRICE, # Optional
)
:::note BitMEX updates trailing stop prices periodically as the market moves. The stop price freezes when the market moves toward the trigger level. See the BitMEX API documentation for current update cadence details. :::
BitMEX supports pegged orders (BBO) that automatically track a reference price. The adapter
supports pegged orders via the params dict on submit_order, which overrides the order type
to Pegged on the exchange side.
| Peg price type | Description |
|---|---|
PrimaryPeg | Pegs to the best bid (buy) or best ask (sell). |
MarketPeg | Pegs to the opposite side (best ask for buy, best bid for sell). |
MidPricePeg | Pegs to the mid‑price between bid and ask. |
LastPeg | Pegs to the last traded price. |
Requirements:
LIMIT order. Other order types are rejected.peg_price_type is required; peg_offset_value is optional (defaults to 0).peg_offset_value can be negative (e.g., sell-side offsets) or fractional.Example:
# Pegged to best bid with zero offset (BBO)
order = self.order_factory.limit(
instrument_id=instrument_id,
order_side=OrderSide.BUY,
quantity=qty,
price=price, # Required for LIMIT order, but overridden by peg
)
self.submit_order(order, params={"peg_price_type": "PrimaryPeg", "peg_offset_value": "0"})
# Pegged to mid-price with a -0.5 offset
self.submit_order(order, params={"peg_price_type": "MidPricePeg", "peg_offset_value": "-0.5"})
:::note
The price field is still required when constructing the LimitOrder, but BitMEX ignores it
for pegged orders and instead continuously tracks the reference price plus offset.
:::
| Time in force | Supported | Notes |
|---|---|---|
GTC | ✓ | Good Till Canceled (default). |
GTD | - | Not supported by BitMEX. |
FOK | ✓ | Fill or Kill - fills entire order or cancels. |
IOC | ✓ | Immediate or Cancel - partial fill allowed. |
DAY | ✓ | Expires at 00:00 UTC (BitMEX trading day boundary). |
:::note
DAY orders expire at 12:00am UTC, which marks the BitMEX trading day boundary (end of trading hours for that day).
See the BitMEX Exchange Rules and API documentation for complete details.
:::
| Feature | Supported | Notes |
|---|---|---|
| Order Modification | ✓ | Modify price, quantity, and trigger price. |
| Bracket Orders | ✓ | Use contingency_type and linked_order_ids. |
| Iceberg Orders | ✓ | Use display_qty. |
| Trailing Stops | ✓ | Use trailing_offset. Price offset type only. |
| Pegged Orders | ✓ | Use params with peg_price_type. See Pegged orders. |
| Operation | Supported | Notes |
|---|---|---|
| Batch Submit | - | Not supported by BitMEX. |
| Batch Modify | - | Not supported by BitMEX. |
| Batch Cancel | ✓ | Cancel multiple orders in a single request. |
| Feature | Supported | Notes |
|---|---|---|
| Query positions | ✓ | REST and real‑time position updates via WebSocket. |
| Cross margin | ✓ | Default margin mode. |
| Isolated margin | ✓ |
| Feature | Supported | Notes |
|---|---|---|
| Query open orders | ✓ | List all active orders. |
| Query order history | ✓ | Historical order data. |
| Order status updates | ✓ | Real‑time order state changes via WebSocket. |
| Trade history | ✓ | Execution and fill reports. |
BitMEX surfaces forced-close fills through the execType field on the
execution channel:
execType | Meaning |
|---|---|
Trade | Normal execution (user or taker‑initiated). |
Liquidation | Position was force‑closed by the liquidation engine. BitMEX uses this code for both auto‑deleveraging and counterparty liquidation fills. |
Bankruptcy | Account bankruptcy; position closed against the insurance fund. |
Settlement | Scheduled contract settlement. |
Funding | Funding settlement on open positions. |
The adapter routes Liquidation and Bankruptcy through the standard
FillReport path and logs a warning on bankruptcy executions. BitMEX's public
API does not distinguish auto-deleveraging from counterparty liquidation
in execType; both appear as Liquidation. An ADL-closed position can
usually be identified by zero commission and the absence of a matching order
in the local cache (the engine creates an external order for it).
Upstream references:
L2_MBP only; depth 0 (full book) or 25.orderBook10 channel.start, end, and limit filters (up to 1,000 results per call).1m, 5m, 1h, 1d) for externally aggregated LAST prices, including optional partial bins.:::note
BitMEX caps each REST response at 1,000 rows and requires manual pagination via start/startTime. The current adapter returns only the
first page; wider pagination support is scheduled for a future update.
:::
Trade ticks and fills use the venue-provided trdMatchID (UUID) as the
TradeId. When the venue omits trdMatchID (bucketed trades or certain
execution types), the execution path falls back to the venue's execID; market
data parsers fall back to a deterministic FNV-1a hash of the symbol,
ts_event, price, size, and side. The same venue event yields the same trade
ID across replays, keeping downstream dedup intact.
The BitMEX adapter uses HTTP keep-alive for optimal performance:
This configuration ensures low-latency communication with BitMEX servers by maintaining persistent connections and avoiding the overhead of establishing new connections for each request.
BitMEX uses an api-expires header for request authentication to prevent replay attacks:
api-expires Unix timestamp set recv_window_ms / 1000 seconds ahead (10 seconds by default).The adapter receives funding rate data from the
Funding
WebSocket stream. BitMEX returns a fundingInterval datetime field in each message,
and the adapter reads the hours and minutes to compute the interval field on
FundingRateUpdate.
BitMEX implements a dual-layer rate limiting system:
The adapter enforces these quotas locally using the configured max_requests_per_second and max_requests_per_minute values.
:::warning Exceeding BitMEX rate limits returns HTTP 429 and may trigger temporary IP bans; persistent 4xx/5xx errors can extend the lockout period. :::
The rate limits can be configured if your account has different limits than the defaults:
| Parameter | Default (authenticated) | Default (unauthenticated) | Description |
|---|---|---|---|
max_requests_per_second | 10 | 10 | Maximum requests per second (burst limit). |
max_requests_per_minute | 120 | 30 | Maximum requests per minute (rolling window). |
:::info For more details on rate limiting, see the BitMEX API documentation on rate limits. :::
:::warning Cancel Broadcaster Rate Limit Considerations
The cancel broadcaster (when canceller_pool_size > 1) fans out each cancel request to multiple independent HTTP clients in parallel. Each client maintains its own rate limiter, which means the effective request rate is multiplied by the pool size.
Example: With canceller_pool_size=3 and max_requests_per_second=10, a single cancel operation consumes 3 requests (one per client), potentially reaching 30 requests/second if canceling rapidly.
Since BitMEX enforces rate limits at the account level (not per connection), the broadcaster can push you over the exchange's default limits of 10 req/s burst and 120 req/min rolling window.
Mitigations: Reduce max_requests_per_second and max_requests_per_minute proportionally (divide by canceller_pool_size), or adjust the pool size itself (see Cancel broadcaster configuration).
Future versions may support shared rate limiters across the pool.
:::
BitMEX exposes the current allowance via response headers:
x-ratelimit-limit: total requests permitted in the current window.x-ratelimit-remaining: remaining requests before throttling occurs.x-ratelimit-reset: UNIX timestamp when the allowance resets.retry-after: seconds to wait after a 429 response.The BitMEX execution client includes a submit broadcaster that provides higher assurance of market and limit orders being accepted at target prices through parallel request fanout, trading lower minimum latency for the risk of duplicate submissions.
Order submissions are time-critical operations - when a strategy decides to enter a position, any delay can result in missed opportunities or adverse pricing. The submit broadcaster addresses this by:
client_order_id. BitMEX rejects duplicate submissions with "duplicate clOrdID" (tracked as expected rejections).This architecture reduces the minimum latency to order acceptance by parallelizing across multiple network paths.
The submit broadcaster is opt-in and controlled via the submit_tries parameter when submitting orders. By default, orders are submitted through a single HTTP client. To enable broadcasting:
# Single submission (default behavior)
self.submit_order(order)
# Broadcast to 2 parallel HTTP clients for redundancy
self.submit_order(order, params={"submit_tries": 2})
# Broadcast to 3 parallel HTTP clients (maximum recommended)
self.submit_order(order, params={"submit_tries": 3})
Key points:
submit_tries must be a positive integer.submit_tries > 1. Default submits go through a single HTTP client.submit_tries exceeds submitter_pool_size, it will be capped at the pool size with a warning.client_order_id; BitMEX rejects duplicates as expected rejections.Each HTTP client in the broadcaster pool maintains health metrics:
The broadcaster exposes metrics including total submits, successful submits, failed submits, and expected rejects for operational monitoring and debugging.
| Metric | Type | Description |
|---|---|---|
total_submits | u64 | Total number of submit operations initiated. |
successful_submits | u64 | Number of submit operations that successfully received acknowledgement from BitMEX. |
failed_submits | u64 | Number of submit operations where all HTTP clients in the pool failed (no healthy clients or all requests failed). |
expected_rejects | u64 | Number of expected rejection patterns detected (e.g., duplicate clOrdID from parallel submissions). |
healthy_clients | usize | Current number of healthy HTTP clients in the pool (clients that passed recent health checks). |
total_clients | usize | Total number of HTTP clients configured in the pool (submitter_pool_size). |
These metrics can be accessed programmatically via the get_metrics() method on the SubmitBroadcaster instance.
The submit broadcaster is configured via the execution client configuration:
| Option | Default | Description |
|---|---|---|
submitter_pool_size | None | Size of the HTTP client pool. None resolves to 1 (single client, no redundancy). |
submitter_proxy_urls | None | Optional list of proxy URLs for submit broadcaster path diversity. Not yet wired through Python integration. |
Example configuration:
from nautilus_trader.adapters.bitmex.config import BitmexExecClientConfig
exec_config = BitmexExecClientConfig(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
submitter_pool_size=3, # Recommended pool size for redundancy
)
:::tip
For HFT strategies without higher rate limits, consider the advantages of using the submit broadcaster against potentially hitting rate limits, as each client has an independent rate limit budget.
The default submitter_pool_size=None disables the broadcaster. The recommended setting of submitter_pool_size=3 broadcasts each submit request to 3 parallel HTTP clients for fault tolerance, which consumes 3× the rate limit quota per submit operation but provides higher assurance against network or exchange issues.
:::
The broadcaster is automatically started when the execution client connects and stopped when it disconnects. Submit operations are routed through the broadcaster only when submit_tries > 1; default submits use a single HTTP client directly.
The BitMEX execution client includes a cancel broadcaster that provides fault-tolerant order cancellation through parallel request fanout.
Order cancellations are time-critical operations - when a strategy decides to cancel an order, any delay or failure can result in unintended fills, slippage, or unwanted position exposure. The cancel broadcaster addresses this by:
This architecture ensures that a single network path failure or slow connection doesn't block cancel operations, improving the reliability of risk management and position control in live trading.
Each HTTP client in the broadcaster pool maintains health metrics:
The broadcaster exposes metrics including total cancels, successful cancels, failed cancels, expected rejects (already canceled orders), and idempotent successes for operational monitoring and debugging.
| Metric | Type | Description |
|---|---|---|
total_cancels | u64 | Total number of cancel operations initiated (includes single, batch, and cancel‑all requests). |
successful_cancels | u64 | Number of cancel operations that successfully received acknowledgement from BitMEX. |
failed_cancels | u64 | Number of cancel operations where all HTTP clients in the pool failed (no healthy clients or all requests failed). |
expected_rejects | u64 | Number of expected rejection patterns detected (e.g., post‑only order rejections). |
idempotent_successes | u64 | Number of idempotent success responses (order already cancelled, order not found, unable to cancel due to state). |
healthy_clients | usize | Current number of healthy HTTP clients in the pool (clients that passed recent health checks). |
total_clients | usize | Total number of HTTP clients configured in the pool (canceller_pool_size). |
These metrics can be accessed programmatically via the get_metrics() method on the CancelBroadcaster instance.
The cancel broadcaster is configured via the execution client configuration:
| Option | Default | Description |
|---|---|---|
canceller_pool_size | None | Size of the HTTP client pool. None resolves to 1 (single client, no redundancy). |
canceller_proxy_urls | None | Optional list of proxy URLs for cancel broadcaster path diversity. Not yet wired through Python integration. |
Example configuration:
from nautilus_trader.adapters.bitmex.config import BitmexExecClientConfig
exec_config = BitmexExecClientConfig(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
canceller_pool_size=3, # Recommended pool size for redundancy
)
:::tip
For HFT strategies without higher rate limits, consider the advantages of using the cancel broadcaster against potentially hitting rate limits, as each client has an independent rate limit budget.
The default canceller_pool_size=None disables the broadcaster. The recommended setting of canceller_pool_size=3 broadcasts each cancel request to 3 parallel HTTP clients for fault tolerance, which consumes 3× the rate limit quota per cancel operation but provides higher assurance against network or exchange issues.
:::
The broadcaster is automatically started when the execution client connects and stopped when it disconnects. All cancel operations (cancel_order, cancel_all_orders, batch_cancel_orders) are automatically routed through the broadcaster without requiring any changes to strategy code.
The adapter supports BitMEX's dead man's switch
(cancelAllAfter), which provides automatic order cancellation as a safety net against
connectivity failures.
When enabled, a server-side timer is set on BitMEX. If the timer expires without being refreshed, BitMEX cancels all open orders on the account. The adapter keeps the timer alive by sending periodic heartbeat requests. If the adapter loses connectivity (network failure, process crash, etc.), the heartbeats stop and BitMEX cancels the orders after the configured timeout.
The flow:
POST /api/v1/order/cancelAllAfter with the configured
timeout (in milliseconds) to arm the server-side timer.timeout / 4
(minimum 1 second) to keep resetting the timer before it expires.cancelAllAfter with timeout=0 to disarm the server-side timer.For example, with a 60-second timeout the adapter sends a heartbeat every 15 seconds. If four consecutive heartbeats fail (60 seconds of lost connectivity), BitMEX cancels all open orders.
Disarming the dead man's switch during disconnect requires careful ordering. The disarm
request (timeout=0) should be the last cancelAllAfter call to reach BitMEX. If an
in-flight heartbeat were processed after the disarm, it would re-arm the server-side timer
and orders could be unexpectedly cancelled after the timeout expires, even though the
adapter disconnected gracefully.
The adapter mitigates this in both implementations:
In a force-stop scenario (e.g., process shutdown via stop()), the heartbeat task is
aborted without disarming. This is intentional, as the server-side timer provides the
desired safety behavior when the process exits unexpectedly.
:::note Each heartbeat consumes one REST rate limit token. A 60-second timeout uses approximately 4 requests per minute from the 120/min budget. :::
Enable the dead man's switch by setting deadmans_switch_timeout_secs on the execution
client config:
from nautilus_trader.adapters.bitmex.config import BitmexExecClientConfig
exec_config = BitmexExecClientConfig(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
deadmans_switch_timeout_secs=60, # Cancel all orders after 60s of lost connectivity
)
When enabled, the adapter logs:
Starting dead man's switch: timeout=60s, refresh_interval=15s
on connect, and:
Disarming dead man's switch
on disconnect.
:::tip A timeout of 60 seconds is the recommended starting point. Shorter timeouts provide faster protection but are more sensitive to transient network blips. Longer timeouts are more tolerant of brief outages but leave orders exposed longer during a real failure. :::
:::warning The dead man's switch applies to all open orders on the account, not just orders placed by the adapter. If other systems place orders on the same account, enabling the dead man's switch will affect those orders too. :::
BitMEX API credentials can be provided either directly in the configuration or via environment variables:
BITMEX_API_KEY: Your BitMEX API key for production.BITMEX_API_SECRET: Your BitMEX API secret for production.BITMEX_TESTNET_API_KEY: Your BitMEX API key for testnet (when testnet=True).BITMEX_TESTNET_API_SECRET: Your BitMEX API secret for testnet (when testnet=True).To generate API keys:
:::note Testnet API endpoints:
https://testnet.bitmex.com/api/v1wss://ws.testnet.bitmex.com/realtimeThe adapter automatically routes requests to the correct endpoints when testnet=True is configured.
:::
The BitMEX data client provides the following configuration options:
| Option | Default | Description |
|---|---|---|
api_key | None | Optional API key; if None, loaded from BITMEX_API_KEY or BITMEX_TESTNET_API_KEY (when testnet=True). |
api_secret | None | Optional API secret; if None, loaded from BITMEX_API_SECRET or BITMEX_TESTNET_API_SECRET (when testnet=True). |
base_url_http | None | Override for the REST base URL (defaults to production). |
base_url_ws | None | Override for the WebSocket base URL (defaults to production). |
testnet | False | Route requests to the BitMEX testnet when True. |
http_timeout_secs | 60 | Request timeout applied to HTTP calls. |
max_retries | 3 | Maximum retry attempts for HTTP calls. |
retry_delay_initial_ms | 1,000 | Initial backoff delay (milliseconds) between retries. |
retry_delay_max_ms | 10,000 | Maximum backoff delay (milliseconds) between retries. |
recv_window_ms | 10,000 | Expiration window (milliseconds) for signed requests. See Request authentication. |
update_instruments_interval_mins | 60 | Interval (minutes) between instrument catalogue refreshes. |
max_requests_per_second | 10 | Burst rate limit enforced by the adapter for REST calls. |
max_requests_per_minute | 120 | Rolling minute rate limit enforced by the adapter for REST calls. |
proxy_url | None | Optional proxy URL for HTTP and WebSocket transports. |
The BitMEX execution client provides the following configuration options:
| Option | Default | Description |
|---|---|---|
api_key | None | Optional API key; if None, loaded from BITMEX_API_KEY or BITMEX_TESTNET_API_KEY (when testnet=True). |
api_secret | None | Optional API secret; if None, loaded from BITMEX_API_SECRET or BITMEX_TESTNET_API_SECRET (when testnet=True). |
base_url_http | None | Override for the REST base URL (defaults to production). |
base_url_ws | None | Override for the WebSocket base URL (defaults to production). |
testnet | False | Route orders to the BitMEX testnet when True. |
http_timeout_secs | 60 | Request timeout applied to HTTP calls. |
max_retries | 3 | Maximum retry attempts for HTTP calls. |
retry_delay_initial_ms | 1,000 | Initial backoff delay (milliseconds) between retries. |
retry_delay_max_ms | 10,000 | Maximum backoff delay (milliseconds) between retries. |
recv_window_ms | 10,000 | Expiration window (milliseconds) for signed requests. See Request authentication. |
max_requests_per_second | 10 | Burst rate limit enforced by the adapter for REST calls. |
max_requests_per_minute | 120 | Rolling minute rate limit enforced by the adapter for REST calls. |
deadmans_switch_timeout_secs | None | Timeout in seconds for the dead man's switch. None disables. See Dead man's switch. |
canceller_pool_size | None | Number of HTTP clients in the cancel broadcaster pool. None resolves to 1. See Cancel broadcaster. |
submitter_pool_size | None | Number of HTTP clients in the submit broadcaster pool. None resolves to 1. See Submit broadcaster. |
proxy_url | None | Optional proxy URL for HTTP and WebSocket transports. |
submitter_proxy_urls | None | Optional list of proxy URLs for submit broadcaster path diversity. Not yet wired through Python integration. |
canceller_proxy_urls | None | Optional list of proxy URLs for cancel broadcaster path diversity. Not yet wired through Python integration. |
A typical BitMEX configuration for live trading includes both testnet and mainnet options:
from nautilus_trader.adapters.bitmex.config import BitmexDataClientConfig
from nautilus_trader.adapters.bitmex.config import BitmexExecClientConfig
# Using environment variables (recommended)
testnet_data_config = BitmexDataClientConfig(
testnet=True, # API credentials loaded from BITMEX_TESTNET_API_KEY and BITMEX_TESTNET_API_SECRET
)
# Using explicit credentials
mainnet_data_config = BitmexDataClientConfig(
api_key="YOUR_API_KEY", # Or use os.getenv("BITMEX_API_KEY")
api_secret="YOUR_API_SECRET", # Or use os.getenv("BITMEX_API_SECRET")
testnet=False,
)
mainnet_exec_config = BitmexExecClientConfig(
api_key="YOUR_API_KEY",
api_secret="YOUR_API_SECRET",
testnet=False,
)
The BitMEX execution adapter now maps Nautilus contingent order lists to the exchange's
native clOrdLinkID/contingencyType mechanics. When the engine submits
ContingencyType::Oco or ContingencyType::Oto orders the adapter will:
This means common bracket flows (entry + stop + take-profit) and multi-leg stop structures can
now be managed directly by BitMEX instead of being emulated client-side. When defining
strategies, continue to use Nautilus OrderList/ContingencyType abstractions. The adapter
handles the required BitMEX wiring automatically.
:::info For additional features or to contribute to the BitMEX adapter, please see our contributing guide. :::