pub struct Okx { /* private fields */ }Expand description
OKX exchange structure.
Implementations§
Source§impl Okx
impl Okx
Sourcepub fn get_auth(&self) -> Result<OkxAuth, Error>
pub fn get_auth(&self) -> Result<OkxAuth, Error>
Get the authentication instance if credentials are configured.
Sourcepub fn check_required_credentials(&self) -> Result<(), Error>
pub fn check_required_credentials(&self) -> Result<(), Error>
Check that required credentials are configured.
Sourcepub fn get_inst_type(&self) -> &str
pub fn get_inst_type(&self) -> &str
Get the instrument type for API requests.
Maps the configured default_type to OKX’s instrument type (instType) parameter.
OKX uses a unified V5 API, so this primarily affects market filtering.
§Returns
Returns the OKX instrument type string:
- “SPOT” for spot trading
- “MARGIN” for margin trading
- “SWAP” for perpetual contracts
- “FUTURES” for delivery contracts
- “OPTION” for options trading
Sourcepub async fn fetch_markets(
&self,
) -> Result<Arc<HashMap<String, Arc<Market>>>, Error>
pub async fn fetch_markets( &self, ) -> Result<Arc<HashMap<String, Arc<Market>>>, Error>
Fetch all trading markets.
§Returns
Returns a vector of Market structures containing market information.
§Errors
Returns an error if the API request fails or response parsing fails.
§Example
let okx = Okx::builder().build()?;
let markets = okx.fetch_markets().await?;
println!("Found {} markets", markets.len());Sourcepub async fn load_markets(
&self,
reload: bool,
) -> Result<Arc<HashMap<String, Arc<Market>>>, Error>
pub async fn load_markets( &self, reload: bool, ) -> Result<Arc<HashMap<String, Arc<Market>>>, Error>
Sourcepub async fn fetch_tickers(
&self,
symbols: Option<Vec<String>>,
) -> Result<Vec<Ticker>, Error>
pub async fn fetch_tickers( &self, symbols: Option<Vec<String>>, ) -> Result<Vec<Ticker>, Error>
Sourcepub async fn fetch_order_book(
&self,
symbol: &str,
limit: Option<u32>,
) -> Result<OrderBook, Error>
pub async fn fetch_order_book( &self, symbol: &str, limit: Option<u32>, ) -> Result<OrderBook, Error>
Sourcepub async fn fetch_trades(
&self,
symbol: &str,
limit: Option<u32>,
) -> Result<Vec<Trade>, Error>
pub async fn fetch_trades( &self, symbol: &str, limit: Option<u32>, ) -> Result<Vec<Trade>, Error>
Sourcepub async fn fetch_ohlcv_v2(
&self,
request: OhlcvRequest,
) -> Result<Vec<OHLCV>, Error>
pub async fn fetch_ohlcv_v2( &self, request: OhlcvRequest, ) -> Result<Vec<OHLCV>, Error>
Fetch OHLCV (candlestick) data using the builder pattern.
This is the preferred method for fetching OHLCV data. It accepts an OhlcvRequest
built using the builder pattern, which provides validation and a more ergonomic API.
§Arguments
request- OHLCV request built viaOhlcvRequest::builder()
§Returns
Returns a vector of OHLCV structures.
§Errors
Returns an error if the market is not found or the API request fails.
Requirements: 2.3, 2.6
Sourcepub async fn fetch_ohlcv(
&self,
symbol: &str,
timeframe: &str,
since: Option<i64>,
limit: Option<u32>,
) -> Result<Vec<OHLCV>, Error>
👎Deprecated since 0.2.0: Use fetch_ohlcv_v2 with OhlcvRequest::builder() instead
pub async fn fetch_ohlcv( &self, symbol: &str, timeframe: &str, since: Option<i64>, limit: Option<u32>, ) -> Result<Vec<OHLCV>, Error>
Fetch OHLCV (candlestick) data (deprecated).
§Deprecated
This method is deprecated. Use fetch_ohlcv_v2 with
OhlcvRequest::builder() instead for a more ergonomic API.
§Arguments
symbol- Trading pair symbol.timeframe- Candlestick timeframe (e.g., “1m”, “5m”, “1h”, “1d”).since- Optional start timestamp in milliseconds.limit- Optional limit on number of candles (maximum: 300).
§Returns
Returns a vector of OHLCV structures.
Sourcepub async fn fetch_balance(&self) -> Result<Balance, Error>
pub async fn fetch_balance(&self) -> Result<Balance, Error>
Sourcepub async fn fetch_my_trades(
&self,
symbol: &str,
since: Option<i64>,
limit: Option<u32>,
) -> Result<Vec<Trade>, Error>
pub async fn fetch_my_trades( &self, symbol: &str, since: Option<i64>, limit: Option<u32>, ) -> Result<Vec<Trade>, Error>
Sourcepub async fn create_order_v2(
&self,
request: OrderRequest,
) -> Result<Order, Error>
pub async fn create_order_v2( &self, request: OrderRequest, ) -> Result<Order, Error>
Create a new order using the builder pattern.
This is the preferred method for creating orders. It accepts an OrderRequest
built using the builder pattern, which provides compile-time validation of
required fields and a more ergonomic API.
§Arguments
request- Order request built viaOrderRequest::builder()
§Returns
Returns the created Order structure with order details.
§Errors
Returns an error if authentication fails, market is not found, or the API request fails.
Requirements: 2.2, 2.6
Sourcepub async fn create_order(
&self,
symbol: &str,
order_type: OrderType,
side: OrderSide,
amount: Amount,
price: Option<Price>,
) -> Result<Order, Error>
👎Deprecated since 0.2.0: Use create_order_v2 with OrderRequest::builder() instead
pub async fn create_order( &self, symbol: &str, order_type: OrderType, side: OrderSide, amount: Amount, price: Option<Price>, ) -> Result<Order, Error>
Create a new order (deprecated).
§Deprecated
This method is deprecated. Use create_order_v2 with
OrderRequest::builder() instead for a more ergonomic API.
§Arguments
symbol- Trading pair symbol.order_type- Order type (Market, Limit).side- Order side (Buy or Sell).amount- Order quantity.price- Optional price (required for limit orders).
§Returns
Returns the created Order structure with order details.
Sourcepub async fn fetch_open_orders(
&self,
symbol: Option<&str>,
since: Option<i64>,
limit: Option<u32>,
) -> Result<Vec<Order>, Error>
pub async fn fetch_open_orders( &self, symbol: Option<&str>, since: Option<i64>, limit: Option<u32>, ) -> Result<Vec<Order>, Error>
Source§impl Okx
impl Okx
Sourcepub fn builder() -> OkxBuilder
pub fn builder() -> OkxBuilder
Creates a new OKX instance using the builder pattern.
This is the recommended way to create an OKX instance.
§Example
use ccxt_exchanges::okx::Okx;
let okx = Okx::builder()
.api_key("your-api-key")
.secret("your-secret")
.passphrase("your-passphrase")
.sandbox(true)
.build()
.unwrap();Sourcepub fn new_with_options(
config: ExchangeConfig,
options: OkxOptions,
) -> Result<Okx, Error>
pub fn new_with_options( config: ExchangeConfig, options: OkxOptions, ) -> Result<Okx, Error>
Creates a new OKX instance with custom options.
This is used internally by the builder pattern.
§Arguments
config- Exchange configuration.options- OKX-specific options.
Sourcepub fn base(&self) -> &BaseExchange
pub fn base(&self) -> &BaseExchange
Returns a reference to the base exchange.
Sourcepub fn base_mut(&mut self) -> &mut BaseExchange
pub fn base_mut(&mut self) -> &mut BaseExchange
Returns a mutable reference to the base exchange.
Sourcepub fn options(&self) -> &OkxOptions
pub fn options(&self) -> &OkxOptions
Returns the OKX options.
Sourcepub fn set_options(&mut self, options: OkxOptions)
pub fn set_options(&mut self, options: OkxOptions)
Sets the OKX options.
Sourcepub fn rate_limit(&self) -> u32
pub fn rate_limit(&self) -> u32
Returns the rate limit in requests per second.
Sourcepub fn is_sandbox(&self) -> bool
pub fn is_sandbox(&self) -> bool
Returns true if sandbox/demo mode is enabled.
Sandbox mode is enabled when either:
config.sandboxis set totrueoptions.demois set totrue
§Returns
true if sandbox mode is enabled, false otherwise.
§Example
use ccxt_exchanges::okx::Okx;
use ccxt_core::ExchangeConfig;
let config = ExchangeConfig {
sandbox: true,
..Default::default()
};
let okx = Okx::new(config).unwrap();
assert!(okx.is_sandbox());Sourcepub fn is_testnet_trading(&self) -> bool
pub fn is_testnet_trading(&self) -> bool
Returns true if demo trading mode is enabled.
This is an OKX-specific alias for is_sandbox(). Demo trading mode
is enabled when either:
config.sandboxis set totrueoptions.demois set totrue
When demo trading is enabled, the client will:
- Add the
x-simulated-trading: 1header to all REST API requests - Use demo WebSocket URLs (
wss://wspap.okx.com:8443/ws/v5/*?brokerId=9999) - Continue using the production REST domain (
https://www.okx.com)
§Returns
true if demo trading mode is enabled, false otherwise.
§Example
use ccxt_exchanges::okx::Okx;
use ccxt_core::ExchangeConfig;
let config = ExchangeConfig {
sandbox: true,
..Default::default()
};
let okx = Okx::new(config).unwrap();
assert!(okx.is_testnet_trading());Sourcepub fn timeframes(&self) -> HashMap<String, String>
pub fn timeframes(&self) -> HashMap<String, String>
Returns the supported timeframes.
Sourcepub fn default_type(&self) -> DefaultType
pub fn default_type(&self) -> DefaultType
Returns the default type configuration.
Sourcepub fn default_sub_type(&self) -> Option<DefaultSubType>
pub fn default_sub_type(&self) -> Option<DefaultSubType>
Returns the default sub-type configuration.
Sourcepub fn is_contract_type(&self) -> bool
pub fn is_contract_type(&self) -> bool
Checks if the current default_type is a contract type (Swap, Futures, or Option).
This is useful for determining whether contract-specific API parameters should be used.
§Returns
true if the default_type is Swap, Futures, or Option; false otherwise.
Sourcepub fn is_inverse(&self) -> bool
pub fn is_inverse(&self) -> bool
Checks if the current configuration uses inverse (coin-margined) contracts.
§Returns
true if default_sub_type is Inverse; false otherwise.
Sourcepub fn is_linear(&self) -> bool
pub fn is_linear(&self) -> bool
Checks if the current configuration uses linear (USDT-margined) contracts.
§Returns
true if default_sub_type is Linear or not specified (defaults to Linear); false otherwise.
Sourcepub fn create_ws(&self) -> OkxWs
pub fn create_ws(&self) -> OkxWs
Creates a new WebSocket client for OKX.
Returns an OkxWs instance configured with the appropriate WebSocket URL
based on the exchange configuration (production or demo).
§Example
use ccxt_exchanges::okx::Okx;
use ccxt_core::ExchangeConfig;
let okx = Okx::new(ExchangeConfig::default())?;
let ws = okx.create_ws();
ws.connect().await?;Sourcepub fn signed_request(
&self,
endpoint: impl Into<String>,
) -> OkxSignedRequestBuilder<'_>
pub fn signed_request( &self, endpoint: impl Into<String>, ) -> OkxSignedRequestBuilder<'_>
Creates a new signed request builder for authenticated API requests.
This builder encapsulates the common signing workflow for OKX API requests, including credential validation, timestamp generation, HMAC-SHA256 signing, and authentication header injection.
§Arguments
endpoint- API endpoint path (e.g., “/api/v5/account/balance”)
§Returns
A OkxSignedRequestBuilder instance for fluent API construction.
§Example
use ccxt_exchanges::okx::Okx;
use ccxt_exchanges::okx::signed_request::HttpMethod;
use ccxt_core::ExchangeConfig;
let okx = Okx::new(ExchangeConfig::default())?;
// Simple GET request
let data = okx.signed_request("/api/v5/account/balance")
.execute()
.await?;
// POST request with parameters
let data = okx.signed_request("/api/v5/trade/order")
.method(HttpMethod::Post)
.param("instId", "BTC-USDT")
.param("tdMode", "cash")
.param("side", "buy")
.execute()
.await?;