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 (const: unstable) · 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

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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.

Source§

impl<T> Instrument for T

Source§

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

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

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + 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
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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.
Source§

impl<T> WithSubscriber for T

Source§

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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