Skip to main content

CoinbaseHttpClient

Struct CoinbaseHttpClient 

Source
pub struct CoinbaseHttpClient { /* private fields */ }
Expand description

Provides a domain-level HTTP client for the Coinbase Advanced Trade API.

Wraps CoinbaseRawHttpClient in an Arc and adds instrument caching and Nautilus type conversions. This is the primary HTTP interface for the data and execution clients.

Implementations§

Source§

impl CoinbaseHttpClient

Source

pub fn new( environment: CoinbaseEnvironment, timeout_secs: u64, proxy_url: Option<String>, retry_config: Option<RetryConfig>, ) -> Result<Self, HttpClientError>

Creates a new CoinbaseHttpClient for public endpoints only.

§Errors

Returns an error if the HTTP client cannot be created.

Source

pub fn with_credentials( credential: CoinbaseCredential, environment: CoinbaseEnvironment, timeout_secs: u64, proxy_url: Option<String>, retry_config: Option<RetryConfig>, ) -> Result<Self, HttpClientError>

Creates a new CoinbaseHttpClient with credentials for authenticated requests.

§Errors

Returns an error if the HTTP client cannot be created.

Source

pub fn from_env(environment: CoinbaseEnvironment) -> Result<Self>

Creates an authenticated client from environment variables.

§Errors

Returns Error::Auth if required environment variables are not set.

Source

pub fn from_credentials( api_key: &str, api_secret: &str, environment: CoinbaseEnvironment, timeout_secs: u64, proxy_url: Option<String>, retry_config: Option<RetryConfig>, ) -> Result<Self>

Creates a new CoinbaseHttpClient with explicit credentials.

§Errors

Returns Error::Auth if credentials are invalid.

Source

pub fn cancellation_token(&self) -> &CancellationToken

Returns the cancellation token shared by in-flight requests.

Source

pub fn set_base_url(&self, url: String)

Overrides the base REST URL (for testing with mock servers).

Safe to call regardless of how many clones share the inner client.

Source

pub fn environment(&self) -> CoinbaseEnvironment

Returns the configured environment.

Source

pub fn is_authenticated(&self) -> bool

Returns true if this client has credentials for authenticated requests.

Source

pub fn instruments(&self) -> &Arc<AtomicMap<InstrumentId, InstrumentAny>>

Returns a reference to the instrument cache.

Source

pub fn product_aliases(&self) -> &Arc<AtomicMap<Ustr, Ustr>>

Returns a reference to the product alias map (product_id -> canonical product_id).

Source

pub fn ts_now(&self) -> UnixNanos

Returns the current timestamp from the atomic clock.

Source

pub async fn get_products(&self) -> Result<Value>

Gets all available products.

Source

pub async fn get_product(&self, product_id: &str) -> Result<Value>

Gets a specific product by ID.

Source

pub async fn get_candles( &self, product_id: &str, start: &str, end: &str, granularity: &str, ) -> Result<Value>

Gets candles for a product.

Source

pub async fn get_market_trades( &self, product_id: &str, limit: u32, ) -> Result<Value>

Gets market trades for a product.

Source

pub async fn get_best_bid_ask(&self, product_ids: &[&str]) -> Result<Value>

Gets best bid/ask for one or more products.

Source

pub async fn get_product_book( &self, product_id: &str, limit: Option<u32>, ) -> Result<Value>

Gets the product order book.

Source

pub async fn get_accounts(&self) -> Result<Value>

Gets all accounts.

Source

pub async fn get_account(&self, account_id: &str) -> Result<Value>

Gets a specific account by UUID.

Source

pub async fn get_portfolios(&self) -> Result<Value>

Lists all portfolios visible to the authenticated key.

Source

pub async fn preview_order(&self, body: &Value) -> Result<Value>

Validates an order payload against the venue without submitting it.

Useful for diagnosing account is not available and similar errors because it returns the same error envelope as POST /orders.

Source

pub async fn get_orders(&self, query: &str) -> Result<Value>

Gets historical orders.

Source

pub async fn get_order(&self, order_id: &str) -> Result<Value>

Gets a specific order by ID.

Source

pub async fn get_fills(&self, query: &str) -> Result<Value>

Gets fills (trade executions).

Source

pub async fn get_transaction_summary(&self) -> Result<Value>

Gets fee transaction summary.

Source

pub async fn request_instruments( &self, product_type: Option<CoinbaseProductType>, ) -> Result<Vec<InstrumentAny>>

Requests all instruments from Coinbase, optionally filtered by product type.

Parses each supported product into a Nautilus [InstrumentAny] and caches the results in the shared instrument map. Unsupported products (non-crypto futures, UNKNOWN product types) are skipped with a debug log.

§Errors

Returns an error when the HTTP request fails or the response cannot be deserialized.

Source

pub async fn request_instrument( &self, product_id: &str, ) -> Result<InstrumentAny>

Requests a single instrument by product ID.

Caches the result on success.

§Errors

Returns an error when the HTTP request fails, deserialization fails, or the product cannot be parsed into a supported instrument.

Source

pub async fn request_raw_product(&self, product_id: &str) -> Result<Product>

Requests the raw product payload for a product ID.

Returns the full crate::http::models::Product so callers can read derivatives-specific fields (future_product_details.index_price, funding_rate, funding_time) that are stripped when parsing to a Nautilus instrument.

§Errors

Returns an error when the HTTP request fails or the response cannot be deserialized.

Source

pub async fn request_account_state( &self, account_id: AccountId, ) -> Result<AccountState>

Requests the current account state.

Builds a cash-type [AccountState] from /accounts with one balance per currency. Follows Coinbase’s cursor pagination so multi-wallet accounts are reported in full. reported is set to true since the values come from the venue.

§Errors

Returns an error when the HTTP request fails or the response cannot be parsed.

Source

pub async fn request_order_status_report( &self, account_id: AccountId, client_order_id: Option<ClientOrderId>, venue_order_id: Option<VenueOrderId>, ) -> Result<OrderStatusReport>

Requests a single order status report by venue or client order ID.

Resolves venue order IDs first via /orders/historical/{id}. When only a client_order_id is provided, paginates the order history filtered to that client ID.

§Errors

Returns an error when the HTTP request fails, the order cannot be found, or the response cannot be parsed.

Source

pub async fn request_order_status_reports( &self, account_id: AccountId, instrument_id: Option<InstrumentId>, open_only: bool, start: Option<DateTime<Utc>>, end: Option<DateTime<Utc>>, limit: Option<u32>, ) -> Result<Vec<OrderStatusReport>>

Requests order status reports, optionally filtered by instrument, open status, and time window.

§Errors

Returns an error when the HTTP request fails or when any response cannot be deserialized.

Source

pub async fn request_fill_reports( &self, account_id: AccountId, instrument_id: Option<InstrumentId>, venue_order_id: Option<VenueOrderId>, start: Option<DateTime<Utc>>, end: Option<DateTime<Utc>>, limit: Option<u32>, ) -> Result<Vec<FillReport>>

Requests fill reports, optionally filtered by instrument, venue order ID, and time window.

§Errors

Returns an error when the HTTP request fails or the response cannot be deserialized.

Source

pub fn cache_instrument(&self, instrument: &InstrumentAny)

Caches an instrument in the shared instrument map.

Source

pub fn cache_instruments(&self, instruments: &[InstrumentAny])

Caches a batch of instruments in the shared instrument map.

Source

pub fn record_product_aliases(&self, products: &[Product])

Records product_id -> alias entries for any product whose alias field is non-empty. Coinbase aliases pairs to a canonical id (e.g. BTC-USDC -> BTC-USD) that the WebSocket and user channel use on the wire even when callers operate on the alias side.

Source

pub async fn submit_order( &self, client_order_id: ClientOrderId, instrument_id: InstrumentId, side: OrderSide, order_type: OrderType, quantity: Quantity, time_in_force: TimeInForce, price: Option<Price>, trigger_price: Option<Price>, expire_time: Option<UnixNanos>, post_only: bool, is_quote_quantity: bool, leverage: Option<Decimal>, margin_type: Option<CoinbaseMarginType>, reduce_only: bool, retail_portfolio_id: Option<String>, ) -> Result<CreateOrderResponse>

Submits a new order built from Nautilus domain types.

Maps the order side, order type, and time-in-force to Coinbase’s order_configuration shape and posts to /orders. Returns the venue’s create-order response; callers inspect success and the success/error response variants.

§Errors

Returns an error when the order parameters cannot be mapped to a supported Coinbase configuration, when the HTTP request fails, or when the response cannot be parsed.

Source

pub async fn cancel_orders( &self, venue_order_ids: &[VenueOrderId], ) -> Result<CancelOrdersResponse>

Cancels one or more orders by venue order ID via batch_cancel.

§Errors

Returns an error when the HTTP request fails or the response cannot be parsed.

Source

pub async fn request_cfm_balance_summary(&self) -> Result<CfmBalanceSummary>

Fetches the CFM (futures) balance summary.

§Errors

Returns an error when the HTTP request fails or the response cannot be deserialized.

Source

pub async fn request_cfm_margin_balances(&self) -> Result<Vec<MarginBalance>>

Fetches margin balances derived from the CFM balance summary.

§Errors

Returns an error when the summary cannot be fetched or when a balance cannot be constructed.

Source

pub async fn request_cfm_account_state( &self, account_id: AccountId, ) -> Result<AccountState>

Fetches a margin [AccountState] derived from the CFM balance summary.

§Errors

Returns an error when the summary cannot be fetched or when balances cannot be constructed.

Source

pub async fn request_position_status_reports( &self, account_id: AccountId, ) -> Result<Vec<PositionStatusReport>>

Fetches all CFM futures positions and returns Nautilus position reports.

§Errors

Returns an error when the HTTP request fails or a position cannot be parsed.

Source

pub async fn request_position_status_report( &self, account_id: AccountId, instrument_id: InstrumentId, ) -> Result<Option<PositionStatusReport>>

Fetches a single CFM futures position and returns a position status report when the venue reports a non-flat position.

§Errors

Returns an error when the HTTP request fails or the position cannot be parsed.

Source

pub async fn modify_order( &self, venue_order_id: VenueOrderId, price: Option<Price>, quantity: Option<Quantity>, trigger_price: Option<Price>, ) -> Result<EditOrderResponse>

Modifies an existing GTC order’s price, size, or stop price.

Coinbase’s /orders/edit endpoint is documented to accept edits on these fields for supported order configurations (primarily LIMIT GTC). At least one of price, quantity, or trigger_price must be supplied.

§Errors

Returns an error when the HTTP request fails or the response cannot be deserialized.

Trait Implementations§

Source§

impl Clone for CoinbaseHttpClient

Source§

fn clone(&self) -> CoinbaseHttpClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CoinbaseHttpClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CoinbaseHttpClient

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'a, 'py> FromPyObject<'a, 'py> for CoinbaseHttpClient
where Self: Clone,

Source§

type Error = PyClassGuardError<'a, 'py>

The type returned in the event of a conversion error. Read more
Source§

fn extract( obj: Borrowed<'a, 'py, PyAny>, ) -> Result<Self, <Self as FromPyObject<'a, 'py>>::Error>

Extracts Self from the bound smart pointer obj. Read more
Source§

impl<'py> IntoPyObject<'py> for CoinbaseHttpClient

Source§

type Target = CoinbaseHttpClient

The Python output type
Source§

type Output = Bound<'py, <CoinbaseHttpClient as IntoPyObject<'py>>::Target>

The smart pointer type to use. Read more
Source§

type Error = PyErr

The type returned in the event of a conversion error.
Source§

fn into_pyobject( self, py: Python<'py>, ) -> Result<<Self as IntoPyObject<'_>>::Output, <Self as IntoPyObject<'_>>::Error>

Performs the conversion.
Source§

impl PyClass for CoinbaseHttpClient

Source§

const NAME: &str = "CoinbaseHttpClient"

Name of the class. Read more
Source§

type Frozen = False

Whether the pyclass is frozen. Read more
Source§

impl PyClassImpl for CoinbaseHttpClient

Source§

const MODULE: Option<&str>

Module which the class will be associated with. Read more
Source§

const IS_BASETYPE: bool = false

#[pyclass(subclass)]
Source§

const IS_SUBCLASS: bool = false

#[pyclass(extends=…)]
Source§

const IS_MAPPING: bool = false

#[pyclass(mapping)]
Source§

const IS_SEQUENCE: bool = false

#[pyclass(sequence)]
Source§

const IS_IMMUTABLE_TYPE: bool = false

#[pyclass(immutable_type)]
Source§

const RAW_DOC: &'static CStr = /// Provides a domain-level HTTP client for the Coinbase Advanced Trade API. /// /// Wraps [`CoinbaseRawHttpClient`] in an `Arc` and adds instrument caching /// and Nautilus type conversions. This is the primary HTTP interface for the /// data and execution clients.

Docstring for the class provided on the struct or enum. Read more
Source§

const DOC: &'static CStr

Fully rendered class doc, including the text_signature if a constructor is defined. Read more
Source§

type Layout = <<CoinbaseHttpClient as PyClassImpl>::BaseNativeType as PyClassBaseType>::Layout<CoinbaseHttpClient>

Description of how this class is laid out in memory
Source§

type BaseType = PyAny

Base class
Source§

type ThreadChecker = NoopThreadChecker

This handles following two situations: Read more
Source§

type Inventory = Pyo3MethodsInventoryForCoinbaseHttpClient

Source§

type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild

Immutable or mutable
Source§

type Dict = PyClassDummySlot

Specify this class has #[pyclass(dict)] or not.
Source§

type WeakRef = PyClassDummySlot

Specify this class has #[pyclass(weakref)] or not.
Source§

type BaseNativeType = PyAny

The closest native ancestor. This is PyAny by default, and when you declare #[pyclass(extends=PyDict)], it’s PyDict.
Source§

fn items_iter() -> PyClassItemsIter

Source§

fn lazy_type_object() -> &'static LazyTypeObject<Self>

§

fn dict_offset() -> Option<PyObjectOffset>

Used to provide the dictoffset slot (equivalent to tp_dictoffset)
§

fn weaklist_offset() -> Option<PyObjectOffset>

Used to provide the weaklistoffset slot (equivalent to tp_weaklistoffset
Source§

impl PyStubType for CoinbaseHttpClient

Source§

fn type_output() -> TypeInfo

The type to be used in the output signature, i.e. return type of the Python function or methods.
§

fn type_input() -> TypeInfo

The type to be used in the input signature, i.e. the arguments of the Python function or methods. Read more
Source§

impl PyTypeInfo for CoinbaseHttpClient

Source§

const NAME: &str = <Self as ::pyo3::PyClass>::NAME

👎Deprecated since 0.28.0:

prefer using ::type_object(py).name() to get the correct runtime value

Class name.
Source§

const MODULE: Option<&str> = <Self as ::pyo3::impl_::pyclass::PyClassImpl>::MODULE

👎Deprecated since 0.28.0:

prefer using ::type_object(py).module() to get the correct runtime value

Module name, if any.
Source§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
§

fn type_object(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
§

fn is_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
§

fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.
Source§

impl DerefToPyAny for CoinbaseHttpClient

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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 T
where T: IntoPyObject<'py>,

§

fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>

Converts self into an owned Python object, dropping type information.
§

fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>

Converts 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>

Converts self into a Python object. Read more
§

impl<'py, T> IntoPyObjectNautilusExt<'py> for T
where T: IntoPyObjectExt<'py>,

§

fn into_py_any_unwrap(self, py: Python<'py>) -> Py<PyAny>

Convert self into a [Py<PyAny>] while panicking if the conversion fails. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
§

impl<T> PyErrArguments for T
where T: for<'py> IntoPyObject<'py> + Send + Sync,

§

fn arguments(self, py: Python<'_>) -> Py<PyAny>

Arguments for exception
§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

§

const NAME: &'static str = T::NAME

👎Deprecated since 0.27.0:

Use ::classinfo_object() instead and format the type name at runtime. Note that using built-in cast features is often better than manual PyTypeCheck usage.

Name of self. This is used in error messages, for example.
§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
§

fn classinfo_object(py: Python<'_>) -> Bound<'_, PyAny>

Returns the expected type as a possible argument for the isinstance and issubclass function. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<'py, T> FromPyObjectOwned<'py> for T
where T: for<'a> FromPyObject<'a, 'py>,

§

impl<T> Ungil for T
where T: Send,