BaseExchange

Struct BaseExchange 

Source
pub struct BaseExchange {
    pub config: ExchangeConfig,
    pub http_client: HttpClient,
    pub rate_limiter: Option<RateLimiter>,
    pub market_cache: Arc<RwLock<MarketCache>>,
    pub capabilities: ExchangeCapabilities,
    pub urls: HashMap<String, String>,
    pub timeframes: HashMap<String, String>,
    pub precision_mode: PrecisionMode,
}
Expand description

Base exchange implementation

Fields§

§config: ExchangeConfig

Exchange configuration

§http_client: HttpClient

HTTP client for API requests

§rate_limiter: Option<RateLimiter>

Rate limiter instance

§market_cache: Arc<RwLock<MarketCache>>

Thread-safe market data cache

§capabilities: ExchangeCapabilities

Exchange capability flags

§urls: HashMap<String, String>

API endpoint URLs

§timeframes: HashMap<String, String>

Timeframe mappings (e.g., “1m” -> “1”)

§precision_mode: PrecisionMode

Precision mode for price/amount formatting

Implementations§

Source§

impl BaseExchange

Source

pub fn new(config: ExchangeConfig) -> Result<Self>

Creates a new exchange instance

§Arguments
  • config - Exchange configuration
§Returns

Returns a Result containing the initialized exchange instance.

§Errors

Returns an error if HTTP client or rate limiter initialization fails.

Source

pub async fn load_markets( &self, reload: bool, ) -> Result<HashMap<String, Market>>

Loads market data from the exchange

§Arguments
  • reload - Whether to force reload even if markets are already cached
§Returns

Returns a HashMap of markets indexed by symbol.

§Errors

Returns an error if market data cannot be fetched. This base implementation always returns NotImplemented error as exchanges must override this method.

Source

pub async fn set_markets( &self, markets: Vec<Market>, currencies: Option<Vec<Currency>>, ) -> Result<Vec<Market>>

Sets market and currency data in the cache

§Arguments
  • markets - Vector of market definitions to cache
  • currencies - Optional vector of currency definitions to cache
§Returns

Returns Ok(markets) on successful cache update, preserving ownership for the caller.

§Errors

This method should not fail under normal circumstances.

Source

pub async fn market(&self, symbol: &str) -> Result<Market>

Gets market information by trading symbol

§Arguments
  • symbol - Trading pair symbol (e.g., “BTC/USDT”)
§Returns

Returns the market definition for the specified symbol.

§Errors

Returns an error if markets are not loaded or the symbol is not found.

Source

pub async fn market_by_id(&self, id: &str) -> Result<Market>

Gets market information by exchange-specific market ID

§Arguments
  • id - Exchange-specific market identifier
§Returns

Returns the market definition for the specified ID.

§Errors

Returns an error if the market ID is not found.

Source

pub async fn currency(&self, code: &str) -> Result<Currency>

Gets currency information by currency code

§Arguments
  • code - Currency code (e.g., “BTC”, “USDT”)
§Returns

Returns the currency definition for the specified code.

§Errors

Returns an error if the currency is not found.

Source

pub async fn symbols(&self) -> Result<Vec<String>>

Gets all available trading symbols

§Returns

Returns a vector of all trading pair symbols.

Source

pub async fn throttle(&self) -> Result<()>

Applies rate limiting if enabled

Blocks until rate limit quota is available.

§Returns

Returns Ok(()) after rate limit check passes.

Source

pub fn check_required_credentials(&self) -> Result<()>

Checks that required API credentials are configured

§Returns

Returns Ok(()) if both API key and secret are present.

§Errors

Returns an authentication error if credentials are missing.

Source

pub fn nonce(&self) -> i64

Gets a nonce value (current timestamp in milliseconds)

§Returns

Returns current Unix timestamp in milliseconds.

Source

pub fn build_query_string(&self, params: &HashMap<String, Value>) -> String

Builds a URL query string from parameters

§Arguments
  • params - Parameter key-value pairs
§Returns

Returns a URL-encoded query string (e.g., “key1=value1&key2=value2”).

Source

pub fn parse_json(&self, response: &str) -> Result<Value>

Parses a JSON response string

§Arguments
  • response - JSON string to parse
§Returns

Returns the parsed Value on success.

§Errors

Returns an error if JSON parsing fails.

Source

pub fn handle_http_error(&self, status_code: u16, response: &str) -> Error

Handles HTTP error responses by mapping status codes to appropriate errors

§Arguments
  • status_code - HTTP status code
  • response - Response body text
§Returns

Returns an appropriate Error variant based on the status code.

Source

pub fn safe_string(&self, dict: &Value, key: &str) -> Option<String>

Safely extracts a string value from a JSON object

§Arguments
  • dict - JSON value to extract from
  • key - Key to look up
§Returns

Returns Some(String) if the key exists and value is a string, None otherwise.

Source

pub fn safe_integer(&self, dict: &Value, key: &str) -> Option<i64>

Safely extracts an integer value from a JSON object

§Arguments
  • dict - JSON value to extract from
  • key - Key to look up
§Returns

Returns Some(i64) if the key exists and value is an integer, None otherwise.

Source

pub fn safe_float(&self, dict: &Value, key: &str) -> Option<f64>

Safely extracts a float value from a JSON object

§Arguments
  • dict - JSON value to extract from
  • key - Key to look up
§Returns

Returns Some(f64) if the key exists and value is a float, None otherwise.

Source

pub fn safe_bool(&self, dict: &Value, key: &str) -> Option<bool>

Safely extracts a boolean value from a JSON object

§Arguments
  • dict - JSON value to extract from
  • key - Key to look up
§Returns

Returns Some(bool) if the key exists and value is a boolean, None otherwise.

Source

pub fn parse_ticker( &self, ticker_data: &Value, market: Option<&Market>, ) -> Result<Ticker>

Parses raw ticker data from exchange API response

§Arguments
  • ticker_data - Raw ticker JSON data from exchange
  • market - Optional market information to populate symbol field
§Returns

Returns a parsed Ticker struct.

§Errors

Returns an error if required fields are missing.

Source

pub fn parse_trade( &self, trade_data: &Value, market: Option<&Market>, ) -> Result<Trade>

Parses raw trade data from exchange API response

§Arguments
  • trade_data - Raw trade JSON data from exchange
  • market - Optional market information to populate symbol field
§Returns

Returns a parsed Trade struct.

§Errors

Returns an error if required fields (symbol, side) are missing.

Source

pub fn parse_order( &self, order_data: &Value, market: Option<&Market>, ) -> Result<Order>

Parses raw order data from exchange API response

§Arguments
  • order_data - Raw order JSON data from exchange
  • market - Optional market information to populate symbol field
§Returns

Returns a parsed Order struct with all available fields populated.

Source

pub fn parse_balance(&self, balance_data: &Value) -> Result<Balance>

Parses raw balance data from exchange API response

§Arguments
  • balance_data - Raw balance JSON data from exchange
§Returns

Returns a Balance map containing all currency balances with free, used, and total amounts.

Source

pub fn parse_order_book( &self, orderbook_data: &Value, timestamp: Option<i64>, ) -> Result<OrderBook>

Parses raw order book data from exchange API response

§Arguments
  • orderbook_data - Raw order book JSON data from exchange
  • timestamp - Optional timestamp for the order book snapshot
§Returns

Returns a parsed OrderBook struct containing bid and ask sides.

Source

pub async fn calculate_fee( &self, symbol: &str, _order_type: OrderType, _side: OrderSide, amount: Decimal, price: Decimal, taker_or_maker: Option<&str>, ) -> Result<Fee>

Calculates trading fee for a given order

§Arguments
  • symbol - Trading pair symbol
  • order_type - Order type (limit, market, etc.)
  • side - Order side (buy or sell)
  • amount - Trade amount in base currency
  • price - Trade price in quote currency
  • taker_or_maker - Optional taker or maker designation
§Returns

Returns a Fee struct containing the currency, cost, and rate.

Source

pub async fn amount_to_precision( &self, symbol: &str, amount: Decimal, ) -> Result<Decimal>

Converts an amount to the precision required by the market

Source

pub async fn price_to_precision( &self, symbol: &str, price: Decimal, ) -> Result<Decimal>

Converts a price to the precision required by the market

Source

pub async fn cost_to_precision( &self, symbol: &str, cost: Decimal, ) -> Result<Decimal>

Converts a cost to the precision required by the market

Source

pub async fn calculate_cost( &self, symbol: &str, amount: Decimal, price: Decimal, ) -> Result<Decimal>

Calculates the cost of a trade

§Arguments
  • symbol - Trading pair symbol
  • amount - Trade amount in base currency
  • price - Trade price in quote currency
§Returns

Returns the total cost (amount × price) in quote currency.

Trait Implementations§

Source§

impl Debug for BaseExchange

Source§

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

Formats the value using the given formatter. 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<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: 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: 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> Same for T

Source§

type Output = T

Should always be Self
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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