dYdX
We are currently working on this integration 指南.
dYdX is one of the largest decentralized cryptocurrency exchanges in terms of daily trading volume for crypto derivative products. dYdX runs on smart contracts on the Ethereum blockchain, and allows users to trade with no intermediaries. This integration supports live market 数据 ingestion and order 执行 with dYdX v4, which is the first 版本 of the 协议 to be fully decentralized with no central components.
安装
To install NautilusTrader with dYdX 支持:
pip install --upgrade "nautilus_trader[dydx]"
To build from source with all extras (including dYdX):
uv sync --all-extras
示例
You can find live example scripts here.
概览
This 指南 assumes a trader is setting up for both live market 数据 feeds, and trade 执行. The dYdX adapter includes multiple components, which can be used together or separately depending on the use case.
DYDXHttpClient
: Low-level HTTP API connectivity.DYDXWebSocketClient
: Low-level WebSocket API connectivity.DYDXAccountGRPCAPI
: Low-level gRPC API connectivity for account updates.DYDXInstrumentProvider
: Instrument parsing and loading functionality.DYDXDataClient
: A market data feed manager.DYDXExecutionClient
: An account management and trade execution gateway.DYDXLiveDataClientFactory
: Factory for dYdX data clients (used by the trading node builder).DYDXLiveExecClientFactory
: Factory for dYdX execution clients (used by the trading node builder).
Most users will simply define a 配置 for a 实时交易 节点 (as below), and won't need to necessarily work with these lower level components directly.
A dYdX v4 trading account (sub-account 0) is created only after the wallet’s first deposit or trade.
Until then, every gRPC/Indexer query returns NOT_FOUND
, so DYDXExecutionClient.connect()
fails.
Action → Before starting a live TradingNode
, send any positive amount of USDC (≥ 1 wei) or other supported collateral from the same wallet on the same 网络 (mainnet / testnet).
Once the transaction has finalised (a few blocks) restart the 节点; the 客户端 will connect cleanly.
故障排除
StatusCode.NOT_FOUND
— account … /0 not found
Cause The wallet/sub-account has never been funded and therefore does not yet exist on-chain.
Fix
- Deposit any positive amount of USDC to sub-account 0 on the correct 网络.
- Wait for finality (≈ 30 s on mainnet, longer on testnet).
- Restart the
TradingNode
; the connection should now succeed.
In unattended deployments, wrap the connect()
call in an exponential-backoff loop so the 客户端 retries until the deposit appears.
Symbology
Only perpetual contracts are available on dYdX. To be consistent with other 适配器 and to be
futureproof in case other products become available on dYdX, NautilusTrader appends -PERP
for all
available perpetual symbols. For example, the Bitcoin/USD-C perpetual futures contract is identified
as BTC-USD-PERP
. The quote currency for all markets is USD-C. Therefore, dYdX abbreviates it to USD.
Short-term and long-term 订单
dYdX makes a distinction between short-term 订单 and long-term 订单 (or stateful 订单). Short-term 订单 are meant to be placed immediately and belongs in the same block the order was received. These 订单 stay in-内存 up to 20 blocks, with only their fill amount and expiry block height being committed to state. Short-term 订单 are mainly intended for use by market makers with high 吞吐量 or for market 订单.
By default, all 订单 are sent as short-term 订单. To construct long-term 订单, you can attach a tag to an order like this:
from nautilus_trader.adapters.dydx import DYDXOrderTags
order: LimitOrder = self.order_factory.limit(
instrument_id=self.instrument_id,
order_side=OrderSide.BUY,
quantity=self.instrument.make_qty(self.trade_size),
price=self.instrument.make_price(price),
time_in_force=TimeInForce.GTD,
expire_time=self.clock.utc_now() + pd.Timedelta(minutes=10),
post_only=True,
emulation_trigger=self.emulation_trigger,
tags=[DYDXOrderTags(is_short_term_order=False).value],
)
To specify the number of blocks that an order is active:
from nautilus_trader.adapters.dydx import DYDXOrderTags
order: LimitOrder = self.order_factory.limit(
instrument_id=self.instrument_id,
order_side=OrderSide.BUY,
quantity=self.instrument.make_qty(self.trade_size),
price=self.instrument.make_price(price),
time_in_force=TimeInForce.GTD,
expire_time=self.clock.utc_now() + pd.Timedelta(seconds=5),
post_only=True,
emulation_trigger=self.emulation_trigger,
tags=[DYDXOrderTags(is_short_term_order=True, num_blocks_open=5).value],
)
Market 订单
Market 订单 require specifying a price to for price slippage protection and use hidden 订单. By setting a price for a market order, you can limit the potential price slippage. For example, if you set the price of $100 for a market buy order, the order will only be executed if the market price is at or below $100. If the market price is above $100, the order will not be executed.
Some exchanges, including dYdX, 支持 hidden 订单. A hidden order is an order that is not visible to other market participants, but is still executable. By setting a price for a market order, you can create a hidden order that will only be executed if the market price reaches the specified price.
If the market price is not specified, a default value of 0 is used.
To specify the price when creating a market order:
order = self.order_factory.market(
instrument_id=self.instrument_id,
order_side=OrderSide.BUY,
quantity=self.instrument.make_qty(self.trade_size),
time_in_force=TimeInForce.IOC,
tags=[DYDXOrderTags(is_short_term_order=True, market_order_price=Price.from_str("10_000")).value],
)
Stop limit and stop market 订单
Both stop limit and stop market conditional 订单 can be submitted. dYdX only supports long-term 订单 for conditional 订单.
Capability Matrix
dYdX supports perpetual futures trading with a comprehensive set of order types and 执行 features.
Order Types
Order Type | Perpetuals | Notes |
---|---|---|
MARKET | ✓ | Requires price for slippage protection. |
LIMIT | ✓ | |
STOP_MARKET | ✓ | Long-term 订单 only. |
STOP_LIMIT | ✓ | Long-term 订单 only. |
MARKET_IF_TOUCHED | - | Not supported. |
LIMIT_IF_TOUCHED | - | Not supported. |
TRAILING_STOP_MARKET | - | Not supported. |
执行 Instructions
Instruction | Perpetuals | Notes |
---|---|---|
post_only | ✓ | Supported on all order types. |
reduce_only | ✓ | Supported on all order types. |
Time in force options
Time in force | Perpetuals | Notes |
---|---|---|
GTC | ✓ | Good Till Canceled. |
GTD | ✓ | Good Till Date. |
FOK | ✓ | Fill or Kill. |
IOC | ✓ | Immediate or Cancel. |
Advanced Order Features
功能 | Perpetuals | Notes |
---|---|---|
Order Modification | ✓ | Short-term 订单 only; cancel-replace method. |
Bracket/OCO 订单 | - | Not supported. |
Iceberg 订单 | - | Not supported. |
Batch operations
Operation | Perpetuals | Notes |
---|---|---|
Batch Submit | - | Not supported. |
Batch Modify | - | Not supported. |
Batch Cancel | - | Not supported. |
Position management
功能 | Perpetuals | Notes |
---|---|---|
Query 头寸 | ✓ | 实时 position updates. |
Position mode | - | Net position mode only. |
Leverage control | ✓ | Per-market leverage settings. |
Margin mode | - | Cross margin only. |
Order querying
功能 | Perpetuals | Notes |
---|---|---|
Query open 订单 | ✓ | List all active 订单. |
Query order history | ✓ | Historical order 数据. |
Order status updates | ✓ | 实时 order state changes. |
Trade history | ✓ | 执行 and fill 报告. |
Contingent 订单
功能 | Perpetuals | Notes |
---|---|---|
Order lists | - | Not supported. |
OCO 订单 | - | Not supported. |
Bracket 订单 | - | Not supported. |
Conditional 订单 | ✓ | Stop market and stop limit 订单. |
配置 Options
The following 执行 客户端 配置 options are available:
Option | Default | Description |
---|---|---|
subaccount | 0 | Subaccount number (venue creates subaccount 0 by default). |
wallet_address | None | dYdX wallet address for the account. |
mnemonic | None | Mnemonic for generating private key for order signing. |
is_testnet | False | If True , connects to testnet; if False , connects to mainnet. |
Order Classification
dYdX classifies 订单 as either short-term or long-term 订单:
- Short-term orders: Default for all orders; intended for high-frequency trading and market orders.
- Long-term orders: Required for conditional orders; use
DYDXOrderTags
to specify.
配置
The product types for each 客户端 must be specified in the configurations.
执行 Clients
The account type must be a margin account to trade the perpetual futures contracts.
The most common use case is to configure a live TradingNode
to include dYdX
数据 and 执行 clients. To achieve this, add a dYdX
section to your 客户端
配置(s):
from nautilus_trader.live.node import TradingNode
config = TradingNodeConfig(
..., # Omitted
data_clients={
"DYDX": {
"wallet_address": "YOUR_DYDX_WALLET_ADDRESS",
"is_testnet": False,
},
},
exec_clients={
"DYDX": {
"wallet_address": "YOUR_DYDX_WALLET_ADDRESS",
"subaccount": "YOUR_DYDX_SUBACCOUNT_NUMBER"
"mnemonic": "YOUR_MNEMONIC",
"is_testnet": False,
},
},
)
Then, create a TradingNode
and add the 客户端 factories:
from nautilus_trader.adapters.dydx import DYDXLiveDataClientFactory
from nautilus_trader.adapters.dydx import DYDXLiveExecClientFactory
from nautilus_trader.live.node import TradingNode
# Instantiate the live trading node with a configuration
node = TradingNode(config=config)
# Register the client factories with the node
node.add_data_client_factory("DYDX", DYDXLiveDataClientFactory)
node.add_exec_client_factory("DYDX", DYDXLiveExecClientFactory)
# Finally build the node
node.build()
API Credentials
There are two options for supplying your credentials to the dYdX clients.
Either pass the corresponding wallet_address
and mnemonic
values to the 配置 objects, or
set the following 环境 variables:
For dYdX live clients, you can set:
DYDX_WALLET_ADDRESS
DYDX_MNEMONIC
For dYdX testnet clients, you can set:
DYDX_TESTNET_WALLET_ADDRESS
DYDX_TESTNET_MNEMONIC
We recommend using 环境 variables to manage your credentials.
The 数据 客户端 is using the wallet address to determine the trading fees. The trading fees are used during back tests only.
Testnets
It's also possible to configure one or both clients to connect to the dYdX testnet.
Simply set the is_testnet
option to True
(this is False
by default):
config = TradingNodeConfig(
..., # Omitted
data_clients={
"DYDX": {
"wallet_address": "YOUR_DYDX_WALLET_ADDRESS",
"is_testnet": True,
},
},
exec_clients={
"DYDX": {
"wallet_address": "YOUR_DYDX_WALLET_ADDRESS",
"subaccount": "YOUR_DYDX_SUBACCOUNT_NUMBER"
"mnemonic": "YOUR_MNEMONIC",
"is_testnet": True,
},
},
)
Parser Warnings
Some dYdX 金融工具 are unable to be parsed into Nautilus objects if they contain enormous field values beyond what can be handled by the platform. In these cases, a warn and continue approach is taken (the instrument will not be available).
Order books
Order books can be maintained at full depth or top-of-book quotes depending on the
subscription. The venue does not provide quotes, but the adapter subscribes to order
book deltas and sends new quotes to the DataEngine
when there is a top-of-book price or size change.