pub struct DydxHttpClient { /* private fields */ }Expand description
Provides a higher-level HTTP client for the dYdX v4 Indexer REST API.
This client wraps the underlying DydxRawHttpClient to handle conversions
into the Nautilus domain model, following the two-layer pattern established
in OKX, Bybit, and BitMEX adapters.
Architecture:
- Raw client (
DydxRawHttpClient): Low-level HTTP methods matching dYdX Indexer API endpoints. - Domain client (
DydxHttpClient): High-level methods using Nautilus domain types.
The domain client:
- Wraps the raw client in an
Arcfor efficient cloning (required for Python bindings). - Maintains an instrument cache using
DashMapfor thread-safe concurrent access. - Provides standard cache methods:
cache_instruments(),cache_instrument(),get_instrument(). - Tracks cache initialization state for optimizations.
Implementations§
Source§impl DydxHttpClient
impl DydxHttpClient
Sourcepub fn new(
base_url: Option<String>,
timeout_secs: Option<u64>,
proxy_url: Option<String>,
is_testnet: bool,
retry_config: Option<RetryConfig>,
) -> Result<Self>
pub fn new( base_url: Option<String>, timeout_secs: Option<u64>, proxy_url: Option<String>, is_testnet: bool, retry_config: Option<RetryConfig>, ) -> Result<Self>
Creates a new DydxHttpClient using the default dYdX Indexer HTTP URL,
optionally overridden with a custom base URL.
This constructor creates its own internal instrument cache. For shared caching
across multiple clients, use new_with_cache instead.
Note: No credentials are required as the dYdX Indexer API is publicly accessible. Order submission and trading operations use gRPC with blockchain transaction signing.
§Errors
Returns an error if the underlying HTTP client or retry manager cannot be created.
Sourcepub fn new_with_cache(
base_url: Option<String>,
timeout_secs: Option<u64>,
proxy_url: Option<String>,
is_testnet: bool,
retry_config: Option<RetryConfig>,
instrument_cache: Arc<InstrumentCache>,
) -> Result<Self>
pub fn new_with_cache( base_url: Option<String>, timeout_secs: Option<u64>, proxy_url: Option<String>, is_testnet: bool, retry_config: Option<RetryConfig>, instrument_cache: Arc<InstrumentCache>, ) -> Result<Self>
Creates a new DydxHttpClient with a shared instrument cache.
Use this constructor when sharing instrument data between HTTP client, WebSocket client, and execution client.
§Arguments
instrument_cache- Shared instrument cache for lookups by symbol, ticker, or clob_pair_id
§Errors
Returns an error if the underlying HTTP client or retry manager cannot be created.
Sourcepub async fn request_instruments(
&self,
symbol: Option<String>,
maker_fee: Option<Decimal>,
taker_fee: Option<Decimal>,
) -> Result<Vec<InstrumentAny>>
pub async fn request_instruments( &self, symbol: Option<String>, maker_fee: Option<Decimal>, taker_fee: Option<Decimal>, ) -> Result<Vec<InstrumentAny>>
Requests instruments from the dYdX Indexer API and returns Nautilus domain types.
This method does NOT automatically cache results. Use fetch_and_cache_instruments()
for automatic caching, or call cache_instruments() manually with the results.
§Errors
Returns an error if the HTTP request or parsing fails. Individual instrument parsing errors are logged as warnings.
Sourcepub async fn fetch_and_cache_instruments(&self) -> Result<()>
pub async fn fetch_and_cache_instruments(&self) -> Result<()>
Fetches instruments from the API and caches them.
This is a convenience method that fetches instruments and populates both the symbol-based and CLOB pair ID-based caches.
On success, existing caches are cleared and repopulated atomically. On failure, existing caches are preserved (no partial updates).
§Errors
Returns an error if the HTTP request fails.
Sourcepub async fn fetch_and_cache_single_instrument(
&self,
ticker: &str,
) -> Result<Option<InstrumentAny>>
pub async fn fetch_and_cache_single_instrument( &self, ticker: &str, ) -> Result<Option<InstrumentAny>>
Fetches a single instrument by ticker and caches it.
§Errors
Returns an error if the HTTP request fails.
Sourcepub fn cache_instruments(&self, instruments: Vec<InstrumentAny>)
pub fn cache_instruments(&self, instruments: Vec<InstrumentAny>)
Caches multiple instruments (symbol lookup only).
Use fetch_and_cache_instruments() for full caching with market params.
Any existing instruments with the same symbols will be replaced.
Sourcepub fn cache_instrument(&self, instrument: InstrumentAny)
pub fn cache_instrument(&self, instrument: InstrumentAny)
Caches a single instrument (symbol lookup only).
Use fetch_and_cache_instruments() for full caching with market params.
Any existing instrument with the same symbol will be replaced.
Sourcepub fn get_instrument(
&self,
instrument_id: &InstrumentId,
) -> Option<InstrumentAny>
pub fn get_instrument( &self, instrument_id: &InstrumentId, ) -> Option<InstrumentAny>
Gets an instrument from the cache by InstrumentId.
Sourcepub fn get_instrument_by_clob_id(
&self,
clob_pair_id: u32,
) -> Option<InstrumentAny>
pub fn get_instrument_by_clob_id( &self, clob_pair_id: u32, ) -> Option<InstrumentAny>
Gets an instrument by CLOB pair ID.
Only works for instruments cached via fetch_and_cache_instruments().
Sourcepub fn get_instrument_by_market(&self, ticker: &str) -> Option<InstrumentAny>
pub fn get_instrument_by_market(&self, ticker: &str) -> Option<InstrumentAny>
Gets an instrument by market ticker (e.g., “BTC-USD”).
Only works for instruments cached via fetch_and_cache_instruments().
Sourcepub fn get_market_params(
&self,
instrument_id: &InstrumentId,
) -> Option<PerpetualMarket>
pub fn get_market_params( &self, instrument_id: &InstrumentId, ) -> Option<PerpetualMarket>
Gets market parameters for order submission from the cached market data.
Returns the quantization parameters needed by OrderBuilder to construct properly formatted orders for the dYdX v4 protocol.
§Errors
Returns None if the instrument is not found in the market params cache.
Sourcepub async fn request_trades(
&self,
symbol: &str,
limit: Option<u32>,
starting_before_or_at_height: Option<u64>,
) -> Result<TradesResponse>
pub async fn request_trades( &self, symbol: &str, limit: Option<u32>, starting_before_or_at_height: Option<u64>, ) -> Result<TradesResponse>
Requests historical trades for a symbol.
Fetches trade data from the dYdX Indexer API’s /v4/trades/perpetualMarket/:ticker endpoint.
Results are ordered by creation time descending (newest first).
§Errors
Returns an error if the HTTP request fails or response cannot be parsed.
Sourcepub async fn request_candles(
&self,
symbol: &str,
resolution: DydxCandleResolution,
limit: Option<u32>,
from_iso: Option<DateTime<Utc>>,
to_iso: Option<DateTime<Utc>>,
) -> Result<CandlesResponse>
pub async fn request_candles( &self, symbol: &str, resolution: DydxCandleResolution, limit: Option<u32>, from_iso: Option<DateTime<Utc>>, to_iso: Option<DateTime<Utc>>, ) -> Result<CandlesResponse>
Requests historical candles for a symbol.
Fetches candle data from the dYdX Indexer API’s /v4/candles/perpetualMarkets/:ticker endpoint.
Results are ordered by start time ascending (oldest first).
§Errors
Returns an error if the HTTP request fails or response cannot be parsed.
Sourcepub async fn request_bars(
&self,
bar_type: BarType,
start: Option<DateTime<Utc>>,
end: Option<DateTime<Utc>>,
limit: Option<u32>,
timestamp_on_close: bool,
) -> Result<Vec<Bar>>
pub async fn request_bars( &self, bar_type: BarType, start: Option<DateTime<Utc>>, end: Option<DateTime<Utc>>, limit: Option<u32>, timestamp_on_close: bool, ) -> Result<Vec<Bar>>
Requests historical bars for an instrument with optional pagination.
Fetches candle data from the dYdX Indexer API and converts to Nautilus
Bar objects. Supports time-chunked pagination for large date ranges.
The resolution is derived internally from bar_type (no need to pass
DydxCandleResolution). Incomplete bars (where ts_event >= now) are
filtered out.
Results are returned in chronological order (oldest first).
§Errors
Returns an error if:
- The bar type uses unsupported aggregation/price type.
- The HTTP request fails or response cannot be parsed.
- The instrument is not found in the cache.
Sourcepub async fn request_trade_ticks(
&self,
instrument_id: InstrumentId,
start: Option<DateTime<Utc>>,
end: Option<DateTime<Utc>>,
limit: Option<u32>,
) -> Result<Vec<TradeTick>>
pub async fn request_trade_ticks( &self, instrument_id: InstrumentId, start: Option<DateTime<Utc>>, end: Option<DateTime<Utc>>, limit: Option<u32>, ) -> Result<Vec<TradeTick>>
Requests historical trade ticks for an instrument with optional pagination.
Fetches trade data from the dYdX Indexer API and converts them to Nautilus
TradeTick objects. Supports cursor-based pagination using block height
and client-side time filtering (the dYdX API has no timestamp filter).
Results are returned in chronological order (oldest first).
§Errors
Returns an error if the HTTP request fails, response cannot be parsed, or the instrument is not found in the cache.
§Panics
This function will panic if the API returns a non-empty trades response
but last() on the trades vector returns None (should never happen).
Sourcepub async fn request_orderbook_snapshot(
&self,
instrument_id: InstrumentId,
) -> Result<OrderBookDeltas>
pub async fn request_orderbook_snapshot( &self, instrument_id: InstrumentId, ) -> Result<OrderBookDeltas>
Requests an order book snapshot for a symbol.
Fetches order book data from the dYdX Indexer API and converts it to Nautilus
OrderBookDeltas. The snapshot is represented as a sequence of deltas starting
with a CLEAR action followed by ADD actions for each level.
§Errors
Returns an error if the HTTP request fails, response cannot be parsed, or the instrument is not found in the cache.
Sourcepub fn raw_client(&self) -> &Arc<DydxRawHttpClient>
pub fn raw_client(&self) -> &Arc<DydxRawHttpClient>
Exposes raw HTTP client for testing and advanced use cases.
This provides access to the underlying DydxRawHttpClient for cases
where low-level API access is needed. Most users should use the domain
client methods instead.
Sourcepub fn is_testnet(&self) -> bool
pub fn is_testnet(&self) -> bool
Check if this client is configured for testnet.
Sourcepub fn is_cache_initialized(&self) -> bool
pub fn is_cache_initialized(&self) -> bool
Check if the instrument cache has been initialized.
Sourcepub fn cached_instruments_count(&self) -> usize
pub fn cached_instruments_count(&self) -> usize
Get the number of instruments currently cached.
Sourcepub fn instrument_cache(&self) -> &Arc<InstrumentCache>
pub fn instrument_cache(&self) -> &Arc<InstrumentCache>
Returns a reference to the shared instrument cache.
The cache provides lookups by symbol, market ticker, and clob_pair_id.
Sourcepub fn all_instruments(&self) -> Vec<InstrumentAny>
pub fn all_instruments(&self) -> Vec<InstrumentAny>
Returns all cached instruments.
This is a convenience method that collects all instruments into a Vec.
Sourcepub fn all_instrument_ids(&self) -> Vec<InstrumentId>
pub fn all_instrument_ids(&self) -> Vec<InstrumentId>
Returns all cached instrument IDs.
Sourcepub async fn request_order_status_reports(
&self,
address: &str,
subaccount_number: u32,
account_id: AccountId,
instrument_id: Option<InstrumentId>,
) -> Result<Vec<OrderStatusReport>>
pub async fn request_order_status_reports( &self, address: &str, subaccount_number: u32, account_id: AccountId, instrument_id: Option<InstrumentId>, ) -> Result<Vec<OrderStatusReport>>
Requests order status reports for a subaccount.
Fetches orders from the dYdX Indexer API and converts them to Nautilus
OrderStatusReport objects.
§Errors
Returns an error if the HTTP request fails or parsing fails.
Sourcepub async fn request_fill_reports(
&self,
address: &str,
subaccount_number: u32,
account_id: AccountId,
instrument_id: Option<InstrumentId>,
) -> Result<Vec<FillReport>>
pub async fn request_fill_reports( &self, address: &str, subaccount_number: u32, account_id: AccountId, instrument_id: Option<InstrumentId>, ) -> Result<Vec<FillReport>>
Requests fill reports for a subaccount.
Fetches fills from the dYdX Indexer API and converts them to Nautilus
FillReport objects.
§Errors
Returns an error if the HTTP request fails or parsing fails.
Sourcepub async fn request_position_status_reports(
&self,
address: &str,
subaccount_number: u32,
account_id: AccountId,
instrument_id: Option<InstrumentId>,
) -> Result<Vec<PositionStatusReport>>
pub async fn request_position_status_reports( &self, address: &str, subaccount_number: u32, account_id: AccountId, instrument_id: Option<InstrumentId>, ) -> Result<Vec<PositionStatusReport>>
Requests position status reports for a subaccount.
Fetches positions from the dYdX Indexer API and converts them to Nautilus
PositionStatusReport objects.
§Errors
Returns an error if the HTTP request fails or parsing fails.
Trait Implementations§
Source§impl Clone for DydxHttpClient
impl Clone for DydxHttpClient
Source§impl Debug for DydxHttpClient
impl Debug for DydxHttpClient
Source§impl Default for DydxHttpClient
impl Default for DydxHttpClient
Source§impl<'py> IntoPyObject<'py> for DydxHttpClient
impl<'py> IntoPyObject<'py> for DydxHttpClient
Source§type Target = DydxHttpClient
type Target = DydxHttpClient
Source§type Output = Bound<'py, <DydxHttpClient as IntoPyObject<'py>>::Target>
type Output = Bound<'py, <DydxHttpClient as IntoPyObject<'py>>::Target>
Source§fn into_pyobject(
self,
py: Python<'py>,
) -> Result<<Self as IntoPyObject<'_>>::Output, <Self as IntoPyObject<'_>>::Error>
fn into_pyobject( self, py: Python<'py>, ) -> Result<<Self as IntoPyObject<'_>>::Output, <Self as IntoPyObject<'_>>::Error>
Source§impl PyClass for DydxHttpClient
impl PyClass for DydxHttpClient
Source§impl PyClassImpl for DydxHttpClient
impl PyClassImpl for DydxHttpClient
Source§const IS_BASETYPE: bool = false
const IS_BASETYPE: bool = false
Source§const IS_SUBCLASS: bool = false
const IS_SUBCLASS: bool = false
Source§const IS_MAPPING: bool = false
const IS_MAPPING: bool = false
Source§const IS_SEQUENCE: bool = false
const IS_SEQUENCE: bool = false
Source§const IS_IMMUTABLE_TYPE: bool = false
const IS_IMMUTABLE_TYPE: bool = false
Source§const RAW_DOC: &'static CStr = /// Provides a higher-level HTTP client for the [dYdX v4](https://dydx.exchange) Indexer REST API.
///
/// This client wraps the underlying `DydxRawHttpClient` to handle conversions
/// into the Nautilus domain model, following the two-layer pattern established
/// in OKX, Bybit, and BitMEX adapters.
///
/// **Architecture:**
/// - **Raw client** (`DydxRawHttpClient`): Low-level HTTP methods matching dYdX Indexer API endpoints.
/// - **Domain client** (`DydxHttpClient`): High-level methods using Nautilus domain types.
///
/// The domain client:
/// - Wraps the raw client in an `Arc` for efficient cloning (required for Python bindings).
/// - Maintains an instrument cache using `DashMap` for thread-safe concurrent access.
/// - Provides standard cache methods: `cache_instruments()`, `cache_instrument()`, `get_instrument()`.
/// - Tracks cache initialization state for optimizations.
const RAW_DOC: &'static CStr = /// Provides a higher-level HTTP client for the [dYdX v4](https://dydx.exchange) Indexer REST API. /// /// This client wraps the underlying `DydxRawHttpClient` to handle conversions /// into the Nautilus domain model, following the two-layer pattern established /// in OKX, Bybit, and BitMEX adapters. /// /// **Architecture:** /// - **Raw client** (`DydxRawHttpClient`): Low-level HTTP methods matching dYdX Indexer API endpoints. /// - **Domain client** (`DydxHttpClient`): High-level methods using Nautilus domain types. /// /// The domain client: /// - Wraps the raw client in an `Arc` for efficient cloning (required for Python bindings). /// - Maintains an instrument cache using `DashMap` for thread-safe concurrent access. /// - Provides standard cache methods: `cache_instruments()`, `cache_instrument()`, `get_instrument()`. /// - Tracks cache initialization state for optimizations.
Source§const DOC: &'static CStr
const DOC: &'static CStr
text_signature if a constructor is defined. Read moreSource§type ThreadChecker = SendablePyClass<DydxHttpClient>
type ThreadChecker = SendablePyClass<DydxHttpClient>
Source§type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild
type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild
Source§type BaseNativeType = PyAny
type BaseNativeType = PyAny
PyAny by default, and when you declare
#[pyclass(extends=PyDict)], it’s PyDict.fn items_iter() -> PyClassItemsIter
fn lazy_type_object() -> &'static LazyTypeObject<Self>
fn dict_offset() -> Option<isize>
fn weaklist_offset() -> Option<isize>
Source§impl PyClassNewTextSignature for DydxHttpClient
impl PyClassNewTextSignature for DydxHttpClient
const TEXT_SIGNATURE: &'static str = "(base_url=None, is_testnet=False)"
Source§impl PyMethods<DydxHttpClient> for PyClassImplCollector<DydxHttpClient>
impl PyMethods<DydxHttpClient> for PyClassImplCollector<DydxHttpClient>
fn py_methods(self) -> &'static PyClassItems
Source§impl PyTypeInfo for DydxHttpClient
impl PyTypeInfo for DydxHttpClient
Source§fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject
fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject
§fn type_object(py: Python<'_>) -> Bound<'_, PyType>
fn type_object(py: Python<'_>) -> Bound<'_, PyType>
§fn is_type_of(object: &Bound<'_, PyAny>) -> bool
fn is_type_of(object: &Bound<'_, PyAny>) -> bool
object is an instance of this type or a subclass of this type.§fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool
fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool
object is an instance of this type.impl DerefToPyAny for DydxHttpClient
impl ExtractPyClassWithClone for DydxHttpClient
Auto Trait Implementations§
impl Freeze for DydxHttpClient
impl !RefUnwindSafe for DydxHttpClient
impl Send for DydxHttpClient
impl Sync for DydxHttpClient
impl Unpin for DydxHttpClient
impl UnsafeUnpin for DydxHttpClient
impl !UnwindSafe for DydxHttpClient
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more§impl<'py, T> IntoPyObjectExt<'py> for Twhere
T: IntoPyObject<'py>,
impl<'py, T> IntoPyObjectExt<'py> for Twhere
T: IntoPyObject<'py>,
§fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>
fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>
self into an owned Python object, dropping type information.§fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>
fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>
self into an owned Python object, dropping type information and unbinding it
from the 'py lifetime.§fn into_pyobject_or_pyerr(self, py: Python<'py>) -> Result<Self::Output, PyErr>
fn into_pyobject_or_pyerr(self, py: Python<'py>) -> Result<Self::Output, PyErr>
self into a Python object. Read more§impl<'py, T> IntoPyObjectNautilusExt<'py> for Twhere
T: IntoPyObjectExt<'py>,
impl<'py, T> IntoPyObjectNautilusExt<'py> for Twhere
T: IntoPyObjectExt<'py>,
§fn into_py_any_unwrap(self, py: Python<'py>) -> Py<PyAny>
fn into_py_any_unwrap(self, py: Python<'py>) -> Py<PyAny>
§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request§impl<L> LayerExt<L> for L
impl<L> LayerExt<L> for L
§fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
Layered].§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
§impl<T> PyErrArguments for T
impl<T> PyErrArguments for T
§impl<T> PyTypeCheck for Twhere
T: PyTypeInfo,
impl<T> PyTypeCheck for Twhere
T: PyTypeInfo,
§const NAME: &'static str = T::NAME
const NAME: &'static str = T::NAME
§fn type_check(object: &Bound<'_, PyAny>) -> bool
fn type_check(object: &Bound<'_, PyAny>) -> bool
§fn classinfo_object(py: Python<'_>) -> Bound<'_, PyAny>
fn classinfo_object(py: Python<'_>) -> Bound<'_, PyAny>
isinstance and issubclass function. Read more