// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
pub struct OkxCore {
pub exchange: crate::exchange::Exchange,
}
impl OkxCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::exchange::Exchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = OkxCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for OkxCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_funding_rate(self, rate, &[market])
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_deposit_address(self, depositAddress, &[currency])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_transfer(self, transfer, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_open_interest(self, interest, &[market])
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_margin_modification(self, data, &[market])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_transaction(self, transaction, &[currency])
}
fn parse_borrow_interest(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_borrow_interest(self, info, &[market])
}
fn parse_greeks(&self, greeks: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_greeks(self, greeks, &[market])
}
fn parse_conversion(&self, conversion: crate::Value, from_currency: crate::Value, to_currency: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_conversion(self, conversion, &[from_currency, to_currency])
}
fn parse_borrow_rate(&self, info: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_borrow_rate(self, info, &[currency])
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_leverage(self, leverage, &[market])
}
fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::parse_market_leverage_tiers(self, info, &[market])
}
fn create_expired_option_market(&self, symbol: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::create_expired_option_market(self, symbol)
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on OkxCore.
OkxCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for OkxCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"borrow_cross_margin" => self.borrow_cross_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"cancel_all_orders_after" => self.cancel_all_orders_after(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders_for_symbols" => self.cancel_orders_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"close_position" => self.close_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"convert_to_instrument_type" => self.convert_to_instrument_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"create_convert_trade" => self.create_convert_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"create_expired_option_market" => self.create_expired_option_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_market_sell_order_with_cost" => self.create_market_sell_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_order_request" => self.edit_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"fetch_accounts" => self.fetch_accounts(&args[..]).await,
"fetch_all_greeks" => self.fetch_all_greeks(&args[..]).await,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_borrow_interest" => self.fetch_borrow_interest(&args[..]).await,
"fetch_borrow_rate_histories" => self.fetch_borrow_rate_histories(&args[..]).await,
"fetch_borrow_rate_history" => self.fetch_borrow_rate_history(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_convert_currencies" => self.fetch_convert_currencies(&args[..]).await,
"fetch_convert_quote" => self.fetch_convert_quote(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"fetch_convert_trade" => self.fetch_convert_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_convert_trade_history" => self.fetch_convert_trade_history(&args[..]).await,
"fetch_cross_borrow_rate" => self.fetch_cross_borrow_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_cross_borrow_rates" => self.fetch_cross_borrow_rates(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposit" => self.fetch_deposit(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_address" => self.fetch_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_addresses_by_network" => self.fetch_deposit_addresses_by_network(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_withdraw_fees" => self.fetch_deposit_withdraw_fees(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_interval" => self.fetch_funding_interval(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args[..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_greeks" => self.fetch_greeks(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_ledger" => self.fetch_ledger(&args[..]).await,
"fetch_leverage" => self.fetch_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_long_short_ratio_history" => self.fetch_long_short_ratio_history(&args[..]).await,
"fetch_margin_adjustment_history" => self.fetch_margin_adjustment_history(&args[..]).await,
"fetch_mark_price" => self.fetch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_mark_prices" => self.fetch_mark_prices(&args[..]).await,
"fetch_market_leverage_tiers" => self.fetch_market_leverage_tiers(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_markets_by_type" => self.fetch_markets_by_type(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest_history" => self.fetch_open_interest_history(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interests" => self.fetch_open_interests(&args[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_option" => self.fetch_option(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_option_chain" => self.fetch_option_chain(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_trades" => self.fetch_order_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_position_mode" => self.fetch_position_mode(&args[..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_positions_for_symbol" => self.fetch_positions_for_symbol(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions_history" => self.fetch_positions_history(&args[..]).await,
"fetch_settlement_history" => self.fetch_settlement_history(&args[..]).await,
"fetch_status" => self.fetch_status(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_transfer" => self.fetch_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_transfers" => self.fetch_transfers(&args[..]).await,
"fetch_underlying_assets" => self.fetch_underlying_assets(&args[..]).await,
"fetch_withdrawal" => self.fetch_withdrawal(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"handle_market_type_and_params" => self.handle_market_type_and_params(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"handle_trading_statistics_window" => self.handle_trading_statistics_window(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]),
"modify_margin_helper" => self.modify_margin_helper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"nonce" => self.nonce(),
"parse_balance_by_type" => self.parse_balance_by_type(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_borrow_interest" => self.parse_borrow_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_borrow_rate" => self.parse_borrow_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_borrow_rate_histories" => self.parse_borrow_rate_histories(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null)),
"parse_conversion" => self.parse_conversion(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_deposit_address" => self.parse_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_deposit_withdraw_fees" => self.parse_deposit_withdraw_fees(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_funding_balance" => self.parse_funding_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_greeks" => self.parse_greeks(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ids" => self.parse_ids(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_leverage" => self.parse_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_long_short_ratio" => self.parse_long_short_ratio(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_loan" => self.parse_margin_loan(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_market_leverage_tiers" => self.parse_market_leverage_tiers(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_option" => self.parse_option(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_settlement" => self.parse_settlement(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_settlements" => self.parse_settlements(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trading_balance" => self.parse_trading_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_trading_fee" => self.parse_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"reduce_margin" => self.reduce_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"repay_cross_margin" => self.repay_cross_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"safe_market" => self.safe_market(&args[..]),
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_position_mode" => self.set_position_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"transfer" => self.transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for OkxCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for OkxCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl OkxCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.super_describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("okx".into()));
m.insert("name".to_string(), Value::Str("OKX".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("CN".into()), Value::Str("US".into())]));
m.insert("version".to_string(), Value::Str("v5".into()));
m.insert("rateLimit".to_string(), (match (&(Value::Int(100)), &(Value::Float(1.1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("certified".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(true));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(true));
m.insert("option".to_string(), Value::Bool(true));
m.insert("addMargin".to_string(), Value::Bool(true));
m.insert("borrowCrossMargin".to_string(), Value::Bool(true));
m.insert("cancelAllOrders".to_string(), Value::Bool(false));
m.insert("cancelAllOrdersAfter".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("cancelOrdersForSymbols".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(true));
m.insert("createConvertTrade".to_string(), Value::Bool(true));
m.insert("createDepositAddress".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(true));
m.insert("createPostOnlyOrder".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopLimitOrder".to_string(), Value::Bool(true));
m.insert("createStopLossOrder".to_string(), Value::Bool(true));
m.insert("createStopMarketOrder".to_string(), Value::Bool(true));
m.insert("createStopOrder".to_string(), Value::Bool(true));
m.insert("createTakeProfitOrder".to_string(), Value::Bool(true));
m.insert("createTrailingPercentOrder".to_string(), Value::Bool(true));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(true));
m.insert("fetchAllGreeks".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBidsAsks".to_string(), Value::Null);
m.insert("fetchBorrowInterest".to_string(), Value::Bool(true));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(true));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(true));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(true));
m.insert("fetchClosedOrder".to_string(), Value::Null);
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchConvertCurrencies".to_string(), Value::Bool(true));
m.insert("fetchConvertQuote".to_string(), Value::Bool(true));
m.insert("fetchConvertTrade".to_string(), Value::Bool(true));
m.insert("fetchConvertTradeHistory".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(true));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDeposit".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(true));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(true));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositsWithdrawals".to_string(), Value::Bool(false));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Str("emulated".into()));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingInterval".to_string(), Value::Bool(true));
m.insert("fetchFundingIntervals".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchGreeks".to_string(), Value::Bool(true));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(true));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchL3OrderBook".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLedgerEntry".to_string(), Value::Null);
m.insert("fetchLeverage".to_string(), Value::Bool(true));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchLongShortRatio".to_string(), Value::Bool(false));
m.insert("fetchLongShortRatioHistory".to_string(), Value::Bool(true));
m.insert("fetchMarginAdjustmentHistory".to_string(), Value::Bool(true));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(true));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(true));
m.insert("fetchMarkPrice".to_string(), Value::Bool(true));
m.insert("fetchMarkPrices".to_string(), Value::Bool(true));
m.insert("fetchMySettlementHistory".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(true));
m.insert("fetchOpenInterests".to_string(), Value::Bool(true));
m.insert("fetchOpenOrder".to_string(), Value::Null);
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOption".to_string(), Value::Bool(true));
m.insert("fetchOptionChain".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrderBooks".to_string(), Value::Bool(false));
m.insert("fetchOrders".to_string(), Value::Bool(false));
m.insert("fetchOrderTrades".to_string(), Value::Bool(true));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositionHistory".to_string(), Value::Str("emulated".into()));
m.insert("fetchPositionMode".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsForSymbol".to_string(), Value::Bool(true));
m.insert("fetchPositionsHistory".to_string(), Value::Bool(true));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchSettlementHistory".to_string(), Value::Bool(true));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(true));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTradingLimits".to_string(), Value::Bool(false));
m.insert("fetchTransactionFee".to_string(), Value::Bool(false));
m.insert("fetchTransactionFees".to_string(), Value::Bool(false));
m.insert("fetchTransactions".to_string(), Value::Bool(false));
m.insert("fetchTransfer".to_string(), Value::Bool(true));
m.insert("fetchTransfers".to_string(), Value::Bool(true));
m.insert("fetchUnderlyingAssets".to_string(), Value::Bool(true));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawal".to_string(), Value::Bool(true));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("fetchWithdrawalWhitelist".to_string(), Value::Bool(false));
m.insert("reduceMargin".to_string(), Value::Bool(true));
m.insert("repayCrossMargin".to_string(), Value::Bool(true));
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMargin".to_string(), Value::Bool(false));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(true));
m.insert("signIn".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".into()));
m.insert("3m".to_string(), Value::Str("3m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15m".to_string(), Value::Str("15m".into()));
m.insert("30m".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1H".into()));
m.insert("2h".to_string(), Value::Str("2H".into()));
m.insert("4h".to_string(), Value::Str("4H".into()));
m.insert("6h".to_string(), Value::Str("6H".into()));
m.insert("12h".to_string(), Value::Str("12H".into()));
m.insert("1d".to_string(), Value::Str("1D".into()));
m.insert("1w".to_string(), Value::Str("1W".into()));
m.insert("1M".to_string(), Value::Str("1M".into()));
m.insert("3M".to_string(), Value::Str("3M".into()));
m
}));
m.insert("hostname".to_string(), Value::Str("www.okx.com".into()));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://user-images.githubusercontent.com/1294454/152485636-38b19e4a-bece-4dec-979a-5982859ffc04.jpg".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rest".to_string(), Value::Str("https://{hostname}".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.okx.com".into()));
m.insert("doc".to_string(), Value::Str("https://www.okx.com/docs-v5/en/".into()));
m.insert("fees".to_string(), Value::Str("https://www.okx.com/pages/products/fees.html".into()));
m.insert("referral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str("https://www.okx.com/join/CCXTCOM".into()));
m.insert("discount".to_string(), Value::Float(0.2));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rest".to_string(), Value::Str("https://{hostname}".into()));
m
}));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market/tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/books".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("market/books-full".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("market/books-rpi".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("market/candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("market/history-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(5)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("market/history-trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("market/option/instrument-family-trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/platform-24-volume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("market/call-auction-detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/call-auction-details".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/books-sbe".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("market/block-tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/block-ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/sprd-ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/sprd-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("market/sprd-history-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/index-tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/index-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/history-index-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("market/mark-price-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/history-mark-price-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/exchange-rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("market/index-components".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/open-oracle".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("market/books-lite".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("public/option-trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/block-trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/estimated-price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("public/delivery-exercise-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("public/estimated-settlement-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("public/settlement-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("public/funding-rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("public/funding-rate-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("public/open-interest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/price-limit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/opt-summary".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/discount-rate-interest-free-quota".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("public/time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("public/mark-price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("public/position-tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("public/interest-rate-loan-quota".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("public/underlying".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/insurance-fund".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("public/convert-contract-coin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("public/instrument-tick-bands".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("public/premium-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/economic-calendar".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("public/market-data-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("public/event-contract/events".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/event-contract/markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/event-contract/series".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("public/vip-interest-rate-loan-quota".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("public/mm-instrument-types".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("public/delta-hedge-currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rubik/stat/trading-data/support-coin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/contracts/open-interest-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("rubik/stat/taker-volume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/taker-volume-contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/margin/loan-ratio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/contracts/long-short-account-ratio-contract-top-trader".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/contracts/long-short-position-ratio-contract-top-trader".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/contracts/long-short-account-ratio-contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/contracts/long-short-account-ratio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/contracts/open-interest-volume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/option/open-interest-volume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/option/open-interest-volume-ratio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/option/open-interest-volume-expiry".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/option/open-interest-volume-strike".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rubik/stat/option/taker-block-volume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("system/status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("sprd/spreads".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/books".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/public-trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/ai-param".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/min-investment".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/public/rsi-back-testing".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/grid-quantity".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("asset/exchange-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/eth/apy-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/sol/apy-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/savings/lending-rate-summary".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/savings/lending-rate-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/fixed-loan/lending-offers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/fixed-loan/lending-apy-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/fixed-loan/pending-lending-volume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/sfp/dcd/products".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(2)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("copytrading/public-config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/public-lead-traders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/public-weekly-pnl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/public-pnl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/public-stats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/public-preference-currency".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/public-current-subpositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/public-subpositions-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/public-copy-traders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("support/announcements".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("support/announcements-types".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("support/announcement-types".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tradingBot/grid/min-investment".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rfq/counterparties".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rfq/maker-instrument-settings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rfq/mmp-config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rfq/rfqs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("rfq/quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("rfq/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rfq/public-trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("sprd/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/orders-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("sprd/orders-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/orders-history-archive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/orders-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/orders-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(2)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/orders-history-archive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/fills-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/fills-archive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("trade/order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-algo-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-algo-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/easy-convert-currency-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("trade/easy-convert-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("trade/one-click-repay-currency-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("trade/one-click-repay-currency-list-v2".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("trade/one-click-repay-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("trade/one-click-repay-history-v2".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("trade/account-rate-limit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/balances".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/non-tradable-assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/asset-valuation".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("asset/transfer-state".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/bills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/bills-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("asset/deposit-lightning".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("asset/deposit-address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/deposit-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/withdrawal-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/deposit-withdraw-status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("asset/monthly-statement".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("asset/convert/currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/convert/currency-pair".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/convert/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/deposit-payment-methods".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/withdrawal-payment-methods".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/deposit-order-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/withdrawal-order-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/buy-sell/currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/buy-sell/currency-pair".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/buy-sell/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("account/instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/positions-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/account-position-risk".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/bills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/bills-archive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/bills-history-archive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/subtypes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/max-size".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/max-avail-size".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/leverage-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/adjust-leverage-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/max-loan".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/trade-fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/interest-accrued".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/interest-rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/max-withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/risk-state".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/interest-limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/spot-borrow-repay-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/greeks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/position-tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/set-account-switch-precheck".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/collateral-assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/mmp-config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/move-positions-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/precheck-set-delta-neutral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("account/quick-margin-borrow-repay-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/borrow-repay-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/vip-interest-accrued".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/vip-interest-deducted".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/vip-loan-order-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/vip-loan-order-detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/fixed-loan/borrowing-limit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/fixed-loan/borrowing-quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/fixed-loan/borrowing-orders-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/spot-manual-borrow-repay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(30));
m
}));
m.insert("account/set-auto-repay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("users/subaccount/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/subaccount/balances".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/subaccount/balances".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("account/subaccount/max-withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/subaccount/bills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/subaccount/managed-subaccount-bills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("users/entrust-subaccount-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/subaccount/interest-limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("users/subaccount/apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("tradingBot/grid/orders-algo-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/orders-algo-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/orders-algo-details".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/sub-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/ai-param".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/signals".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/orders-algo-details".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/orders-algo-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/orders-algo-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/positions-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("tradingBot/signal/sub-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/event-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/orders-algo-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/orders-algo-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/orders-algo-details".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/sub-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/ongoing-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/history-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/position-details".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/cycle-list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("finance/savings/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/savings/lending-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/offers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/orders-active".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/orders-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/eth/product-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/eth/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/eth/purchase-redeem-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/sol/product-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/sol/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/sol/purchase-redeem-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/flexible-loan/borrow-currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/flexible-loan/collateral-assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/flexible-loan/max-collateral-redeem-amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/flexible-loan/loan-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/flexible-loan/loan-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/flexible-loan/interest-accrued".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/flexible-loan/emode-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/okusd/limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("finance/okusd/account".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("finance/okusd/subscribe/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/okusd/redeem/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/okusd/rewards/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/okusd/rate/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/stable-rewards/product-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/stable-rewards/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/stable-rewards/apy-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("users/glp/todayperformance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("users/glp/historicalperformance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/current-subpositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/subpositions-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/profit-sharing-details".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/total-profit-sharing".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/unrealized-profit-sharing-details".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/total-unrealized-profit-sharing".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/copy-settings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/current-lead-traders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/batch-leverage-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/lead-traders-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("broker/dma/subaccount-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("broker/dma/subaccount-trade-fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("broker/dma/subaccount/apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("broker/dma/rebate-per-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(300));
m
}));
m.insert("broker/fd/rebate-per-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(300));
m
}));
m.insert("broker/fd/if-rebate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("broker/nd/info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("broker/nd/subaccount-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("broker/nd/subaccount/apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("asset/broker/nd/subaccount-deposit-address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/broker/nd/subaccount-deposit-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("asset/broker/nd/subaccount-withdrawal-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("broker/nd/rebate-daily".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(100));
m
}));
m.insert("broker/nd/rebate-per-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(300));
m
}));
m.insert("finance/sfp/dcd/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("finance/sfp/dcd/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("finance/sfp/dcd/currency-pair".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("finance/sfp/dcd/order-status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("finance/sfp/dcd/order-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("affiliate/invitee/detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("affiliate/performance/summary".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("affiliate/invitee/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("affiliate/link/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("affiliate/co-inviter/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("affiliate/sub-affiliate/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("users/partner/if-rebate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("support/announcements".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rfq/create-rfq".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rfq/cancel-rfq".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rfq/cancel-batch-rfqs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("rfq/cancel-all-rfqs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("rfq/execute-quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(15));
m
}));
m.insert("rfq/maker-instrument-settings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rfq/mmp-reset".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("rfq/mmp-config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(100));
m
}));
m.insert("rfq/create-quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(0.4));
m
}));
m.insert("rfq/cancel-quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(0.4));
m
}));
m.insert("rfq/cancel-batch-quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("rfq/cancel-all-quotes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("rfq/cancel-all-after".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("sprd/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/cancel-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/mass-cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/amend-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sprd/cancel-all-after".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(15)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/cancel-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/cancel-batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(15)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/amend-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/amend-batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(150)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("trade/close-position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/fills-archive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(172800));
m
}));
m.insert("trade/cancel-advance-algos".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/easy-convert".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("trade/one-click-repay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("trade/one-click-repay-v2".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("trade/mass-cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("trade/cancel-all-after".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("trade/order-precheck".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("trade/order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/cancel-algos".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/amend-algos".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("asset/withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/withdrawal-lightning".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("asset/cancel-withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("asset/convert-dust-assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("asset/monthly-statement".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1296000));
m
}));
m.insert("asset/convert/estimate-quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("asset/convert/trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fiat/create-withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/cancel-withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(10)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("fiat/buy-sell/quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("fiat/buy-sell/trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("account/bills-history-archive".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(72000));
m
}));
m.insert("account/set-position-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/set-leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/position/margin-balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/set-fee-type".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/set-greeks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/set-isolated-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/spot-manual-borrow-repay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(30));
m
}));
m.insert("account/set-auto-repay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/quick-margin-borrow-repay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/borrow-repay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("account/simulated_margin".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/position-builder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/position-builder-graph".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("account/set-riskOffset-type".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/set-riskOffset-amt".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(2));
m
}));
m.insert("account/activate-option".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/set-auto-loan".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/account-level-switch-preset".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/set-account-level".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/set-collateral-assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/mmp-reset".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("account/mmp-config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(50));
m
}));
m.insert("account/fixed-loan/borrowing-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/fixed-loan/amend-borrowing-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/fixed-loan/manual-reborrow".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/fixed-loan/repay-borrowing-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("account/move-positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/set-auto-earn".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/set-settle-currency".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/set-trading-config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("account/demo-adjust-balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("asset/subaccount/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("account/subaccount/set-loan-allocation".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("users/subaccount/create-subaccount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("users/subaccount/apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("users/subaccount/modify-apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("users/subaccount/subaccount-apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("users/subaccount/delete-apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("users/subaccount/set-transfer-out".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("tradingBot/grid/order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/copy-order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/amend-algo-basic-param".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/amend-order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/stop-order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/close-position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/cancel-close-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/order-instant-trigger".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/withdraw-income".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/compute-margin-balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/margin-balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/min-investment".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/grid/adjust-investment".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/create-signal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/stop-order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/margin-balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/amendTPSL".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/set-instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/close-position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/sub-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/signal/cancel-sub-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/amend-order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/stop-order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/amend-order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/stop".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/orders/manual-buy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/settings/reinvestment".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/settings/take-profit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/margin/add".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/dca/margin/reduce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/add-investment".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/amend-price-range".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/amend-recurring-amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/amend-recurring-time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/pause".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tradingBot/recurring/restart".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("finance/savings/purchase-redempt".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/savings/set-lending-rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("finance/staking-defi/purchase".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("finance/staking-defi/redeem".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("finance/staking-defi/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("finance/staking-defi/eth/purchase".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("finance/staking-defi/eth/redeem".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("finance/staking-defi/eth/cancel-redeem".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("finance/staking-defi/sol/purchase".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("finance/staking-defi/sol/redeem".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("finance/staking-defi/sol/cancel-redeem".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(5));
m
}));
m.insert("finance/flexible-loan/max-loan".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/flexible-loan/adjust-collateral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("finance/flexible-loan/borrow".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("finance/flexible-loan/repay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("finance/okusd/subscribe".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("finance/okusd/redeem".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(20));
m
}));
m.insert("copytrading/algo-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/close-subposition".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/set-instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/amend-profit-sharing-ratio".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/first-copy-settings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/amend-copy-settings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/stop-copy-trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("copytrading/batch-set-leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("broker/nd/create-subaccount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(0.25));
m
}));
m.insert("broker/nd/delete-subaccount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("broker/nd/subaccount/apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(0.25));
m
}));
m.insert("broker/nd/subaccount/modify-apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("broker/nd/subaccount/delete-apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("broker/nd/set-subaccount-level".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("broker/nd/set-subaccount-fee-rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(4));
m
}));
m.insert("broker/nd/set-subaccount-assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(0.25));
m
}));
m.insert("asset/broker/nd/subaccount-deposit-address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/broker/nd/modify-subaccount-deposit-address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(5)).as_f64(), (Value::Int(3)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("broker/nd/rebate-per-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(36000));
m
}));
m.insert("finance/sfp/dcd/quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("finance/sfp/dcd/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("finance/sfp/dcd/trade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("finance/sfp/dcd/redeem-quote".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("finance/sfp/dcd/redeem".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m
}));
m.insert("broker/nd/report-subaccount-ip".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(0.25));
m
}));
m.insert("broker/dma/subaccount/apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(4)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("broker/dma/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(36000));
m
}));
m.insert("broker/fd/rebate-per-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(36000));
m
}));
m
}));
m
}));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0015".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0010".into()), &[]));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0015".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0010".into()), &[]));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0005".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0002".into()), &[]));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.00050".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.00020".into()), &[]));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(true));
m.insert("password".to_string(), Value::Bool(true));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("2".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("4088".to_string(), Value::Str("ManualInteractionNeeded".into()).clone());
m.insert("50000".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("50001".to_string(), Value::Str("OnMaintenance".into()).clone());
m.insert("50002".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("50004".to_string(), Value::Str("RequestTimeout".into()).clone());
m.insert("50005".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("50006".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("50007".to_string(), Value::Str("AccountSuspended".into()).clone());
m.insert("50008".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50009".to_string(), Value::Str("AccountSuspended".into()).clone());
m.insert("50010".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50011".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("50012".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50013".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("50014".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("50015".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50016".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50017".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50018".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50019".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50020".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50021".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50022".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50023".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50024".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("50025".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50026".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("50027".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("50028".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50044".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("50061".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50062".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50100".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50101".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50102".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("50103".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50104".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50105".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50106".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50107".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50108".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50109".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("50110".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("50111".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50112".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50113".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50114".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("50115".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51000".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51001".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("51002".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("51003".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51004".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51005".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51006".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51007".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51008".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("51009".to_string(), Value::Str("AccountSuspended".into()).clone());
m.insert("51010".to_string(), Value::Str("AccountNotEnabled".into()).clone());
m.insert("51011".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51012".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("51014".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("51015".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("51016".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51017".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51018".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51019".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51020".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51021".to_string(), Value::Str("ContractUnavailable".into()).clone());
m.insert("51022".to_string(), Value::Str("ContractUnavailable".into()).clone());
m.insert("51023".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51024".to_string(), Value::Str("AccountSuspended".into()).clone());
m.insert("51025".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51026".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("51027".to_string(), Value::Str("ContractUnavailable".into()).clone());
m.insert("51028".to_string(), Value::Str("ContractUnavailable".into()).clone());
m.insert("51029".to_string(), Value::Str("ContractUnavailable".into()).clone());
m.insert("51030".to_string(), Value::Str("ContractUnavailable".into()).clone());
m.insert("51031".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51046".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51047".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51051".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51072".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51073".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51074".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51090".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51091".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51092".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51093".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51094".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51095".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51096".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51098".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51099".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51100".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51101".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51102".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51103".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51104".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51105".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51106".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51107".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51108".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51109".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51110".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51111".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51112".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51113".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("51115".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51116".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51117".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51118".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51119".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("51120".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51121".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51122".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51124".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51125".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51126".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51127".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("51128".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51129".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51130".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("51131".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("51132".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51133".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51134".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51135".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51136".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51137".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51138".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51139".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51155".to_string(), Value::Str("RestrictedLocation".into()).clone());
m.insert("51156".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51159".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51162".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51163".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51166".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51174".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51185".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51201".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51202".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51203".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51204".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51205".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51250".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51251".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51252".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51253".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51254".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51255".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51256".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51257".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51258".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51259".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51260".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51261".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51262".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51263".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51264".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51265".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51267".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51268".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51269".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51270".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51271".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51272".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51273".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51274".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51275".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51276".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51277".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51278".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51279".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51280".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51321".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51322".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51323".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51324".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51325".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51327".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51328".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51329".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51330".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51400".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("51401".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("51402".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("51403".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51404".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("51405".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51406".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51407".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51408".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51409".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51410".to_string(), Value::Str("CancelPending".into()).clone());
m.insert("51500".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51501".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51502".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("51503".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51506".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51508".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51509".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51510".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51511".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51600".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51601".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51602".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51603".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("51732".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("51733".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("51734".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("51735".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51736".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("51763".to_string(), Value::Str("AccountNotEnabled".into()).clone());
m.insert("51764".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("51765".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51766".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51767".to_string(), Value::Str("OnMaintenance".into()).clone());
m.insert("51768".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51769".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51770".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("51771".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("51772".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("51773".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("51774".to_string(), Value::Str("OnMaintenance".into()).clone());
m.insert("52000".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("54000".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("54001".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("54008".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("54009".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("54011".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("54051".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("54072".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("54073".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("54074".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("54094".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("55100".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("55101".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("55102".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("55103".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("55104".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("55111".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("55112".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("55113".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("58000".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58001".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("58002".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("58003".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58004".to_string(), Value::Str("AccountSuspended".into()).clone());
m.insert("58005".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58006".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58007".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58100".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58101".to_string(), Value::Str("AccountSuspended".into()).clone());
m.insert("58102".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("58103".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58104".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58105".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58106".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58107".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58108".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58109".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58110".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58111".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58112".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58114".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58115".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58116".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58117".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58125".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("58126".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("58127".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("58128".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("58200".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58201".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58202".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58203".to_string(), Value::Str("InvalidAddress".into()).clone());
m.insert("58204".to_string(), Value::Str("AccountSuspended".into()).clone());
m.insert("58205".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58206".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58207".to_string(), Value::Str("InvalidAddress".into()).clone());
m.insert("58208".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58209".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58210".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58211".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58212".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58213".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("58221".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("58222".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("58224".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("58227".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("58228".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("58229".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("58300".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("58350".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("59000".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59001".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59100".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59101".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59102".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59103".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("59104".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59105".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59106".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59107".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59108".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("59109".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59113".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("59128".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("59200".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("59201".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("59216".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("59260".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("59262".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("59300".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59301".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59313".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59401".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59410".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("59411".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("59412".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("59413".to_string(), Value::Str("OperationRejected".into()).clone());
m.insert("59414".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("59500".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59501".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59502".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59503".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59504".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59505".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59506".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59507".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59508".to_string(), Value::Str("AccountSuspended".into()).clone());
m.insert("59515".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59516".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59517".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59518".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59519".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59642".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("59643".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59683".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("59684".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("59686".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("60001".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60002".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60003".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60004".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60005".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60006".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("60007".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60008".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60009".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60010".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60011".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60012".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("60013".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("60014".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("60015".to_string(), Value::Str("NetworkError".into()).clone());
m.insert("60016".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("60017".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("60018".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("60019".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("60020".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("60021".to_string(), Value::Str("AccountNotEnabled".into()).clone());
m.insert("60022".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60023".to_string(), Value::Str("DDoSProtection".into()).clone());
m.insert("60024".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60025".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("60026".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60027".to_string(), Value::Str("ArgumentsRequired".into()).clone());
m.insert("60028".to_string(), Value::Str("NotSupported".into()).clone());
m.insert("60029".to_string(), Value::Str("AccountNotEnabled".into()).clone());
m.insert("60030".to_string(), Value::Str("AccountNotEnabled".into()).clone());
m.insert("60031".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("60032".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("63999".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("64000".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("64001".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("64002".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("64003".to_string(), Value::Str("AccountNotEnabled".into()).clone());
m.insert("64004".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("64008".to_string(), Value::Str("NetworkError".into()).clone());
m.insert("70010".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("70013".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("70016".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("70060".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("70061".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("70062".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("70064".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("70065".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("70066".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("70067".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("1009".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("4001".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("4002".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("4003".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("4004".to_string(), Value::Str("NetworkError".into()).clone());
m.insert("4005".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("4006".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("4007".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("4008".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Internal Server Error".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("server error".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m
}));
m
}));
m.insert("httpExceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("429".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandboxMode".to_string(), Value::Bool(false));
m.insert("defaultNetwork".to_string(), Value::Str("ERC20".into()));
m.insert("defaultNetworks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ETH".to_string(), Value::Str("ERC20".into()));
m.insert("BTC".to_string(), Value::Str("BTC".into()));
m.insert("USDT".to_string(), Value::Str("TRC20".into()));
m
}));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("BTC".to_string(), Value::Str("Bitcoin".into()));
m.insert("BTCLIGHTNING".to_string(), Value::Str("Lightning".into()));
m.insert("BSC".to_string(), Value::Str("BSC".into()));
m.insert("BEP20".to_string(), Value::Str("BSC".into()));
m.insert("BRC20".to_string(), Value::Str("BRC20".into()));
m.insert("ETH".to_string(), Value::Str("ERC20".into()));
m.insert("ERC20".to_string(), Value::Str("ERC20".into()));
m.insert("TRX".to_string(), Value::Str("TRC20".into()));
m.insert("TRC20".to_string(), Value::Str("TRC20".into()));
m.insert("CRC20".to_string(), Value::Str("Crypto".into()));
m.insert("CRONOS".to_string(), Value::Str("Crypto".into()));
m.insert("ACA".to_string(), Value::Str("Acala".into()));
m.insert("ALGO".to_string(), Value::Str("Algorand".into()));
m.insert("APT".to_string(), Value::Str("Aptos".into()));
m.insert("SONIC".to_string(), Value::Str("Sonic".into()));
m.insert("SCROLL".to_string(), Value::Str("Scroll".into()));
m.insert("ARBITRUM".to_string(), Value::Str("Arbitrum One".into()));
m.insert("AVAXC".to_string(), Value::Str("Avalanche C-Chain".into()));
m.insert("AVAXX".to_string(), Value::Str("Avalanche X-Chain".into()));
m.insert("BASE".to_string(), Value::Str("Base".into()));
m.insert("SUI".to_string(), Value::Str("SUI".into()));
m.insert("ZKSYNCERA".to_string(), Value::Str("zkSync Era".into()));
m.insert("LINEA".to_string(), Value::Str("Linea".into()));
m.insert("VAULTA".to_string(), Value::Str("Vaulta".into()));
m.insert("AR".to_string(), Value::Str("Arweave".into()));
m.insert("ASTR".to_string(), Value::Str("Astar".into()));
m.insert("BCH".to_string(), Value::Str("BitcoinCash".into()));
m.insert("BSV".to_string(), Value::Str("Bitcoin SV".into()));
m.insert("ADA".to_string(), Value::Str("Cardano".into()));
m.insert("CSPR".to_string(), Value::Str("Casper".into()));
m.insert("CANTON".to_string(), Value::Str("Canton Network".into()));
m.insert("CELO".to_string(), Value::Str("CELO".into()));
m.insert("XCH".to_string(), Value::Str("Chia".into()));
m.insert("BABY".to_string(), Value::Str("Babylon".into()));
m.insert("ATOM".to_string(), Value::Str("Cosmos".into()));
m.insert("DGB".to_string(), Value::Str("Digibyte".into()));
m.insert("DOGE".to_string(), Value::Str("Dogecoin".into()));
m.insert("EGLD".to_string(), Value::Str("Elrond".into()));
m.insert("CFX".to_string(), Value::Str("Conflux".into()));
m.insert("EOS".to_string(), Value::Str("EOS".into()));
m.insert("CORE".to_string(), Value::Str("CORE".into()));
m.insert("ETC".to_string(), Value::Str("Ethereum Classic".into()));
m.insert("ETHW".to_string(), Value::Str("EthereumPow".into()));
m.insert("FIL".to_string(), Value::Str("Filecoin".into()));
m.insert("HBAR".to_string(), Value::Str("Hedera".into()));
m.insert("HYPER".to_string(), Value::Str("HyperEVM".into()));
m.insert("ICP".to_string(), Value::Str("Dfinity".into()));
m.insert("PI".to_string(), Value::Str("PI".into()));
m.insert("IOTA".to_string(), Value::Str("MIOTA".into()));
m.insert("KLAY".to_string(), Value::Str("Klaytn".into()));
m.insert("KSM".to_string(), Value::Str("Kusama".into()));
m.insert("LSK".to_string(), Value::Str("Lisk".into()));
m.insert("LTC".to_string(), Value::Str("Litecoin".into()));
m.insert("METIS".to_string(), Value::Str("Metis".into()));
m.insert("MINA".to_string(), Value::Str("Mina".into()));
m.insert("GLRM".to_string(), Value::Str("Moonbeam".into()));
m.insert("MOVR".to_string(), Value::Str("Moonriver".into()));
m.insert("NANO".to_string(), Value::Str("Nano".into()));
m.insert("NEAR".to_string(), Value::Str("NEAR".into()));
m.insert("NULS".to_string(), Value::Str("NULS".into()));
m.insert("OASYS".to_string(), Value::Str("OASYS".into()));
m.insert("ONT".to_string(), Value::Str("Ontology".into()));
m.insert("OP".to_string(), Value::Str("Optimism".into()));
m.insert("DOT".to_string(), Value::Str("Polkadot".into()));
m.insert("MATIC".to_string(), Value::Str("Polygon".into()));
m.insert("RVN".to_string(), Value::Str("Ravencoin".into()));
m.insert("XRP".to_string(), Value::Str("Ripple".into()));
m.insert("SC".to_string(), Value::Str("Siacoin".into()));
m.insert("SOL".to_string(), Value::Str("Solana".into()));
m.insert("STX".to_string(), Value::Str("l-Stacks".into()));
m.insert("XLM".to_string(), Value::Str("Stellar Lumens".into()));
m.insert("XTZ".to_string(), Value::Str("Tezos".into()));
m.insert("TON".to_string(), Value::Str("TON".into()));
m.insert("THETA".to_string(), Value::Str("Theta".into()));
m.insert("WAX".to_string(), Value::Str("Wax".into()));
m.insert("ZIL".to_string(), Value::Str("Zilliqa".into()));
m.insert("ZEC".to_string(), Value::Str("Zcash".into()));
m.insert("ZETA".to_string(), Value::Str("ZetaChain".into()));
m.insert("TIA".to_string(), Value::Str("Celestia".into()));
m.insert("SEI".to_string(), Value::Str("SEI".into()));
m.insert("QUANTUM".to_string(), Value::Str("Quantum".into()));
m.insert("PHAROS".to_string(), Value::Str("Pharos".into()));
m.insert("RONIN".to_string(), Value::Str("Ronin".into()));
m.insert("MEGAETH".to_string(), Value::Str("MegaETH".into()));
m.insert("INJ".to_string(), Value::Str("INJ".into()));
m.insert("FOGO".to_string(), Value::Str("Fogo".into()));
m.insert("FLR".to_string(), Value::Str("Flare".into()));
m.insert("FLOW".to_string(), Value::Str("FLOW".into()));
m.insert("DYDX".to_string(), Value::Str("DYDX".into()));
m.insert("AELF".to_string(), Value::Str("AELF".into()));
m.insert("BERA".to_string(), Value::Str("Berachain".into()));
m.insert("TEMPO".to_string(), Value::Str("Tempo".into()));
m.insert("MONAD".to_string(), Value::Str("Monad".into()));
m.insert("PLASMA".to_string(), Value::Str("Plasma".into()));
m
}));
m.insert("networksById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ERC20".to_string(), Value::Str("ERC20".into()));
m.insert("TRC20".to_string(), Value::Str("TRC20".into()));
m.insert("BEP20".to_string(), Value::Str("BEP20".into()));
m
}));
m.insert("fetchOpenInterestHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("1h".to_string(), Value::Str("1H".into()));
m.insert("8h".to_string(), Value::Str("8H".into()));
m.insert("1d".to_string(), Value::Str("1D".into()));
m.insert("5M".to_string(), Value::Str("5m".into()));
m.insert("1H".to_string(), Value::Str("1H".into()));
m.insert("8H".to_string(), Value::Str("8H".into()));
m.insert("1D".to_string(), Value::Str("1D".into()));
m
}));
m
}));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timezone".to_string(), Value::Str("UTC".into()));
m
}));
m.insert("fetchPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetAccountPositions".into()));
m
}));
m.insert("createOrder".to_string(), Value::Str("privatePostTradeBatchOrders".into()));
m.insert("createMarketBuyOrderRequiresPrice".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("types".to_string(), Value::from(vec![Value::Str("spot".into()), Value::Str("future".into()), Value::Str("swap".into()), Value::Str("option".into())]));
m
}));
m.insert("timeDifference".to_string(), Value::Int(0));
m.insert("adjustForTimeDifference".to_string(), Value::Bool(false));
m.insert("defaultType".to_string(), Value::Str("spot".into()));
m.insert("fetchLedger".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetAccountBills".into()));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetTradeOrder".into()));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetTradeOrdersPending".into()));
m
}));
m.insert("cancelOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privatePostTradeCancelBatchOrders".into()));
m
}));
m.insert("fetchCanceledOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetTradeOrdersHistory".into()));
m.insert("paginationDirection".to_string(), Value::Str("forward".into()));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetTradeOrdersHistory".into()));
m.insert("paginationDirection".to_string(), Value::Str("forward".into()));
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("password".to_string(), Value::Null);
m.insert("pwd".to_string(), Value::Null);
m
}));
m.insert("algoOrderTypes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("conditional".to_string(), Value::Bool(true));
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("oco".to_string(), Value::Bool(true));
m.insert("move_order_stop".to_string(), Value::Bool(true));
m.insert("iceberg".to_string(), Value::Bool(true));
m.insert("twap".to_string(), Value::Bool(true));
m
}));
m.insert("accountsByType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("funding".to_string(), Value::Str("6".into()));
m.insert("trading".to_string(), Value::Str("18".into()));
m.insert("spot".to_string(), Value::Str("18".into()));
m.insert("future".to_string(), Value::Str("18".into()));
m.insert("futures".to_string(), Value::Str("18".into()));
m.insert("margin".to_string(), Value::Str("18".into()));
m.insert("swap".to_string(), Value::Str("18".into()));
m.insert("option".to_string(), Value::Str("18".into()));
m
}));
m.insert("accountsById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("6".to_string(), Value::Str("funding".into()));
m.insert("18".to_string(), Value::Str("trading".into()));
m
}));
m.insert("exchangeType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("SPOT".into()));
m.insert("margin".to_string(), Value::Str("MARGIN".into()));
m.insert("swap".to_string(), Value::Str("SWAP".into()));
m.insert("future".to_string(), Value::Str("FUTURES".into()));
m.insert("futures".to_string(), Value::Str("FUTURES".into()));
m.insert("option".to_string(), Value::Str("OPTION".into()));
m.insert("SPOT".to_string(), Value::Str("SPOT".into()));
m.insert("MARGIN".to_string(), Value::Str("MARGIN".into()));
m.insert("SWAP".to_string(), Value::Str("SWAP".into()));
m.insert("FUTURES".to_string(), Value::Str("FUTURES".into()));
m.insert("OPTION".to_string(), Value::Str("OPTION".into()));
m
}));
m.insert("brokerId".to_string(), Value::Str("6b9ad766b55dBCDE".into()));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("default".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(true));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Bool(true));
m.insert("mark".to_string(), Value::Bool(true));
m.insert("index".to_string(), Value::Bool(true));
m
}));
m.insert("triggerDirection".to_string(), Value::Bool(false));
m.insert("stopLossPrice".to_string(), Value::Bool(true));
m.insert("takeProfitPrice".to_string(), Value::Bool(true));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Bool(true));
m.insert("mark".to_string(), Value::Bool(true));
m.insert("index".to_string(), Value::Bool(true));
m
}));
m.insert("price".to_string(), Value::Bool(true));
m
}));
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(true));
m.insert("FOK".to_string(), Value::Bool(true));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(true));
m.insert("iceberg".to_string(), Value::Bool(true));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("EXPIRE_MAKER".to_string(), Value::Bool(true));
m.insert("EXPIRE_TAKER".to_string(), Value::Bool(true));
m.insert("EXPIRE_BOTH".to_string(), Value::Bool(true));
m.insert("NONE".to_string(), Value::Bool(false));
m
}));
m.insert("marketBuyByCost".to_string(), Value::Bool(true));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Int(20));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("daysBack".to_string(), Value::Int(90));
m.insert("limit".to_string(), Value::Int(100));
m.insert("untilDays".to_string(), Value::Int(10000));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(true));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(true));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Null);
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("daysBack".to_string(), Value::Int(90));
m.insert("daysBackCanceled".to_string(), (match ((Value::Int(1)).as_f64(), (Value::Int(12)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m.insert("untilDays".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(true));
m.insert("trailing".to_string(), Value::Bool(true));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(300));
m.insert("mark".to_string(), Value::Int(100));
m.insert("index".to_string(), Value::Int(100));
m
}));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m.insert("fetchCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("private".to_string(), Value::Bool(true));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m
}));
m
}));
m.insert("currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("USD".to_string(), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("USD".into()));
m.insert("code".to_string(), Value::Str("USD".into()));
m.insert("precision".to_string(), self.parse_number(Value::Str("0.0001".into()), &[]));
m
})));
m.insert("EUR".to_string(), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("EUR".into()));
m.insert("code".to_string(), Value::Str("EUR".into()));
m.insert("precision".to_string(), self.parse_number(Value::Str("0.0001".into()), &[]));
m
})));
m.insert("AED".to_string(), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("AED".into()));
m.insert("code".to_string(), Value::Str("AED".into()));
m.insert("precision".to_string(), self.parse_number(Value::Str("0.0001".into()), &[]));
m
})));
m.insert("GBP".to_string(), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("GBP".into()));
m.insert("code".to_string(), Value::Str("GBP".into()));
m.insert("precision".to_string(), self.parse_number(Value::Str("0.0001".into()), &[]));
m
})));
m.insert("AUD".to_string(), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("AUD".into()));
m.insert("code".to_string(), Value::Str("AUD".into()));
m.insert("precision".to_string(), self.parse_number(Value::Str("0.0001".into()), &[]));
m
})));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("AE".to_string(), Value::Str("AET".into()));
m
}));
m.insert("rollingWindowSize".to_string(), Value::Int(0));
m
})]);
Value::Null
}
pub fn handle_market_type_and_params(&self, mut methodName: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut defaultValue = get_arg(optional_args, 2, Value::Null);
let mut instType: Value = self.safe_string_k(params.clone(), "instType", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("instType".into()), &[]);
let mut type_var: Option<String> = self.safe_string_k(paramsOmitted.clone(), "type", &[]).as_str().map(str::to_owned);
if (type_var.is_none()) && (instType != Value::Null) {
add_element_to_object(&mut paramsOmitted, &Value::Str("type".into()), instType);
}
return self.super_handle_market_type_and_params(methodName, market, paramsOmitted, defaultValue);
Value::Null
}
pub fn convert_to_instrument_type(&self, mut type_var: Value) -> Value {
let mut exchangeTypes: Value = self.safe_dict_k(self.options.clone(), "exchangeType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_string(exchangeTypes, type_var.clone(), &[type_var.clone()]);
Value::Null
}
pub fn create_expired_option_market(&self, mut symbol: Value) -> Value {
// support expired option contracts
let mut quote: Value = Value::Str("USD".into());
let mut optionParts: Value = split(&symbol, &Value::Str("-".into()));
let mut symbolBase: Value = split(&symbol, &Value::Str("/".into()));
let mut base: Value = Value::Null;
if Value::Int(symbol.as_str().and_then(|__s| __s.find("/")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64) {
base = self.safe_string(symbolBase, Value::Int(0), &[]);
} else {
base = self.safe_string(optionParts.clone(), Value::Int(0), &[]);
}
let mut settle: Value = base.clone();
let mut expiry: Value = self.safe_string(optionParts.clone(), Value::Int(2), &[]);
let mut strike: Value = self.safe_string(optionParts.clone(), Value::Int(3), &[]);
let mut optionType: Value = self.safe_string(optionParts, Value::Int(4), &[]);
let mut datetime: Value = (if (expiry == Value::Null) { Value::Null } else { self.convert_expire_date(expiry.clone()) });
let mut timestamp: Value = self.parse8601(datetime.clone());
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("-".into())).into()), quote).into()), Value::Str("-".into())).into()), expiry).into()), Value::Str("-".into())).into()), strike).into()), Value::Str("-".into())).into()), optionType).into()));
m.insert("symbol".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into()), Value::Str(":".into())).into()), settle).into()), Value::Str("-".into())).into()), expiry).into()), Value::Str("-".into())).into()), strike).into()), Value::Str("-".into())).into()), optionType).into()));
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("settle".to_string(), settle.clone());
m.insert("baseId".to_string(), base);
m.insert("quoteId".to_string(), quote);
m.insert("settleId".to_string(), settle);
m.insert("active".to_string(), Value::Bool(false));
m.insert("type".to_string(), Value::Str("option".into()));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("contract".to_string(), Value::Bool(true));
m.insert("contractSize".to_string(), self.parse_number(Value::Str("1".into()), &[]));
m.insert("expiry".to_string(), timestamp);
m.insert("expiryDatetime".to_string(), datetime);
m.insert("optionType".to_string(), (if (optionType.as_str() == Some("C")) { Value::Str("call".into()) } else { Value::Str("put".into()) }));
m.insert("strike".to_string(), self.parse_number(strike, &[]));
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Null);
m.insert("price".to_string(), Value::Null);
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), Value::Null);
m
});
Value::Null
}
pub fn safe_market(&self, optional_args: &[Value]) -> Value {
let mut marketId = get_arg(optional_args, 0, Value::Null);
let mut market = get_arg(optional_args, 1, Value::Null);
let mut delimiter = get_arg(optional_args, 2, Value::Null);
let mut marketType = get_arg(optional_args, 3, Value::Null);
let mut isOption: bool = false;
if (marketId != Value::Null) {
let mut parts: Value = split(&marketId, &Value::Str("-".into()));
let mut partsLength: f64 = ((parts.len() as i64) as f64);
// a valid OKX option ends with the call/put flag and carries expiry+strike segments,
// e.g. the market id BTC-USD-220325-194000-P (5 parts) or the unified symbol
// BTC/USD:USD-260611-54000-C (4 parts). Requiring more than 3 dash-separated parts avoids
// misclassifying ordinary ids that merely contain "-C"/"-P" (such as a SPOT id like
// "PERFTESTA-PERFTESTB") as expired options, which would crash createExpiredOptionMarket
// on the missing expiry.
isOption = (partsLength > ((3i64) as f64)) && ((ends_with(&marketId, &Value::Str("-C".into()))) || (ends_with(&marketId, &Value::Str("-P".into()))));
}
if isOption && (marketId != Value::Null) && ((self.markets_by_id.clone() == Value::Null) || !(in_op(&self.markets_by_id, &marketId))) {
return self.create_expired_option_market(marketId.clone());
}
return self.super_safe_market(marketId, market, delimiter, marketType);
Value::Null
}
/*
* @method
* @name okx#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://www.okx.com/docs-v5/en/#status-get-status
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/?id=exchange-status-structure}
*/
pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_system_status(&[params]).await;
//
// Note, if there is no maintenance around, the 'data' array is empty
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "begin": "1621328400000",
// "end": "1621329000000",
// "href": "https://www.okx.com/support/hc/en-us/articles/360060882172",
// "scheDesc": "",
// "serviceType": "1", // 0 WebSocket, 1 Spot/Margin, 2 Futures, 3 Perpetual, 4 Options, 5 Trading service
// "state": "scheduled", // ongoing, completed, canceled
// "system": "classic", // classic, unified
// "title": "Classic Spot System Upgrade"
// },
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
let mut dataLength: f64 = ((data.len() as i64) as f64);
let mut update: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("updated".to_string(), Value::Null);
m.insert("status".to_string(), (if (dataLength == 0.0) { Value::Str("ok".into()) } else { Value::Str("maintenance".into()) }));
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_978: bool = true;
while { if !__for_first_978 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_978 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut event: Value = self.safe_dict(data.clone(), i.clone(), &[]);
let mut state: Option<String> = self.safe_string_k(event.clone(), "state", &[]).as_str().map(str::to_owned);
if let Value::Dict(__d) = &mut update { std::sync::Arc::make_mut(__d).insert("eta".into(), self.safe_integer_k(event.clone(), "end", &[])); }
if let Value::Dict(__d) = &mut update { std::sync::Arc::make_mut(__d).insert("url".into(), self.safe_string_k(event, "href", &[])); }
if (state.as_deref() == Some("ongoing")) {
if let Value::Dict(__d) = &mut update { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("maintenance".into())); }
} else if (state.as_deref() == Some("scheduled")) {
if let Value::Dict(__d) = &mut update { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("ok".into())); }
} else if (state.as_deref() == Some("completed")) {
if let Value::Dict(__d) = &mut update { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("ok".into())); }
} else if (state.as_deref() == Some("canceled")) {
if let Value::Dict(__d) = &mut update { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("ok".into())); }
}
}
}
return update;
Value::Null
}
/*
* @method
* @name okx#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-system-time
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_public_time(&[params]).await;
//
// {
// "code": "0",
// "data": [
// {"ts": "1621247923668"}
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_integer_k(first, "ts", &[]);
Value::Null
}
/*
* @method
* @name okx#fetchAccounts
* @description fetch all the accounts associated with a profile
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-account-configuration
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [account structures]{@link https://docs.ccxt.com/?id=account-structure} indexed by the account type
*/
pub async fn fetch_accounts(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.private_get_account_config(&[params]).await;
//
// {
// "code": "0",
// "data": [
// {
// "acctLv": "2",
// "acctStpMode": "cancel_maker",
// "autoLoan": false,
// "ctIsoMode": "automatic",
// "enableSpotBorrow": false,
// "greeksType": "PA",
// "feeType": "0",
// "ip": "",
// "type": "0",
// "kycLv": "3",
// "label": "v5 test",
// "level": "Lv1",
// "levelTmp": "",
// "liquidationGear": "-1",
// "mainUid": "44705892343619584",
// "mgnIsoMode": "automatic",
// "opAuth": "1",
// "perm": "read_only,withdraw,trade",
// "posMode": "long_short_mode",
// "roleType": "0",
// "spotBorrowAutoRepay": false,
// "spotOffsetType": "",
// "spotRoleType": "0",
// "spotTraderInsts": [],
// "traderInsts": [],
// "uid": "44705892343619584",
// "settleCcy": "USDT",
// "settleCcyList": ["USD", "USDC", "USDG"],
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_979: bool = true;
while { if !__for_first_979 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_979 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut account: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut accountId: Value = self.safe_string_k(account.clone(), "uid", &[]);
let mut type_var: Value = self.safe_string_k(account.clone(), "acctLv", &[]);
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), accountId);
m.insert("type".to_string(), type_var);
m.insert("currency".to_string(), Value::Null);
m.insert("info".to_string(), account);
m.insert("code".to_string(), Value::Null);
m
}));
}
}
return result;
Value::Null
}
pub fn nonce(&self) -> Value {
let mut timeDifference: Value = self.safe_integer_k(self.options.clone(), "timeDifference", &[]);
if (timeDifference == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" nonce() requires a numeric options[\"timeDifference\"]".into()))));
}
return (match (&(self.milliseconds()), &(timeDifference)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
Value::Null
}
/*
* @method
* @name okx#fetchMarkets
* @description retrieves data on all markets for okx
* @see https://www.okx.com/docs-v5/en/#rest-api-public-data-get-instruments
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if matches!(self.safe_bool_k(self.options.clone(), "adjustForTimeDifference", &[Value::Bool(false)]), Value::Bool(true)) {
self.load_time_difference(&[]).await;
}
let mut types: Value = Value::from(vec![Value::Str("spot".into()), Value::Str("future".into()), Value::Str("swap".into()), Value::Str("option".into())]);
let mut fetchMarketsOption: Value = self.safe_dict_k(self.options.clone(), "fetchMarkets", &[]);
if (fetchMarketsOption != Value::Null) {
types = self.safe_list_k(fetchMarketsOption, "types", &[types.clone()]);
} else {
types = self.safe_list_k(self.options.clone(), "fetchMarkets", &[types.clone()]); // backward-support
}
let mut promises: Value = Value::from(vec![]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_980: bool = true;
while { if !__for_first_980 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_980 = false; i.as_f64().unwrap_or(f64::NAN) < ((types.len() as i64) as f64) } {
append_to_array(&mut promises, self.fetch_markets_by_type(types.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[params.clone()]).await);
}
}
promises = promise_all(&promises).await;
{
let mut i: Value = Value::Int(0);
let mut __for_first_981: bool = true;
while { if !__for_first_981 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_981 = false; i.as_f64().unwrap_or(f64::NAN) < ((promises.len() as i64) as f64) } {
result = self.array_concat(result.clone(), promises.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
}
}
return result;
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
//
// {
// "alias": "", // this_week, next_week, quarter, next_quarter
// "baseCcy": "BTC",
// "category": "1",
// "ctMult": "",
// "ctType": "", // inverse, linear
// "ctVal": "",
// "ctValCcy": "",
// "expTime": "",
// "instId": "BTC-USDT", // BTC-USD-210521, CSPR-USDT-SWAP, BTC-USD-210517-44000-C
// "instType": "SPOT", // SPOT, FUTURES, SWAP, OPTION
// "lever": "10",
// "listTime": "1548133413000",
// "lotSz": "0.00000001",
// "minSz": "0.00001",
// "optType": "",
// "quoteCcy": "USDT",
// "settleCcy": "",
// "state": "live",
// "stk": "",
// "tickSz": "0.1",
// "uly": ""
// }
//
// {
// "alias": "",
// "baseCcy": "",
// "category": "1",
// "ctMult": "0.1",
// "ctType": "",
// "ctVal": "1",
// "ctValCcy": "BTC",
// "expTime": "1648195200000",
// "instId": "BTC-USD-220325-194000-P",
// "instType": "OPTION",
// "lever": "",
// "listTime": "1631262612280",
// "contTdSwTime": "1631262812280",
// "lotSz": "1",
// "minSz": "1",
// "optType": "P",
// "quoteCcy": "",
// "settleCcy": "BTC",
// "state": "live",
// "stk": "194000",
// "tickSz": "0.0005",
// "uly": "BTC-USD"
// }
//
// for swap "preopen" markets, only `instId` and `instType` are present
//
// instId: "ETH-USD_UM-SWAP",
// instType: "SWAP",
// state: "preopen",
//
let mut id: Value = self.safe_string_k(market.clone(), "instId", &[Value::Str("".into())]);
let mut type_var: Value = self.safe_string_lower_k(market.clone(), "instType", &[]);
if (type_var.as_str() == Some("futures")) {
type_var = Value::Str("future".into());
}
let mut spot: Value = (Value::Bool(type_var.as_str() == Some("spot")));
let mut future: Value = (Value::Bool(type_var.as_str() == Some("future")));
let mut swap: Value = (Value::Bool(type_var.as_str() == Some("swap")));
let mut option: Value = (Value::Bool(type_var.as_str() == Some("option")));
let mut contract: Value = Value::Bool(matches!(&swap, Value::Bool(true)) || matches!(&future, Value::Bool(true)) || matches!(&option, Value::Bool(true)));
let mut baseId: Value = self.safe_string_k(market.clone(), "baseCcy", &[Value::Str("".into())]); // defaulting to '' because some weird preopen markets have empty baseId
let mut quoteId: Value = self.safe_string_k(market.clone(), "quoteCcy", &[Value::Str("".into())]);
let mut settleId: Value = self.safe_string_k(market.clone(), "settleCcy", &[]);
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut underlying: Value = self.safe_string_k(market.clone(), "uly", &[]);
if (underlying != Value::Null) && !(matches!(&spot, Value::Bool(true))) {
let mut parts: Value = split(&underlying, &Value::Str("-".into()));
baseId = self.safe_string(parts.clone(), Value::Int(0), &[Value::Str("".into())]);
quoteId = self.safe_string(parts.clone(), Value::Int(1), &[Value::Str("".into())]);
}
if ((baseId.as_str() == Some("")) || (quoteId.as_str() == Some(""))) && matches!(&spot, Value::Bool(true)) {
let mut instId: Value = self.safe_string_k(market.clone(), "instId", &[Value::Str("".into())]);
let mut parts: Value = split(&instId, &Value::Str("-".into()));
baseId = self.safe_string(parts.clone(), Value::Int(0), &[Value::Str("".into())]);
quoteId = self.safe_string(parts, Value::Int(1), &[Value::Str("".into())]);
}
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
return Value::Null;
}
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
// handle preopen empty markets
if (base.as_str() == Some("")) || (quote.as_str() == Some("")) {
symbol = id.clone();
}
let mut expiry: Value = Value::Null;
let mut strikePrice: Value = Value::Null;
let mut optionType: Value = Value::Null;
if matches!(&contract, Value::Bool(true)) {
if (settle != Value::Null) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str(":".into())).into()), settle).into());
}
if matches!(&future, Value::Bool(true)) {
expiry = self.safe_integer_k(market.clone(), "expTime", &[]);
if (expiry != Value::Null) {
let mut ymd: Value = self.yymmdd(expiry.clone(), &[]);
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str("-".into())).into()), ymd).into());
}
} else if matches!(&option, Value::Bool(true)) {
expiry = self.safe_integer_k(market.clone(), "expTime", &[]);
strikePrice = self.safe_string_k(market.clone(), "stk", &[]);
optionType = self.safe_string_k(market.clone(), "optType", &[]);
if (expiry != Value::Null) {
let mut ymd: Value = self.yymmdd(expiry.clone(), &[]);
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str("-".into())).into()), ymd).into()), Value::Str("-".into())).into()), strikePrice).into()), Value::Str("-".into())).into()), optionType).into());
optionType = (if (optionType.as_str() == Some("P")) { Value::Str("put".into()) } else { Value::Str("call".into()) });
}
}
}
let mut feesType: Value = (if (type_var == Value::Null) { Value::Str("".into()) } else { type_var.clone() });
let mut fees: Value = self.safe_dict2(self.fees.clone(), feesType, Value::Str("trading".into()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut maxLeverage: Value = self.safe_string_k(market.clone(), "lever", &[Value::Str("1".into())]);
maxLeverage = crate::precise::Precise::stringMax(&maxLeverage, &Value::Str("1".into()));
let mut maxSpotCost: Value = self.safe_number_k(market.clone(), "maxMktSz", &[]);
let mut leverageAboveOne: Value = crate::precise::Precise::stringGt(&maxLeverage, &Value::Str("1".into()));
let mut quoteEqualSettle: Value = (Value::Bool(quoteId.as_str() == settleId.as_str()));
let mut baseEqualSettle: Value = (Value::Bool(baseId.as_str() == settleId.as_str()));
let mut status: Option<String> = self.safe_string_k(market.clone(), "state", &[]).as_str().map(str::to_owned);
let mut instIdCode: Value = self.safe_integer_k(market.clone(), "instIdCode", &[]);
let __ws_arg_0 = self.safe_number_k(market.clone(), "ctVal", &[]);
let __ws_arg_1 = self.iso8601(expiry.clone());
let __ws_arg_2 = self.parse_number(strikePrice, &[]);
let __ws_arg_3 = self.safe_integer2(market.clone(), Value::Str("contTdSwTime".into()), Value::Str("listTime".into()), &[]);
let __ws_arg_4 = self.safe_number_k(market.clone(), "lotSz", &[]);
let __ws_arg_5 = self.safe_number_k(market.clone(), "tickSz", &[]);
let __ws_arg_6 = self.parse_number(Value::Str("1".into()), &[]);
let __ws_arg_7 = self.parse_number(maxLeverage, &[]);
let __ws_arg_8 = self.safe_number_k(market.clone(), "minSz", &[]);
let __ws_arg_9 = self.safe_number_k(market.clone(), "maxLmtSz", &[]);
return self.extend(fees, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("instIdCode".to_string(), instIdCode);
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), type_var);
m.insert("spot".to_string(), spot.clone());
m.insert("margin".to_string(), Value::Bool(matches!(&spot, Value::Bool(true)) && is_true(&leverageAboveOne)));
m.insert("swap".to_string(), swap);
m.insert("future".to_string(), future);
m.insert("option".to_string(), option);
m.insert("active".to_string(), Value::Bool(status.as_deref() == Some("live")));
m.insert("contract".to_string(), contract.clone());
m.insert("linear".to_string(), (if matches!(&contract, Value::Bool(true)) { quoteEqualSettle } else { Value::Null }));
m.insert("inverse".to_string(), (if matches!(&contract, Value::Bool(true)) { baseEqualSettle } else { Value::Null }));
m.insert("contractSize".to_string(), (if matches!(&contract, Value::Bool(true)) { __ws_arg_0 } else { Value::Null }));
m.insert("expiry".to_string(), expiry);
m.insert("expiryDatetime".to_string(), __ws_arg_1);
m.insert("strike".to_string(), __ws_arg_2);
m.insert("optionType".to_string(), optionType);
m.insert("created".to_string(), __ws_arg_3);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), __ws_arg_4);
m.insert("price".to_string(), __ws_arg_5);
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), __ws_arg_6);
m.insert("max".to_string(), __ws_arg_7);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), __ws_arg_8);
m.insert("max".to_string(), __ws_arg_9);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), (if matches!(&contract, Value::Bool(true)) { Value::Null } else { maxSpotCost }));
m
}));
m
}));
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
pub async fn fetch_markets_by_type(&mut self, mut type_var: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instType".to_string(), self.convert_to_instrument_type(type_var.clone()));
m
});
if (type_var.as_str() == Some("option")) {
let mut optionsUnderlying: Value = self.safe_list_k(self.options.clone(), "defaultUnderlying", &[Value::from(vec![Value::Str("BTC-USD".into()), Value::Str("ETH-USD".into())])]);
let mut promises: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_982: bool = true;
while { if !__for_first_982 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_982 = false; i.as_f64().unwrap_or(f64::NAN) < ((optionsUnderlying.len() as i64) as f64) } {
let mut underlying: Value = optionsUnderlying.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("uly".into(), underlying); }
let __ws_arg_10 = self.extend(request.clone(), &[params.clone()]);
append_to_array(&mut promises, self.public_get_public_instruments(&[__ws_arg_10]).await);
}
}
let mut promisesResult: Value = promise_all(&promises).await;
let mut markets: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_983: bool = true;
while { if !__for_first_983 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_983 = false; i.as_f64().unwrap_or(f64::NAN) < ((promisesResult.len() as i64) as f64) } {
let mut res: Value = self.safe_dict(promisesResult.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut options: Value = self.safe_list_k(res, "data", &[Value::from(vec![])]);
markets = self.array_concat(markets.clone(), options);
}
}
return self.parse_markets(markets);
}
let __ws_arg_11 = self.extend(request, &[params]);
let mut response: Value = self.public_get_public_instruments(&[__ws_arg_11]).await;
//
// spot, future, swap, option
//
// {
// "code": "0",
// "data": [
// {
// "alias": "", // this_week, next_week, quarter, next_quarter
// "baseCcy": "BTC",
// "category": "1",
// "ctMult": "",
// "ctType": "", // inverse, linear
// "ctVal": "",
// "ctValCcy": "",
// "expTime": "",
// "instId": "BTC-USDT", // BTC-USD-210521, CSPR-USDT-SWAP, BTC-USD-210517-44000-C
// "instType": "SPOT", // SPOT, FUTURES, SWAP, OPTION
// "lever": "10",
// "listTime": "1548133413000",
// "lotSz": "0.00000001",
// "minSz": "0.00001",
// "optType": "",
// "quoteCcy": "USDT",
// "settleCcy": "",
// "state": "live",
// "stk": "",
// "tickSz": "0.1",
// "uly": ""
// }
// ],
// "msg": ""
// }
//
let mut dataResponse: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut marketsWithoutTest: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_984: bool = true;
while { if !__for_first_984 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_984 = false; i.as_f64().unwrap_or(f64::NAN) < ((dataResponse.len() as i64) as f64) } {
let mut data: Value = dataResponse.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut instId: Option<String> = self.safe_string_k(data.clone(), "instId", &[Value::Str("".into())]).as_str().map(str::to_owned);
if (instId.as_deref() == Some("")) {
continue;
}
if is_true(&self.isSandboxModeEnabled) {
let mut instFamily: Value = self.safe_string_k(data.clone(), "instFamily", &[Value::Str("".into())]);
if (starts_with(&instFamily, &Value::Str("TEST".into()))) {
continue;
}
}
append_to_array(&mut marketsWithoutTest, data);
}
}
return self.parse_markets(marketsWithoutTest);
Value::Null
}
/*
* @method
* @name okx#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://www.okx.com/docs-v5/en/#rest-api-funding-get-currencies
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// this endpoint requires authentication
// while fetchCurrencies is a public API method by design
// therefore we check the keys here
// and fallback to generating the currencies from the markets
let mut isSandboxMode: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
if !(self.check_required_credentials(&[Value::Bool(false)]).as_bool() == Some(true)) || (isSandboxMode.as_bool() == Some(true)) {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
}
//
// has['fetchCurrencies'] is currently set to true, but an unauthorized request returns
//
// {"msg":"Request header “OK_ACCESS_KEY“ can't be empty.","code":"50103"}
//
let mut response: Value = self.private_get_asset_currencies(&[params]).await;
//
// {
// "code": "0",
// "data": [
// {
// "canDep": true,
// "canInternal": false,
// "canWd": true,
// "ccy": "USDT",
// "chain": "USDT-TRC20",
// "logoLink": "https://static.coinall.ltd/cdn/assets/imgs/221/5F74EB20302D7761.png",
// "mainNet": false,
// "maxFee": "1.6",
// "maxWd": "8852150",
// "minFee": "0.8",
// "minWd": "2",
// "name": "Tether",
// "usedWdQuota": "0",
// "wdQuota": "500",
// "wdTickSz": "3"
// },
// {
// "canDep": true,
// "canInternal": false,
// "canWd": true,
// "ccy": "USDT",
// "chain": "USDT-ERC20",
// "logoLink": "https://static.coinall.ltd/cdn/assets/imgs/221/5F74EB20302D7761.png",
// "mainNet": false,
// "maxFee": "16",
// "maxWd": "8852150",
// "minFee": "8",
// "minWd": "2",
// "name": "Tether",
// "usedWdQuota": "0",
// "wdQuota": "500",
// "wdTickSz": "3"
// },
// ...
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut dataByCurrencyId: Value = self.group_by(data, Value::Str("ccy".into()), &[]);
let mut currencies: Value = object_values(&dataByCurrencyId);
return self.parse_currencies(currencies);
Value::Null
}
pub fn parse_currency(&self, mut currency: Value) -> Value {
let mut chains: Value = currency;
// currencies are grouped by chain entries, so there is at least one entry
let mut firstChain: Value = self.safe_dict(chains.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut currencyId: Value = self.safe_string_k(firstChain.clone(), "ccy", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut networks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut type_var: Value = Value::Str("crypto".into());
let mut chainsLength: f64 = ((chains.len() as i64) as f64);
{
let mut j: Value = Value::Int(0);
let mut __for_first_985: bool = true;
while { if !__for_first_985 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_985 = false; j.as_f64().unwrap_or(f64::NAN) < chainsLength } {
let mut chain: Value = self.safe_dict(chains.clone(), j.clone(), &[]);
// allow empty string for rare fiat-currencies, e.g. TRY
let mut networkId: Value = self.safe_string_k(chain.clone(), "chain", &[Value::Str("".into())]); // USDT-BEP20, USDT-Avalance-C, etc
if (networkId.as_str() == Some("")) {
// only happens for fiat 'TRY' currency
type_var = Value::Str("fiat".into());
}
let mut idParts: Value = split(&networkId, &Value::Str("-".into()));
let mut parts: Value = self.array_slice(idParts, Value::Int(1), &[]);
let mut chainPart: Value = join(&parts, &Value::Str("-".into()));
let mut networkCode: Value = self.network_id_to_code(&[chainPart, code.clone()]);
if (networkCode != Value::Null) {
if let Value::Dict(__d) = &mut networks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&networkCode), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), networkId);
m.insert("network".to_string(), networkCode.clone());
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), self.safe_bool_k(chain.clone(), "canDep", &[]));
m.insert("withdraw".to_string(), self.safe_bool_k(chain.clone(), "canWd", &[]));
m.insert("fee".to_string(), self.safe_number_k(chain.clone(), "fee", &[]));
m.insert("precision".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(chain.clone(), "wdTickSz", &[])]), &[]));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(chain.clone(), "minWd", &[]));
m.insert("max".to_string(), self.safe_number_k(chain.clone(), "maxWd", &[]));
m
}));
m
}));
m.insert("info".to_string(), chain);
m
})); }
}
}
}
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), chains);
m.insert("code".to_string(), code);
m.insert("id".to_string(), currencyId);
m.insert("name".to_string(), self.safe_string_k(firstChain, "name", &[]));
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), Value::Null);
m.insert("withdraw".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Null);
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("type".to_string(), type_var);
m.insert("networks".to_string(), networks);
m
}));
Value::Null
}
/*
* @method
* @name okx#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-order-book
* @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-full-order-book
* @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-rpi-order-book
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.method] 'publicGetMarketBooksFull' or 'publicGetMarketBooks' default is 'publicGetMarketBooks'
* @param {bool} [params.rpi] set to true to use the RPI order book, which consolidates organic and retail-price-improvement liquidity, capped at 400 entries
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut rpiparamsRpiVariable = self.handle_option_bool_and_params(params, Value::Str("fetchOrderBook".into()), Value::Str("rpi".into()), &[Value::Bool(false)]);
let mut rpi: Value = rpiparamsRpiVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsRpi: Value = rpiparamsRpiVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut methodparamsMethodVariable = self.handle_option_string_and_params(paramsRpi, Value::Str("fetchOrderBook".into()), Value::Str("method".into()), &[Value::Str("publicGetMarketBooks".into())]);
let mut method: Value = methodparamsMethodVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMethod: Value = methodparamsMethodVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut defaultLimit: Value = (if (method.as_str() == Some("publicGetMarketBooksFull")) { Value::Int(5000) } else { Value::Int(100) });
let mut requestedLimit: Value = (if (limit == Value::Null) { defaultLimit } else { limit });
// the rpi book hard-errors with 51000 "Parameter sz error." above 400,
// including the 5000 that publicGetMarketBooksFull defaults to
let mut limitResolved: Value = requestedLimit.clone();
if is_true(&rpi) && (requestedLimit.as_f64().unwrap_or(f64::NAN) > ((400i64) as f64)) {
limitResolved = Value::Int(400);
}
if (limitResolved != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("sz".into(), limitResolved.clone()); }; // max 400
}
let mut response: Value = Value::Null;
if is_true(&rpi) {
let __ws_arg_12 = self.extend(request.clone(), &[paramsMethod.clone()]);
response = self.public_get_market_books_rpi(&[__ws_arg_12]).await;
} else if (method.as_str() == Some("publicGetMarketBooksFull")) || (limitResolved.as_f64().unwrap_or(f64::NAN) > ((400i64) as f64)) {
let __ws_arg_13 = self.extend(request.clone(), &[paramsMethod.clone()]);
response = self.public_get_market_books_full(&[__ws_arg_13]).await;
} else {
let __ws_arg_14 = self.extend(request, &[paramsMethod]);
response = self.public_get_market_books(&[__ws_arg_14]).await;
}
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "asks": [
// ["0.07228","4.211619","0","2"], // price, amount, liquidated orders, total open orders
// ["0.0723","299.880364","0","2"],
// ["0.07231","3.72832","0","1"],
// ],
// "bids": [
// ["0.07221","18.5","0","1"],
// ["0.0722","18.5","0","1"],
// ["0.07219","0.505407","0","1"],
// ],
// "ts": "1621438475342"
// }
// ]
// }
//
// the rpi book has the same envelope, but each level is
// [ price, totalQty, nonRpiQty, count ] - totalQty already includes the
// rpi liquidity, so index 0 and 1 stay the price and the amount
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_k(first.clone(), "ts", &[]);
return self.parse_order_book(first, symbol, &[timestamp]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "instType": "SPOT", // SPOT, SWAP, etc
// "instId": "ETH-BTC", // BTC-USDT, BTC-USDT-SWAP, etc..
// "last": "0.07319",
// "lastSz": "0.044378", // base size for spot, or contracts amount for derivatives
// "askPx": "0.07322",
// "askSz": "4.2",
// "bidPx": "0.0732",
// "bidSz": "6.050058",
// "open24h": "0.07801",
// "high24h": "0.07975",
// "low24h": "0.06019",
// "volCcy24h": "11788.887619", // note, for derivatives this is base-amount
// "vol24h": "167493.829229",
// "ts": "1621440583784",
// "sodUtc0": "0.07872",
// "sodUtc8": "0.07345"
// }
//
// {
// instId: 'LTC-USDT',
// idxPx: '65.74',
// open24h: '65.37',
// high24h: '66.15',
// low24h: '64.97',
// sodUtc0: '65.68',
// sodUtc8: '65.54',
// ts: '1728467346900'
// },
//
let mut instType: Option<String> = self.safe_string_k(ticker.clone(), "instType", &[]).as_str().map(str::to_owned);
let mut marketType: Value = Value::Null;
if (instType.is_some()) {
marketType = (if (instType.as_deref() == Some("SPOT")) { Value::Str("spot".into()) } else { Value::Str("swap".into()) });
}
let mut timestamp: Value = self.safe_integer_k(ticker.clone(), "ts", &[]);
let mut marketId: Value = self.safe_string_k(ticker.clone(), "instId", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Str("-".into()), marketType]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut last: Value = self.safe_string_k(ticker.clone(), "last", &[]);
let mut open: Value = self.safe_string_k(ticker.clone(), "open24h", &[]);
let mut spot: Value = self.safe_bool_k(marketResolved.clone(), "spot", &[Value::Bool(false)]);
let mut quoteVolume: Value = (if (spot.as_bool() == Some(true)) { self.safe_string_k(ticker.clone(), "volCcy24h", &[]) } else { Value::Null });
let mut baseVolume: Value = self.safe_string_k(ticker.clone(), "vol24h", &[]);
let mut high: Value = self.safe_string_k(ticker.clone(), "high24h", &[]);
let mut low: Value = self.safe_string_k(ticker.clone(), "low24h", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), high);
m.insert("low".to_string(), low);
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "bidPx", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(ticker.clone(), "bidSz", &[]));
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "askPx", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(ticker.clone(), "askSz", &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), open);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), baseVolume);
m.insert("quoteVolume".to_string(), quoteVolume);
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "markPx", &[]));
m.insert("indexPrice".to_string(), self.safe_string_k(ticker.clone(), "idxPx", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name okx#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-ticker
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_15 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_ticker(&[__ws_arg_15]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "instType": "SPOT",
// "instId": "ETH-BTC",
// "last": "0.07319",
// "lastSz": "0.044378",
// "askPx": "0.07322",
// "askSz": "4.2",
// "bidPx": "0.0732",
// "bidSz": "6.050058",
// "open24h": "0.07801",
// "high24h": "0.07975",
// "low24h": "0.06019",
// "volCcy24h": "11788.887619",
// "vol24h": "167493.829229",
// "ts": "1621440583784",
// "sodUtc0": "0.07872",
// "sodUtc8": "0.07345"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(first, &[market]);
Value::Null
}
/*
* @method
* @name okx#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-tickers
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut market: Value = self.get_market_from_symbols(&[symbolsNormalized.clone()]);
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchTickers".into()), &[market, params]);
let mut marketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instType".to_string(), self.convert_to_instrument_type(marketType.clone()));
m
});
if (marketType.as_str() == Some("option")) {
let mut defaultUnderlying: Value = self.safe_string_k(self.options.clone(), "defaultUnderlying", &[Value::Str("BTC-USD".into())]);
let mut currencyId: Value = self.safe_string2(paramsMarketType.clone(), Value::Str("uly".into()), Value::Str("marketId".into()), &[defaultUnderlying]);
if (currencyId == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTickers() requires an underlying uly or marketId parameter for options markets".into()))));
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("uly".into(), currencyId); }
}
}
let __ws_arg_16 = self.extend(request, &[paramsMarketType]);
let mut response: Value = self.public_get_market_tickers(&[__ws_arg_16]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "instType": "SPOT",
// "instId": "BCD-BTC",
// "last": "0.0000769",
// "lastSz": "5.4788",
// "askPx": "0.0000777",
// "askSz": "3.2197",
// "bidPx": "0.0000757",
// "bidSz": "4.7509",
// "open24h": "0.0000885",
// "high24h": "0.0000917",
// "low24h": "0.0000596",
// "volCcy24h": "9.2877",
// "vol24h": "124824.1985",
// "ts": "1621441741434",
// "sodUtc0": "0.0000905",
// "sodUtc8": "0.0000729"
// },
// ]
// }
//
let mut tickers: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_tickers(tickers, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name okx#fetchMarkPrice
* @description fetches mark price for the market
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-mark-price
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_mark_price(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_17 = self.extend(request, &[params]);
let mut response: Value = self.public_get_public_mark_price(&[__ws_arg_17]).await;
//
// {
// "code": "0",
// "data": [
// {
// "instId": "ETH-USDT",
// "instType": "MARGIN",
// "markPx": "2403.98",
// "ts": "1728578500703"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[]);
return self.parse_ticker(self.safe_dict(data, Value::Int(0), &[]), &[market]);
Value::Null
}
/*
* @method
* @name okx#fetchMarkPrices
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-mark-price
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_mark_prices(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut market: Value = self.get_market_from_symbols(&[symbolsNormalized.clone()]);
let mut marketTypeparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchMarkPrices".into()), &[market, params, Value::Str("swap".into())]);
let mut marketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instType".to_string(), self.convert_to_instrument_type(marketType.clone()));
m
});
if (marketType.as_str() == Some("option")) {
let mut defaultUnderlying: Value = self.safe_string_k(self.options.clone(), "defaultUnderlying", &[Value::Str("BTC-USD".into())]);
let mut currencyId: Value = self.safe_string2(paramsMarketType.clone(), Value::Str("uly".into()), Value::Str("marketId".into()), &[defaultUnderlying]);
if (currencyId == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchMarkPrices() requires an underlying uly or marketId parameter for options markets".into()))));
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("uly".into(), currencyId); }
}
}
let __ws_arg_18 = self.extend(request, &[paramsMarketType]);
let mut response: Value = self.public_get_public_mark_price(&[__ws_arg_18]).await;
let mut tickers: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_tickers(tickers, &[symbolsNormalized]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// public fetchTrades
//
// {
// "instId": "ETH-BTC",
// "side": "sell",
// "sz": "0.119501",
// "px": "0.07065",
// "tradeId": "15826757",
// "ts": "1621446178316"
// }
//
// option: fetchTrades
//
// {
// "fillVol": "0.46387625976562497",
// "fwdPx": "26299.754935451125",
// "indexPx": "26309.7",
// "instFamily": "BTC-USD",
// "instId": "BTC-USD-230526-26000-C",
// "markPx": "0.042386283557554236",
// "optType": "C",
// "px": "0.0415",
// "side": "sell",
// "sz": "90",
// "tradeId": "112",
// "ts": "1683907480154"
// }
//
// private fetchMyTrades
//
// {
// "side": "buy",
// "fillSz": "0.007533",
// "fillPx": "2654.98",
// "fee": "-0.000007533",
// "ordId": "317321390244397056",
// "instType": "SPOT",
// "instId": "ETH-USDT",
// "clOrdId": "",
// "posSide": "net",
// "billId": "317321390265368576",
// "tag": "0",
// "execType": "T",
// "tradeId": "107601752",
// "feeCcy": "ETH",
// "ts": "1621927314985"
// }
//
let mut id: Value = self.safe_string_k(trade.clone(), "tradeId", &[]);
let mut marketId: Value = self.safe_string_k(trade.clone(), "instId", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Str("-".into())]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "ts", &[]);
let mut price: Value = self.safe_string2(trade.clone(), Value::Str("fillPx".into()), Value::Str("px".into()), &[]);
let mut amount: Value = self.safe_string2(trade.clone(), Value::Str("fillSz".into()), Value::Str("sz".into()), &[]);
let mut side: Value = self.safe_string_k(trade.clone(), "side", &[]);
let mut orderId: Value = self.safe_string_k(trade.clone(), "ordId", &[]);
let mut feeCostString: Value = self.safe_string_k(trade.clone(), "fee", &[]);
let mut fee: Value = Value::Null;
if (feeCostString != Value::Null) {
let mut feeCostSigned: Value = crate::precise::Precise::stringNeg(&feeCostString);
let mut feeCurrencyId: Value = self.safe_string_k(trade.clone(), "feeCcy", &[]);
let mut feeCurrencyCode: Value = self.safe_currency_code(feeCurrencyId, &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCostSigned);
m.insert("currency".to_string(), feeCurrencyCode);
m
});
}
let mut takerOrMaker: Value = self.safe_string_k(trade.clone(), "execType", &[]);
if (takerOrMaker.as_str() == Some("T")) {
takerOrMaker = Value::Str("taker".into());
} else if (takerOrMaker.as_str() == Some("M")) {
takerOrMaker = Value::Str("maker".into());
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("id".to_string(), id);
m.insert("order".to_string(), orderId);
m.insert("type".to_string(), Value::Null);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name okx#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://www.okx.com/docs-v5/en/#rest-api-market-data-get-trades
* @see https://www.okx.com/docs-v5/en/#rest-api-market-data-get-trades-history
* @see https://www.okx.com/docs-v5/en/#rest-api-public-data-get-option-trades
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.method] 'publicGetMarketTrades' or 'publicGetMarketHistoryTrades' default is 'publicGetMarketTrades'
* @param {boolean} [params.paginate] *only applies to publicGetMarketHistoryTrades* default false, when true will automatically paginate by calling this endpoint multiple times
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchTrades".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("tradeId".into()), Value::Str("after".into()), Value::Null, Value::Int(100)]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut response: Value = Value::Null;
if (market.as_map().and_then(|__m| __m.get("option")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let __ws_arg_19 = self.extend(request.clone(), &[paramsPaginate.clone()]);
response = self.public_get_public_option_trades(&[__ws_arg_19]).await;
} else {
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100
}
let mut methodparamsMethodVariable = self.handle_option_string_and_params(paramsPaginate, Value::Str("fetchTrades".into()), Value::Str("method".into()), &[Value::Str("publicGetMarketTrades".into())]);
let mut method: Value = methodparamsMethodVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMethod: Value = methodparamsMethodVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (method.as_str() == Some("publicGetMarketTrades")) {
let __ws_arg_20 = self.extend(request.clone(), &[paramsMethod.clone()]);
response = self.public_get_market_trades(&[__ws_arg_20]).await;
} else if (method.as_str() == Some("publicGetMarketHistoryTrades")) {
let __ws_arg_21 = self.extend(request, &[paramsMethod]);
response = self.public_get_market_history_trades(&[__ws_arg_21]).await;
}
}
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {"instId":"ETH-BTC","side":"sell","sz":"0.119501","px":"0.07065","tradeId":"15826757","ts":"1621446178316"},
// {"instId":"ETH-BTC","side":"sell","sz":"0.03","px":"0.07068","tradeId":"15826756","ts":"1621446178066"},
// {"instId":"ETH-BTC","side":"buy","sz":"0.507","px":"0.07069","tradeId":"15826755","ts":"1621446175085"},
// ]
// }
//
// option
//
// {
// "code": "0",
// "data": [
// {
// "fillVol": "0.46387625976562497",
// "fwdPx": "26299.754935451125",
// "indexPx": "26309.7",
// "instFamily": "BTC-USD",
// "instId": "BTC-USD-230526-26000-C",
// "markPx": "0.042386283557554236",
// "optType": "C",
// "px": "0.0415",
// "side": "sell",
// "sz": "90",
// "tradeId": "112",
// "ts": "1683907480154"
// },
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(data, &[market, since, limit]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// [
// "1678928760000", // timestamp
// "24341.4", // open
// "24344", // high
// "24313.2", // low
// "24323", // close
// "628", // contract volume
// "2.5819", // base volume
// "62800", // quote volume
// "0" // candlestick state
// ]
//
let mut type_var: Value = self.handle_market_type_and_params(Value::Str("fetchOHLCV".into()), &[market, Value::Null]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut volumeIndex: Value = (if (type_var.as_str() == Some("spot")) { Value::Int(5) } else { Value::Int(6) });
return Value::from(vec![self.safe_integer(ohlcv.clone(), Value::Int(0), &[]), self.safe_number(ohlcv.clone(), Value::Int(1), &[]), self.safe_number(ohlcv.clone(), Value::Int(2), &[]), self.safe_number(ohlcv.clone(), Value::Int(3), &[]), self.safe_number(ohlcv.clone(), Value::Int(4), &[]), self.safe_number(ohlcv, volumeIndex, &[])]);
Value::Null
}
/*
* @method
* @name okx#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://www.okx.com/docs-v5/en/#rest-api-market-data-get-candlesticks
* @see https://www.okx.com/docs-v5/en/#rest-api-market-data-get-candlesticks-history
* @see https://www.okx.com/docs-v5/en/#rest-api-market-data-get-mark-price-candlesticks
* @see https://www.okx.com/docs-v5/en/#rest-api-market-data-get-mark-price-candlesticks-history
* @see https://www.okx.com/docs-v5/en/#rest-api-market-data-get-index-candlesticks
* @see https://www.okx.com/docs-v5/en/#rest-api-market-data-get-index-candlesticks-history
* @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-candlesticks-history
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.price] "mark" or "index" for mark price and index price candles
* @param {int} [params.until] timestamp in ms of the latest candle to fetch
* @param {string} [params.type] "Candles" or "HistoryCandles", default is "Candles" for recent candles, "HistoryCandles" for older candles
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchOHLCV".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".into()), &[symbol, since.clone(), limit.clone(), timeframe.clone(), paramsPaginate.clone(), Value::Int(200)]).await;
}
let mut priceType: Value = self.safe_string_k(paramsPaginate.clone(), "price", &[]);
let mut isMarkOrIndex: Value = self.in_array(priceType.clone(), Value::from(vec![Value::Str("mark".into()), Value::Str("index".into())]));
let mut paramsPrice: Value = self.omit(paramsPaginate, Value::Str("price".into()), &[]);
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchOHLCV", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timezone: Value = self.safe_string_k(options.clone(), "timezone", &[Value::Str("UTC".into())]);
let mut limitIsUndefined: bool = limit == Value::Null;
// default 100, max 300, only 100 if 'mark' or 'index'
let mut requestMaxLimit: Value = Value::Int(300);
if is_true(&isMarkOrIndex) {
requestMaxLimit = Value::Int(100);
}
let mut limitResolved: Value = Value::Int(100);
if (limit != Value::Null) {
limitResolved = crate::runtime::Math::min(&limit, &requestMaxLimit);
}
let mut duration: Value = self.parse_timeframe(timeframe.clone());
let mut bar: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
if (timezone.as_str() == Some("UTC")) && (duration.as_f64().unwrap_or(f64::NAN) >= ((21600i64) as f64)) {
bar = Value::Str(format!("{}{}", bar, to_lower(&timezone)).into());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("bar".to_string(), bar);
m.insert("limit".to_string(), limitResolved.clone());
m
});
let mut defaultType: Value = Value::Str("Candles".into());
if (since != Value::Null) {
let mut now: Value = self.milliseconds();
let mut durationInMilliseconds: Value = (match (&(duration), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
// switch to history candles if since is past the cutoff for current candles
let mut historyBorder: Value = (match (&(now), &(((match (&(((match (&(Value::Int(1440)), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }))), &(durationInMilliseconds)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
if since.as_f64().unwrap_or(f64::NAN) < historyBorder.as_f64().unwrap_or(f64::NAN) {
defaultType = Value::Str("HistoryCandles".into());
let mut maxLimit: Value = (if is_true(&isMarkOrIndex) { Value::Int(100) } else { Value::Int(300) });
limitResolved = crate::runtime::Math::min(&limitResolved, &maxLimit);
}
let mut startTime: Value = crate::runtime::Math::max(&(match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &Value::Int(0));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), startTime); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("after".into(), self.sum(&[since.clone(), (match (&(durationInMilliseconds), &(limitResolved)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })])); }
}
let mut until: Value = self.safe_integer_k(paramsPrice.clone(), "until", &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("after".into(), until.clone()); }
}
let mut paramsUntil: Value = (if (until != Value::Null) { self.omit(paramsPrice.clone(), Value::Str("until".into()), &[]) } else { paramsPrice });
defaultType = self.safe_string_k(options, "type", &[defaultType.clone()]); // Candles or HistoryCandles
let mut type_var: Option<String> = self.safe_string_k(paramsUntil.clone(), "type", &[defaultType]).as_str().map(str::to_owned);
let mut paramsType: Value = self.omit(paramsUntil, Value::Str("type".into()), &[]);
let mut isHistoryCandles: bool = type_var.as_deref() == Some("HistoryCandles");
let mut response: Value = Value::Null;
if (priceType.as_str() == Some("mark")) {
if isHistoryCandles {
let __ws_arg_22 = self.extend(request.clone(), &[paramsType.clone()]);
response = self.public_get_market_history_mark_price_candles(&[__ws_arg_22]).await;
} else {
let __ws_arg_23 = self.extend(request.clone(), &[paramsType.clone()]);
response = self.public_get_market_mark_price_candles(&[__ws_arg_23]).await;
}
} else if (priceType.as_str() == Some("index")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), crate::value::get_value_k(&market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), "instFamily")); }; // okx index candles require instFamily instead of instId
if isHistoryCandles {
let __ws_arg_24 = self.extend(request.clone(), &[paramsType.clone()]);
response = self.public_get_market_history_index_candles(&[__ws_arg_24]).await;
} else {
let __ws_arg_25 = self.extend(request.clone(), &[paramsType.clone()]);
response = self.public_get_market_index_candles(&[__ws_arg_25]).await;
}
} else {
if isHistoryCandles {
if limitIsUndefined && (limitResolved.as_f64() == Some(100.0)) {
limitResolved = Value::Int(300);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), Value::Int(300)); }; // reassign to 300, but this whole logic needs to be simplified...
}
let __ws_arg_26 = self.extend(request.clone(), &[paramsType.clone()]);
response = self.public_get_market_history_candles(&[__ws_arg_26]).await;
} else {
let __ws_arg_27 = self.extend(request, &[paramsType]);
response = self.public_get_market_candles(&[__ws_arg_27]).await;
}
}
//
// {
// "code": "0",
// "msg": "",
// "data": [
// ["1678928760000","24341.4","24344","24313.2","24323","628","2.5819","62800","0"],
// ["1678928700000","24324.1","24347.6","24321.7","24341.4","2565","10.5401","256500","1"],
// ["1678928640000","24300.2","24324.1","24288","24324.1","3304","13.5937","330400","1"],
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_ohlc_vs(data, &[market, timeframe, since, limitResolved]);
Value::Null
}
/*
* @method
* @name okx#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-funding-rate-history
* @param {string} symbol unified symbol of the market to fetch the funding rate history for
* @param {int} [since] timestamp in ms of the earliest funding rate to fetch
* @param {int} [limit] the maximum amount of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure} to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure}
*/
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchFundingRateHistory".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchFundingRateHistory".into()), &[symbol.clone(), since.clone(), limit.clone(), Value::Str("8h".into()), paramsPaginate.clone(), Value::Int(100)]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), crate::runtime::Math::max(&(match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &Value::Int(0))); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_28 = self.extend(request, &[paramsPaginate]);
let mut response: Value = self.public_get_public_funding_rate_history(&[__ws_arg_28]).await;
//
// {
// "code":"0",
// "msg":"",
// "data":[
// {
// "instType":"SWAP",
// "instId":"BTC-USDT-SWAP",
// "fundingRate":"0.018",
// "realizedRate":"0.017",
// "fundingTime":"1597026383085"
// },
// {
// "instType":"SWAP",
// "instId":"BTC-USDT-SWAP",
// "fundingRate":"0.018",
// "realizedRate":"0.017",
// "fundingTime":"1597026383085"
// }
// ]
// }
//
let mut rates: Value = Value::from(vec![]);
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_986: bool = true;
while { if !__for_first_986 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_986 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut rate: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_k(rate.clone(), "fundingTime", &[]);
append_to_array(&mut rates, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), rate.clone());
m.insert("symbol".to_string(), self.safe_symbol(self.safe_string_k(rate.clone(), "instId", &[]), &[]));
m.insert("fundingRate".to_string(), self.safe_number_k(rate, "realizedRate", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
}));
}
}
let mut sorted: Value = self.sort_by(rates, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[self.safe_string_k(market, "symbol", &[]), since, limit]);
Value::Null
}
pub fn parse_balance_by_type(&self, mut type_var: Value, mut response: Value) -> Value {
if (type_var.as_str() == Some("funding")) {
return self.parse_funding_balance(response.clone());
} else {
return self.parse_trading_balance(response);
}
Value::Null
}
pub fn parse_trading_balance(&self, mut response: Value) -> Value {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_k(first.clone(), "uTime", &[]);
let mut details: Value = self.safe_list_k(first, "details", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_987: bool = true;
while { if !__for_first_987 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_987 = false; i.as_f64().unwrap_or(f64::NAN) < ((details.len() as i64) as f64) } {
let mut balance: Value = self.safe_dict(details.clone(), i.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "ccy", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
// it may be incorrect to use total, free and used for swap accounts
let mut eq: Value = self.safe_string_k(balance.clone(), "eq", &[]);
let mut availEq: Value = self.safe_string_k(balance.clone(), "availEq", &[]);
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), eq); }
if (availEq == Value::Null) {
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(balance.clone(), "availBal", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(balance, "frozenBal", &[])); }
} else {
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), availEq); }
}
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
}
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("timestamp".into(), timestamp.clone()); }
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("datetime".into(), self.iso8601(timestamp)); }
return self.safe_balance(result);
Value::Null
}
pub fn parse_funding_balance(&self, mut response: Value) -> Value {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_988: bool = true;
while { if !__for_first_988 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_988 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut balance: Value = self.safe_dict(data.clone(), i.clone(), &[]);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "ccy", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
// it may be incorrect to use total, free and used for swap accounts
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(balance.clone(), "bal", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(balance.clone(), "availBal", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(balance, "frozenBal", &[])); }
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
}
return self.safe_balance(result);
Value::Null
}
pub fn parse_trading_fee(&self, mut fee: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market]));
m.insert("maker".to_string(), self.parse_number(crate::precise::Precise::stringNeg(&self.safe_string2(fee.clone(), Value::Str("maker".into()), Value::Str("makerU".into()), &[])), &[]));
m.insert("taker".to_string(), self.parse_number(crate::precise::Precise::stringNeg(&self.safe_string2(fee, Value::Str("taker".into()), Value::Str("takerU".into()), &[])), &[]));
m.insert("percentage".to_string(), Value::Null);
m.insert("tierBased".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name okx#fetchTradingFee
* @description fetch the trading fees for a market
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-fee-rates
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [fee structure]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_trading_fee(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instType".to_string(), self.convert_to_instrument_type(market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null)));
m
});
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
} else if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) || (market.as_map().and_then(|__m| __m.get("future")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) || (market.as_map().and_then(|__m| __m.get("option")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("uly".into(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), Value::Str("-".into())).into()), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)).into())); }
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchTradingFee() supports spot, swap, future or option markets only".into()))));
}
let __ws_arg_29 = self.extend(request, &[params]);
let mut response: Value = self.private_get_account_trade_fee(&[__ws_arg_29]).await;
//
// {
// "code": "0",
// "data": [
// {
// "category": "1",
// "delivery": "",
// "exercise": "",
// "instType": "SPOT",
// "level": "Lv1",
// "maker": "-0.0008",
// "taker": "-0.001",
// "ts": "1639043138472"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_trading_fee(first, &[market]);
Value::Null
}
/*
* @method
* @name okx#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-balance
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-balance
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] wallet type, ['funding' or 'trading'] default is 'trading'
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut marketTypequeryVariable = self.handle_market_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, params]);
let mut marketType: Value = marketTypequeryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = marketTypequeryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (marketType.as_str() == Some("funding")) {
let __ws_arg_30 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_asset_balances(&[__ws_arg_30]).await;
} else {
let __ws_arg_31 = self.extend(request, &[query]);
response = self.private_get_account_balance(&[__ws_arg_31]).await;
}
return self.parse_balance_by_type(marketType, response);
Value::Null
}
/*
* @method
* @name okx#createMarketBuyOrderWithCost
* @description create a market buy order by providing the symbol and cost
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_market_buy_order_with_cost(&mut self, mut symbol: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createMarketBuyOrderWithCost() supports spot markets only".into()))));
}
let mut req: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("createMarketBuyOrderRequiresPrice".to_string(), Value::Bool(false));
m.insert("tgtCcy".to_string(), Value::Str("quote_ccy".into()));
m
});
let __ws_arg_32 = self.extend(req, &[params]);
return self.create_order(symbol, Value::Str("market".into()), Value::Str("buy".into()), cost, &[Value::Null, __ws_arg_32]).await;
Value::Null
}
/*
* @method
* @name okx#createMarketSellOrderWithCost
* @description create a market buy order by providing the symbol and cost
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_market_sell_order_with_cost(&mut self, mut symbol: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createMarketSellOrderWithCost() supports spot markets only".into()))));
}
let mut req: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("createMarketBuyOrderRequiresPrice".to_string(), Value::Bool(false));
m.insert("tgtCcy".to_string(), Value::Str("quote_ccy".into()));
m
});
let __ws_arg_33 = self.extend(req, &[params]);
return self.create_order(symbol, Value::Str("market".into()), Value::Str("sell".into()), cost, &[Value::Null, __ws_arg_33]).await;
Value::Null
}
pub fn create_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
let mut market: Value = self.market(symbol.clone());
let mut takeProfitPrice: Value = self.safe_value2(params.clone(), Value::Str("takeProfitPrice".into()), Value::Str("tpTriggerPx".into()), &[]);
let mut stopLossPrice: Value = self.safe_value2(params.clone(), Value::Str("stopLossPrice".into()), Value::Str("slTriggerPx".into()), &[]);
let mut conditional: bool = (stopLossPrice != Value::Null) || (takeProfitPrice != Value::Null) || (type_var.as_str() == Some("conditional"));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("side".to_string(), side.clone());
m.insert("ordType".to_string(), type_var.clone());
m
});
let mut isConditionalOrOCO: bool = conditional || (type_var.as_str() == Some("oco"));
let mut closeFraction: Option<String> = self.safe_string_k(params.clone(), "closeFraction", &[]).as_str().map(str::to_owned);
let mut shouldOmitSize: bool = isConditionalOrOCO && (closeFraction.is_some());
if !shouldOmitSize {
add_element_to_object(&mut request, &Value::Str("sz".into()), self.amount_to_precision(symbol.clone(), amount.clone()));
}
let mut spot: Value = market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null);
let mut contract: Value = market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null);
let mut triggerPrice: Value = self.safe_value_n(params.clone(), Value::from(vec![Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("triggerPx".into())]), &[]);
let mut timeInForce: Option<String> = self.safe_string_k(params.clone(), "timeInForce", &[Value::Str("GTC".into())]).as_str().map(str::to_owned);
// const takeProfitPrice = this.safeValue2 (params, 'takeProfitPrice', 'tpTriggerPx');
let mut tpOrdPx: Value = self.safe_number_k(params.clone(), "tpOrdPx", &[price.clone()]);
let mut tpTriggerPxType: Value = self.safe_string_k(params.clone(), "tpTriggerPxType", &[Value::Str("last".into())]);
// const stopLossPrice = this.safeValue2 (params, 'stopLossPrice', 'slTriggerPx');
let mut slOrdPx: Value = self.safe_number_k(params.clone(), "slOrdPx", &[price.clone()]);
let mut slTriggerPxType: Value = self.safe_string_k(params.clone(), "slTriggerPxType", &[Value::Str("last".into())]);
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clOrdId".into()), Value::Str("clientOrderId".into()), &[]);
let mut stopLoss: Value = self.safe_dict_k(params.clone(), "stopLoss", &[]);
let mut takeProfit: Value = self.safe_dict_k(params.clone(), "takeProfit", &[]);
let mut hasStopLoss: bool = stopLoss != Value::Null;
let mut hasTakeProfit: bool = takeProfit != Value::Null;
let mut trailingPercent: Value = self.safe_string2(params.clone(), Value::Str("trailingPercent".into()), Value::Str("callbackRatio".into()), &[]);
let mut isTrailingPercentOrder: bool = trailingPercent != Value::Null;
let mut trailingPrice: Value = self.safe_string2(params.clone(), Value::Str("trailingPrice".into()), Value::Str("callbackSpread".into()), &[]);
let mut isTrailingPriceOrder: bool = trailingPrice != Value::Null;
let mut trigger: bool = (triggerPrice != Value::Null) || (type_var.as_str() == Some("trigger"));
let mut isReduceOnly: bool = is_true(&(self.safe_bool_k(params.clone(), "reduceOnly", &[Value::Bool(false)]))) || (closeFraction.is_some());
let mut defaultMarginMode: Value = self.safe_string2(self.options.clone(), Value::Str("defaultMarginMode".into()), Value::Str("marginMode".into()), &[Value::Str("cross".into())]);
let mut marginMode: Value = self.safe_string2(params.clone(), Value::Str("marginMode".into()), Value::Str("tdMode".into()), &[]); // cross or isolated, tdMode not omitted so as to be extended into the request
let mut margin: Value = Value::Bool(false);
if (marginMode != Value::Null) && (marginMode.as_str() != Some("cash")) {
margin = Value::Bool(true);
} else {
marginMode = defaultMarginMode;
margin = self.safe_bool_k(params.clone(), "margin", &[Value::Bool(false)]);
}
// position side / hedged options only apply to swap and future orders
let mut isSwapOrFuture: bool = (contract.as_bool() == Some(true)) && ((market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) || (market.as_map().and_then(|__m| __m.get("future")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)));
let mut positionSideparamsPositionSideVariable = self.handle_option_string_and_params(params.clone(), Value::Str("createOrder".into()), Value::Str("positionSide".into()), &[]);
let mut positionSide: Value = positionSideparamsPositionSideVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPositionSide: Value = positionSideparamsPositionSideVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut paramsSwapOrFuture: Value = params.clone();
if isSwapOrFuture {
paramsSwapOrFuture = paramsPositionSide;
}
let mut usesHedged: bool = isSwapOrFuture && (positionSide == Value::Null);
let mut hedgedparamsHedgedOptionVariable = self.handle_option_bool_and_params(paramsSwapOrFuture.clone(), Value::Str("createOrder".into()), Value::Str("hedged".into()), &[]);
let mut hedged: Value = hedgedparamsHedgedOptionVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsHedgedOption: Value = hedgedparamsHedgedOptionVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut paramsHedged: Value = paramsSwapOrFuture;
if usesHedged {
paramsHedged = paramsHedgedOption;
}
let mut omitReduceOnly: bool = usesHedged && (hedged.as_bool() == Some(true)) && isReduceOnly;
let mut paramsReduceOnly: Value = paramsHedged.clone();
if omitReduceOnly {
paramsReduceOnly = self.omit(paramsHedged, Value::Str("reduceOnly".into()), &[]);
}
if (spot.as_bool() == Some(true)) {
if (margin.as_bool() == Some(true)) {
let mut defaultCurrency: Value = (if (side.as_str() == Some("buy")) { market.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null) } else { market.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null) });
let mut currency: Value = self.safe_string_k(params, "ccy", &[defaultCurrency]);
add_element_to_object(&mut request, &Value::Str("ccy".into()), self.safe_currency_code(currency, &[]));
}
let mut tradeMode: Value = (if (margin.as_bool() == Some(true)) { marginMode.clone() } else { Value::Str("cash".into()) });
add_element_to_object(&mut request, &Value::Str("tdMode".into()), tradeMode);
} else if (contract.as_bool() == Some(true)) {
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) || (market.as_map().and_then(|__m| __m.get("future")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if (positionSide != Value::Null) {
add_element_to_object(&mut request, &Value::Str("posSide".into()), positionSide);
} else {
if (hedged.as_bool() == Some(true)) {
let mut isBuy: bool = side.as_str() == Some("buy");
let mut isProtective: bool = (takeProfitPrice != Value::Null) || (stopLossPrice != Value::Null) || isReduceOnly;
if isProtective {
// in case of protective orders, the posSide should be opposite of position side
// reduceOnly is emulated and not natively supported by the exchange
add_element_to_object(&mut request, &Value::Str("posSide".into()), (if isBuy { Value::Str("short".into()) } else { Value::Str("long".into()) }));
} else {
add_element_to_object(&mut request, &Value::Str("posSide".into()), (if isBuy { Value::Str("long".into()) } else { Value::Str("short".into()) }));
}
}
}
}
add_element_to_object(&mut request, &Value::Str("tdMode".into()), marginMode.clone());
}
let mut isMarketOrder: Value = Value::Bool(type_var.as_str() == Some("market"));
let mut postOnlyparamsPostOnlyVariable = self.handle_post_only(isMarketOrder.clone(), Value::Bool(type_var.as_str() == Some("post_only")), &[paramsReduceOnly]);
let mut postOnly: Value = postOnlyparamsPostOnlyVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPostOnly: Value = postOnlyparamsPostOnlyVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut orderParams: Value = self.omit(paramsPostOnly, Value::from(vec![Value::Str("currency".into()), Value::Str("ccy".into()), Value::Str("marginMode".into()), Value::Str("timeInForce".into()), Value::Str("stopPrice".into()), Value::Str("triggerPrice".into()), Value::Str("clientOrderId".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("slOrdPx".into()), Value::Str("tpOrdPx".into()), Value::Str("margin".into()), Value::Str("stopLoss".into()), Value::Str("takeProfit".into()), Value::Str("trailingPercent".into())]), &[]);
let mut ioc: bool = (timeInForce.as_deref() == Some("IOC")) || (type_var.as_str() == Some("ioc"));
let mut fok: bool = (timeInForce.as_deref() == Some("FOK")) || (type_var.as_str() == Some("fok"));
// const conditional = (stopLossPrice !== undefined) || (takeProfitPrice !== undefined) || (type === 'conditional');
let mut marketIOC: bool = (matches!(&isMarketOrder, Value::Bool(true)) && ioc) || (type_var.as_str() == Some("optimal_limit_ioc"));
let mut defaultTgtCcy: Value = self.safe_string_k(self.options.clone(), "tgtCcy", &[Value::Str("base_ccy".into())]);
let mut tgtCcy: Value = self.safe_string_k(orderParams.clone(), "tgtCcy", &[defaultTgtCcy]);
if (contract.as_bool() != Some(true)) && (margin.as_bool() != Some(true)) {
add_element_to_object(&mut request, &Value::Str("tgtCcy".into()), tgtCcy.clone());
}
if matches!(&isMarketOrder, Value::Bool(true)) || marketIOC {
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("market".into()));
if (spot.as_bool() == Some(true)) && (side.as_str() == Some("buy")) {
// spot market buy: "sz" can refer either to base currency units or to quote currency units
// see documentation: https://www.okx.com/docs-v5/en/#rest-api-trade-place-order
if (tgtCcy.as_str() == Some("quote_ccy")) {
// quote_ccy: sz refers to units of quote currency
let mut createMarketBuyOrderRequiresPriceparamsRequiresPriceVariable = self.handle_option_bool_and_params(orderParams.clone(), Value::Str("createOrder".into()), Value::Str("createMarketBuyOrderRequiresPrice".into()), &[Value::Bool(true)]);
let mut createMarketBuyOrderRequiresPrice: Value = createMarketBuyOrderRequiresPriceparamsRequiresPriceVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsRequiresPrice: Value = createMarketBuyOrderRequiresPriceparamsRequiresPriceVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut notional: Value = self.safe_number2(paramsRequiresPrice.clone(), Value::Str("cost".into()), Value::Str("sz".into()), &[]);
orderParams = self.omit(paramsRequiresPrice, Value::from(vec![Value::Str("cost".into()), Value::Str("sz".into())]), &[]);
if is_true(&createMarketBuyOrderRequiresPrice) {
if (price != Value::Null) {
if (notional == Value::Null) {
let mut amountString: Value = self.number_to_string(amount.clone());
let mut priceString: Value = self.number_to_string(price.clone());
let mut quoteAmount: Value = crate::precise::Precise::stringMul(&amountString, &priceString);
notional = self.parse_number(quoteAmount, &[]);
}
} else if (notional == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires the price argument with market buy orders to calculate total order cost (amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = false and supply the total cost value in the 'amount' argument or in the 'cost' unified extra parameter or in exchange-specific 'sz' extra parameter (the exchange-specific behaviour)".into()))));
}
} else {
notional = (if (notional == Value::Null) { amount } else { notional.clone() });
}
add_element_to_object(&mut request, &Value::Str("sz".into()), self.cost_to_precision(symbol.clone(), notional));
}
}
if marketIOC && (contract.as_bool() == Some(true)) {
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("optimal_limit_ioc".into()));
}
} else {
if (!trigger) && (!conditional) {
add_element_to_object(&mut request, &Value::Str("px".into()), self.price_to_precision(symbol.clone(), price.clone()));
}
}
if is_true(&postOnly) {
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("post_only".into()));
} else if ioc && !marketIOC {
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("ioc".into()));
} else if fok {
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("fok".into()));
}
if isTrailingPercentOrder {
let mut convertedTrailingPercent: Value = crate::precise::Precise::stringDiv(&trailingPercent, &Value::Str("100".into()));
add_element_to_object(&mut request, &Value::Str("callbackRatio".into()), convertedTrailingPercent);
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("move_order_stop".into()));
} else if isTrailingPriceOrder {
add_element_to_object(&mut request, &Value::Str("callbackSpread".into()), trailingPrice);
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("move_order_stop".into()));
} else if hasStopLoss || hasTakeProfit {
let mut attachAlgoOrd: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if hasStopLoss {
let mut stopLossTriggerPrice: Value = self.safe_value_n(stopLoss.clone(), Value::from(vec![Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("slTriggerPx".into())]), &[]);
if (stopLossTriggerPrice == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a trigger price in params[\"stopLoss\"][\"triggerPrice\"], or params[\"stopLoss\"][\"stopPrice\"], or params[\"stopLoss\"][\"slTriggerPx\"] for a stop loss order".into()))));
}
let mut slTriggerPx: Value = self.price_to_precision(symbol.clone(), stopLossTriggerPrice);
let mut slOrder: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if let Value::Dict(__d) = &mut slOrder { std::sync::Arc::make_mut(__d).insert("slTriggerPx".into(), slTriggerPx); }
let mut stopLossLimitPrice: Value = self.safe_value_n(stopLoss.clone(), Value::from(vec![Value::Str("price".into()), Value::Str("stopLossPrice".into()), Value::Str("slOrdPx".into())]), &[]);
let mut stopLossOrderType: Option<String> = self.safe_string_k(stopLoss.clone(), "type", &[]).as_str().map(str::to_owned);
if (stopLossOrderType.is_some()) {
let mut stopLossLimitOrderType: bool = stopLossOrderType.as_deref() == Some("limit");
let mut stopLossMarketOrderType: bool = stopLossOrderType.as_deref() == Some("market");
if (!stopLossLimitOrderType) && (!stopLossMarketOrderType) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() params[\"stopLoss\"][\"type\"] must be either \"limit\" or \"market\"".into()))));
} else if stopLossLimitOrderType {
if (stopLossLimitPrice == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a limit price in params[\"stopLoss\"][\"price\"] or params[\"stopLoss\"][\"slOrdPx\"] for a stop loss limit order".into()))));
} else {
if let Value::Dict(__d) = &mut slOrder { std::sync::Arc::make_mut(__d).insert("slOrdPx".into(), self.price_to_precision(symbol.clone(), stopLossLimitPrice.clone())); }
}
} else if (stopLossOrderType.as_deref() == Some("market")) {
if let Value::Dict(__d) = &mut slOrder { std::sync::Arc::make_mut(__d).insert("slOrdPx".into(), Value::Str("-1".into())); }
}
} else if (stopLossLimitPrice != Value::Null) {
if let Value::Dict(__d) = &mut slOrder { std::sync::Arc::make_mut(__d).insert("slOrdPx".into(), self.price_to_precision(symbol.clone(), stopLossLimitPrice)); }; // limit sl order
} else {
if let Value::Dict(__d) = &mut slOrder { std::sync::Arc::make_mut(__d).insert("slOrdPx".into(), Value::Str("-1".into())); }; // market sl order
}
let mut stopLossTriggerPriceType: Value = self.safe_string2(stopLoss, Value::Str("triggerPriceType".into()), Value::Str("slTriggerPxType".into()), &[Value::Str("last".into())]);
if (stopLossTriggerPriceType != Value::Null) {
if (stopLossTriggerPriceType.as_str() != Some("last")) && (stopLossTriggerPriceType.as_str() != Some("index")) && (stopLossTriggerPriceType.as_str() != Some("mark")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() stop loss trigger price type must be one of \"last\", \"index\" or \"mark\"".into()))));
}
if let Value::Dict(__d) = &mut slOrder { std::sync::Arc::make_mut(__d).insert("slTriggerPxType".into(), stopLossTriggerPriceType); }
}
attachAlgoOrd = self.extend(attachAlgoOrd.clone(), &[slOrder]);
}
if hasTakeProfit {
let mut takeProfitTriggerPrice: Value = self.safe_value_n(takeProfit.clone(), Value::from(vec![Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("tpTriggerPx".into())]), &[]);
if (takeProfitTriggerPrice == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a trigger price in params[\"takeProfit\"][\"triggerPrice\"], or params[\"takeProfit\"][\"stopPrice\"], or params[\"takeProfit\"][\"tpTriggerPx\"] for a take profit order".into()))));
}
let mut tpOrder: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if let Value::Dict(__d) = &mut tpOrder { std::sync::Arc::make_mut(__d).insert("tpTriggerPx".into(), self.price_to_precision(symbol.clone(), takeProfitTriggerPrice)); }
let mut takeProfitLimitPrice: Value = self.safe_value_n(takeProfit.clone(), Value::from(vec![Value::Str("price".into()), Value::Str("takeProfitPrice".into()), Value::Str("tpOrdPx".into())]), &[]);
let mut takeProfitOrderType: Value = self.safe_string2(takeProfit.clone(), Value::Str("type".into()), Value::Str("tpOrdKind".into()), &[]);
if (takeProfitOrderType != Value::Null) {
let mut takeProfitLimitOrderType: bool = takeProfitOrderType.as_str() == Some("limit");
let mut takeProfitMarketOrderType: bool = takeProfitOrderType.as_str() == Some("market");
if (!takeProfitLimitOrderType) && (!takeProfitMarketOrderType) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() params[\"takeProfit\"][\"type\"] must be either \"limit\" or \"market\"".into()))));
} else if takeProfitLimitOrderType {
if (takeProfitLimitPrice == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a limit price in params[\"takeProfit\"][\"price\"] or params[\"takeProfit\"][\"tpOrdPx\"] for a take profit limit order".into()))));
} else {
if let Value::Dict(__d) = &mut tpOrder { std::sync::Arc::make_mut(__d).insert("tpOrdKind".into(), takeProfitOrderType.clone()); }
if let Value::Dict(__d) = &mut tpOrder { std::sync::Arc::make_mut(__d).insert("tpOrdPx".into(), self.price_to_precision(symbol.clone(), takeProfitLimitPrice.clone())); }
}
} else if (takeProfitOrderType.as_str() == Some("market")) {
if let Value::Dict(__d) = &mut tpOrder { std::sync::Arc::make_mut(__d).insert("tpOrdPx".into(), Value::Str("-1".into())); }
}
} else if (takeProfitLimitPrice != Value::Null) {
if let Value::Dict(__d) = &mut tpOrder { std::sync::Arc::make_mut(__d).insert("tpOrdKind".into(), Value::Str("limit".into())); }
if let Value::Dict(__d) = &mut tpOrder { std::sync::Arc::make_mut(__d).insert("tpOrdPx".into(), self.price_to_precision(symbol.clone(), takeProfitLimitPrice)); }; // limit tp order
} else {
if let Value::Dict(__d) = &mut tpOrder { std::sync::Arc::make_mut(__d).insert("tpOrdPx".into(), Value::Str("-1".into())); }; // market tp order
}
let mut takeProfitTriggerPriceType: Value = self.safe_string2(takeProfit, Value::Str("triggerPriceType".into()), Value::Str("tpTriggerPxType".into()), &[Value::Str("last".into())]);
if (takeProfitTriggerPriceType != Value::Null) {
if (takeProfitTriggerPriceType.as_str() != Some("last")) && (takeProfitTriggerPriceType.as_str() != Some("index")) && (takeProfitTriggerPriceType.as_str() != Some("mark")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() take profit trigger price type must be one of \"last\", \"index\" or \"mark\"".into()))));
}
if let Value::Dict(__d) = &mut tpOrder { std::sync::Arc::make_mut(__d).insert("tpTriggerPxType".into(), takeProfitTriggerPriceType); }
}
attachAlgoOrd = self.extend(attachAlgoOrd.clone(), &[tpOrder]);
}
let mut attachOrdKeys: Value = object_keys(&attachAlgoOrd);
let mut attachOrdLen: f64 = ((attachOrdKeys.len() as i64) as f64);
if attachOrdLen > ((0i64) as f64) {
add_element_to_object(&mut request, &Value::Str("attachAlgoOrds".into()), Value::from(vec![attachAlgoOrd]));
}
}
// algo order details
if trigger {
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("trigger".into()));
add_element_to_object(&mut request, &Value::Str("triggerPx".into()), self.price_to_precision(symbol.clone(), triggerPrice));
add_element_to_object(&mut request, &Value::Str("orderPx".into()), (if matches!(&isMarketOrder, Value::Bool(true)) { Value::Str("-1".into()) } else { self.price_to_precision(symbol.clone(), price) }));
} else if conditional {
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("conditional".into()));
let mut twoWayCondition: bool = (takeProfitPrice != Value::Null) && (stopLossPrice != Value::Null);
// if TP and SL are sent together
// as ordType 'conditional' only stop-loss order will be applied
// tpOrdKind is 'condition' which is the default
if twoWayCondition {
add_element_to_object(&mut request, &Value::Str("ordType".into()), Value::Str("oco".into()));
}
if (side.as_str() == Some("sell")) {
request = self.omit(request.clone(), Value::Str("tgtCcy".into()), &[]);
}
if (self.safe_string_k(request.clone(), "tdMode", &[]).as_str() == Some("cash")) {
// for some reason tdMode = cash throws
// {"code":"1","data":[{"algoClOrdId":"","algoId":"","clOrdId":"","sCode":"51000","sMsg":"Parameter tdMode error ","tag":""}],"msg":""}
add_element_to_object(&mut request, &Value::Str("tdMode".into()), marginMode);
}
if (takeProfitPrice != Value::Null) {
add_element_to_object(&mut request, &Value::Str("tpTriggerPx".into()), self.price_to_precision(symbol.clone(), takeProfitPrice));
let mut tpOrdPxReq: Value = Value::Str("-1".into());
if (tpOrdPx != Value::Null) {
tpOrdPxReq = self.price_to_precision(symbol.clone(), tpOrdPx);
}
add_element_to_object(&mut request, &Value::Str("tpOrdPx".into()), tpOrdPxReq);
add_element_to_object(&mut request, &Value::Str("tpTriggerPxType".into()), tpTriggerPxType);
}
if (stopLossPrice != Value::Null) {
add_element_to_object(&mut request, &Value::Str("slTriggerPx".into()), self.price_to_precision(symbol.clone(), stopLossPrice));
let mut slOrdPxReq: Value = Value::Str("-1".into());
if (slOrdPx != Value::Null) {
slOrdPxReq = self.price_to_precision(symbol, slOrdPx);
}
add_element_to_object(&mut request, &Value::Str("slOrdPx".into()), slOrdPxReq);
add_element_to_object(&mut request, &Value::Str("slTriggerPxType".into()), slTriggerPxType);
}
}
// unified stp
let mut selfTradePrevention: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(orderParams.clone(), Value::Str("createOrder".into()), Value::Str("selfTradePrevention".into()), &[]); selfTradePrevention = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); orderParams = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (selfTradePrevention != Value::Null) {
let mut stpModes: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("EXPIRE_MAKER".to_string(), Value::Str("cancel_maker".into()));
m.insert("EXPIRE_TAKER".to_string(), Value::Str("cancel_taker".into()));
m.insert("EXPIRE_BOTH".to_string(), Value::Str("cancel_both".into()));
m
});
let mut selfTradePreventionUpper: Value = to_upper(&selfTradePrevention);
if (selfTradePreventionUpper.as_str() == Some("NONE")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() does not support NONE for selfTradePrevention, okx enforces self trade prevention at the account level and it cannot be turned off per order".into()))));
}
let mut stpMode: Value = self.safe_string(stpModes, selfTradePreventionUpper, &[to_lower(&selfTradePrevention)]);
let mut algoOrderTypes: Value = self.safe_dict_k(self.options.clone(), "algoOrderTypes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut requestOrdType: Value = self.safe_string_k(request.clone(), "ordType", &[]);
if (requestOrdType != Value::Null) && (in_op(&algoOrderTypes, &requestOrdType)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" createOrder() selfTradePrevention is not supported for algo orders, the venue silently ignores stpMode on that endpoint".into()))));
}
if (stpMode.as_str() == Some("cancel_both")) && (requestOrdType.as_str() == Some("fok")) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", self.id.clone(), Value::Str(" createOrder() EXPIRE_BOTH for selfTradePrevention is not supported for fok orders".into()))));
}
add_element_to_object(&mut request, &Value::Str("stpMode".into()), stpMode);
}
if (clientOrderId == Value::Null) {
let mut brokerId: Value = self.safe_string_k(self.options.clone(), "brokerId", &[]);
if (brokerId != Value::Null) {
add_element_to_object(&mut request, &Value::Str("clOrdId".into()), Value::Str(format!("{}{}", brokerId, self.uuid16(&[])).into()));
add_element_to_object(&mut request, &Value::Str("tag".into()), brokerId);
}
} else {
add_element_to_object(&mut request, &Value::Str("clOrdId".into()), clientOrderId);
orderParams = self.omit(orderParams.clone(), Value::from(vec![Value::Str("clOrdId".into()), Value::Str("clientOrderId".into())]), &[]);
}
return self.extend(request, &[orderParams]);
Value::Null
}
/*
* @method
* @name okx#createOrder
* @description create a trade order
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-order
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-multiple-orders
* @see https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-place-algo-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit', or 'rpi' for a retail price improvement maker order
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.reduceOnly] a mark to reduce the position size for margin, swap and future orders
* @param {bool} [params.postOnly] true to place a post only order
* @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered (perpetual swap markets only)
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {float} [params.takeProfit.price] used for take profit limit orders, not used for take profit market price orders
* @param {string} [params.takeProfit.type] 'market' or 'limit' used to specify the take profit price type
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered (perpetual swap markets only)
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {float} [params.stopLoss.price] used for stop loss limit orders, not used for stop loss market price orders
* @param {string} [params.stopLoss.type] 'market' or 'limit' used to specify the stop loss price type
* @param {string} [params.positionSide] if position mode is one-way: set to 'net', if position mode is hedge-mode: set to 'long' or 'short'
* @param {string} [params.trailingPercent] the percent to trail away from the current market price
* @param {string} [params.tpOrdKind] 'condition' or 'limit', the default is 'condition'
* @param {bool} [params.hedged] *swap and future only* true for hedged mode, false for one way mode
* @param {string} [params.marginMode] 'cross' or 'isolated', the default is 'cross'
* @param {bool} [params.rpiTakerAccess] true to let a taker order match against retail price improvement liquidity
* @param {bool} [params.rpiPxRound] *rpi orders only* true to round the price outward to the nearest placeable non-crossing level
* @param {string} [params.selfTradePrevention] set unified value for stp, EXPIRE_MAKER, EXPIRE_TAKER or EXPIRE_BOTH, other values are forwarded as-is, NONE is not supported, not supported for algo orders, and EXPIRE_BOTH is not supported for fok orders
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = self.create_order_request(symbol, type_var.clone(), side.clone(), amount, &[price, params]);
let mut method: Value = self.safe_string_k(self.options.clone(), "createOrder", &[Value::Str("privatePostTradeBatchOrders".into())]);
let mut requestOrdType: Option<String> = self.safe_string_k(request.clone(), "ordType", &[]).as_str().map(str::to_owned);
if (requestOrdType.as_deref() == Some("trigger")) || (requestOrdType.as_deref() == Some("conditional")) || (requestOrdType.as_deref() == Some("move_order_stop")) || (type_var.as_str() == Some("move_order_stop")) || (type_var.as_str() == Some("oco")) || (type_var.as_str() == Some("iceberg")) || (type_var.as_str() == Some("twap")) {
method = Value::Str("privatePostTradeOrderAlgo".into());
}
if (method.as_str() != Some("privatePostTradeOrder")) && (method.as_str() != Some("privatePostTradeOrderAlgo")) && (method.as_str() != Some("privatePostTradeBatchOrders")) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" createOrder() this.options[\"createOrder\"] must be either privatePostTradeBatchOrders or privatePostTradeOrder or privatePostTradeOrderAlgo".into()))));
}
if (method.as_str() == Some("privatePostTradeBatchOrders")) {
// keep the request body the same
// submit a single order in an array to the batch order endpoint
// because it has a lower ratelimit
request = Value::from(vec![request.clone()]);
}
let mut response: Value = Value::Null;
if (method.as_str() == Some("privatePostTradeOrder")) {
response = self.private_post_trade_order(&[request.clone()]).await;
} else if (method.as_str() == Some("privatePostTradeOrderAlgo")) {
response = self.private_post_trade_order_algo(&[request.clone()]).await;
} else {
response = self.private_post_trade_batch_orders(&[request]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = self.parse_order(first, &[market]);
add_element_to_object(&mut order, &Value::Str("type".into()), type_var);
add_element_to_object(&mut order, &Value::Str("side".into()), side);
return order;
Value::Null
}
/*
* @method
* @name okx#createOrders
* @description create a list of trade orders
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-multiple-orders
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut ordersRequests: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_989: bool = true;
while { if !__for_first_989 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_989 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut marketId: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
if (marketId == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrders() requires a symbol for each order".into()))));
}
let mut type_var: Value = self.safe_string_k(rawOrder.clone(), "type", &[Value::Str("".into())]);
let mut side: Value = self.safe_string_k(rawOrder.clone(), "side", &[]);
let mut amount: Value = self.safe_number_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_number_k(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut extendedParams: Value = self.extend(orderParams, &[params.clone()]); // the request does not accept extra params since it's a list, so we're extending each order with the common params
let mut orderRequest: Value = self.create_order_request(marketId, type_var, side, amount, &[price, extendedParams]);
append_to_array(&mut ordersRequests, orderRequest);
}
}
let mut response: Value = self.private_post_trade_batch_orders(&[ordersRequests]).await;
// {
// "code": "0",
// "data": [
// {
// "clOrdId": "e847386590ce4dBCc7f2a1b4c4509f82",
// "ordId": "636305438765568000",
// "sCode": "0",
// "sMsg": "Order placed",
// "tag": "e847386590ce4dBC"
// },
// {
// "clOrdId": "e847386590ce4dBC0b9993fe642d8f62",
// "ordId": "636305438765568001",
// "sCode": "0",
// "sMsg": "Order placed",
// "tag": "e847386590ce4dBC"
// }
// ],
// "inTime": "1697979038584486",
// "msg": "",
// "outTime": "1697979038586493"
// }
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[]);
Value::Null
}
pub fn edit_order_request(&self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut isAlgoOrder: Value = Value::Null;
if (type_var.as_str() == Some("trigger")) || (type_var.as_str() == Some("conditional")) || (type_var.as_str() == Some("move_order_stop")) || (type_var.as_str() == Some("oco")) || (type_var.as_str() == Some("iceberg")) || (type_var.as_str() == Some("twap")) {
isAlgoOrder = Value::Bool(true);
}
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clOrdId".into()), Value::Str("clientOrderId".into()), &[]);
if (clientOrderId != Value::Null) {
if isAlgoOrder.as_bool() == Some(true) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("algoClOrdId".into(), clientOrderId.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clOrdId".into(), clientOrderId); }
}
} else {
if isAlgoOrder.as_bool() == Some(true) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("algoId".into(), id.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordId".into(), id.clone()); }
}
}
let mut stopLossTriggerPrice: Value = self.safe_number2(params.clone(), Value::Str("stopLossPrice".into()), Value::Str("newSlTriggerPx".into()), &[]);
let mut stopLossPrice: Value = self.safe_number_k(params.clone(), "newSlOrdPx", &[]);
let mut stopLossTriggerPriceType: Value = self.safe_string_k(params.clone(), "newSlTriggerPxType", &[Value::Str("last".into())]);
let mut takeProfitTriggerPrice: Value = self.safe_number2(params.clone(), Value::Str("takeProfitPrice".into()), Value::Str("newTpTriggerPx".into()), &[]);
let mut takeProfitPrice: Value = self.safe_number_k(params.clone(), "newTpOrdPx", &[]);
let mut takeProfitTriggerPriceType: Value = self.safe_string_k(params.clone(), "newTpTriggerPxType", &[Value::Str("last".into())]);
let mut stopLoss: Value = self.safe_dict_k(params.clone(), "stopLoss", &[]);
let mut takeProfit: Value = self.safe_dict_k(params.clone(), "takeProfit", &[]);
let mut hasStopLoss: bool = stopLoss != Value::Null;
let mut hasTakeProfit: bool = takeProfit != Value::Null;
if isAlgoOrder.as_bool() == Some(true) {
if (stopLossTriggerPrice == Value::Null) && (takeProfitTriggerPrice == Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires a stopLossPrice or takeProfitPrice parameter for editing an algo order".into()))));
}
if (stopLossTriggerPrice != Value::Null) {
if (stopLossPrice == Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires a newSlOrdPx parameter for editing an algo order".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSlTriggerPx".into(), self.price_to_precision(symbol.clone(), stopLossTriggerPrice.clone())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSlOrdPx".into(), (if (type_var.as_str() == Some("market")) { Value::Str("-1".into()) } else { self.price_to_precision(symbol.clone(), stopLossPrice.clone()) })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSlTriggerPxType".into(), stopLossTriggerPriceType.clone()); }
}
if (takeProfitTriggerPrice != Value::Null) {
if (takeProfitPrice == Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires a newTpOrdPx parameter for editing an algo order".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpTriggerPx".into(), self.price_to_precision(symbol.clone(), takeProfitTriggerPrice.clone())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpOrdPx".into(), (if (type_var.as_str() == Some("market")) { Value::Str("-1".into()) } else { self.price_to_precision(symbol.clone(), takeProfitPrice.clone()) })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpTriggerPxType".into(), takeProfitTriggerPriceType.clone()); }
}
} else {
if (stopLossTriggerPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSlTriggerPx".into(), self.price_to_precision(symbol.clone(), stopLossTriggerPrice.clone())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSlOrdPx".into(), (if (type_var.as_str() == Some("market")) { Value::Str("-1".into()) } else { self.price_to_precision(symbol.clone(), stopLossPrice.clone()) })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSlTriggerPxType".into(), stopLossTriggerPriceType.clone()); }
}
if (takeProfitTriggerPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpTriggerPx".into(), self.price_to_precision(symbol.clone(), takeProfitTriggerPrice.clone())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpOrdPx".into(), (if (type_var.as_str() == Some("market")) { Value::Str("-1".into()) } else { self.price_to_precision(symbol.clone(), takeProfitPrice.clone()) })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpTriggerPxType".into(), takeProfitTriggerPriceType.clone()); }
}
if hasStopLoss {
stopLossTriggerPrice = self.safe_number_k(stopLoss.clone(), "triggerPrice", &[]);
stopLossPrice = self.safe_number_k(stopLoss.clone(), "price", &[]);
let mut stopLossType: Option<String> = self.safe_string_k(stopLoss, "type", &[]).as_str().map(str::to_owned);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSlTriggerPx".into(), self.price_to_precision(symbol.clone(), stopLossTriggerPrice)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSlOrdPx".into(), (if (stopLossType.as_deref() == Some("market")) { Value::Str("-1".into()) } else { self.price_to_precision(symbol.clone(), stopLossPrice) })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSlTriggerPxType".into(), stopLossTriggerPriceType); }
}
if hasTakeProfit {
takeProfitTriggerPrice = self.safe_number_k(takeProfit.clone(), "triggerPrice", &[]);
takeProfitPrice = self.safe_number_k(takeProfit.clone(), "price", &[]);
let mut takeProfitType: Value = self.safe_string_k(takeProfit, "type", &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpOrdKind".into(), (if (takeProfitType.as_str() == Some("limit")) { takeProfitType.clone() } else { Value::Str("condition".into()) })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpTriggerPx".into(), self.price_to_precision(symbol.clone(), takeProfitTriggerPrice)); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpOrdPx".into(), (if (takeProfitType.as_str() == Some("market")) { Value::Str("-1".into()) } else { self.price_to_precision(symbol.clone(), takeProfitPrice) })); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newTpTriggerPxType".into(), takeProfitTriggerPriceType); }
}
}
if (amount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newSz".into(), self.amount_to_precision(symbol.clone(), amount)); }
}
if !(isAlgoOrder.as_bool() == Some(true)) {
if (price != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("newPx".into(), self.price_to_precision(symbol, price)); }
}
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("clOrdId".into()), Value::Str("clientOrderId".into()), Value::Str("takeProfitPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("stopLoss".into()), Value::Str("takeProfit".into()), Value::Str("postOnly".into())]), &[]);
return self.extend(request, &[paramsOmitted]);
Value::Null
}
/*
* @method
* @name okx#editOrder
* @description edit a trade order
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-amend-order
* @see https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-amend-algo-order
* @param {string} id order id
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of the currency you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] client order id, uses id if not passed
* @param {float} [params.stopLossPrice] stop loss trigger price
* @param {float} [params.newSlOrdPx] the stop loss order price, set to stopLossPrice if the type is market
* @param {string} [params.newSlTriggerPxType] 'last', 'index' or 'mark' used to specify the stop loss trigger price type, default is 'last'
* @param {float} [params.takeProfitPrice] take profit trigger price
* @param {float} [params.newTpOrdPx] the take profit order price, set to takeProfitPrice if the type is market
* @param {string} [params.newTpTriggerPxType] 'last', 'index' or 'mark' used to specify the take profit trigger price type, default is 'last'
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {float} [params.stopLoss.price] used for stop loss limit orders, not used for stop loss market price orders
* @param {string} [params.stopLoss.type] 'market' or 'limit' used to specify the stop loss price type
* @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {float} [params.takeProfit.price] used for take profit limit orders, not used for take profit market price orders
* @param {string} [params.takeProfit.type] 'market' or 'limit' used to specify the take profit price type
* @param {string} [params.newTpOrdKind] 'condition' or 'limit', the default is 'condition'
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = self.edit_order_request(id, symbol, type_var.clone(), side.clone(), &[amount, price, params.clone()]);
let mut isAlgoOrder: Value = Value::Null;
if (type_var.as_str() == Some("trigger")) || (type_var.as_str() == Some("conditional")) || (type_var.as_str() == Some("move_order_stop")) || (type_var.as_str() == Some("oco")) || (type_var.as_str() == Some("iceberg")) || (type_var.as_str() == Some("twap")) {
isAlgoOrder = Value::Bool(true);
}
let mut response: Value = Value::Null;
if isAlgoOrder.as_bool() == Some(true) {
let __ws_arg_34 = self.extend(request.clone(), &[params.clone()]);
response = self.private_post_trade_amend_algos(&[__ws_arg_34]).await;
} else {
let __ws_arg_35 = self.extend(request, &[params]);
response = self.private_post_trade_amend_order(&[__ws_arg_35]).await;
}
//
// {
// "code": "0",
// "data": [
// {
// "clOrdId": "e847386590ce4dBCc1a045253497a547",
// "ordId": "559176536793178112",
// "reqId": "",
// "sCode": "0",
// "sMsg": ""
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut order: Value = self.parse_order(first, &[market]);
add_element_to_object(&mut order, &Value::Str("type".into()), type_var);
add_element_to_object(&mut order, &Value::Str("side".into()), side);
return order;
Value::Null
}
/*
* @method
* @name okx#cancelOrder
* @description cancels an open order
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-order
* @see https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.trigger] true if trigger orders
* @param {boolean} [params.trailing] set to true if you want to cancel a trailing order
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() requires a symbol argument".into()))));
}
let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut trailing: Value = self.safe_bool_k(params.clone(), "trailing", &[Value::Bool(false)]);
let mut isTrigger: bool = trigger.as_bool() == Some(true);
if isTrigger || (trailing.as_bool() == Some(true)) {
let mut orderInner: Value = self.cancel_orders(Value::from(vec![id.clone()]), &[symbol.clone(), params.clone()]).await;
let mut canceledInner: Value = self.safe_dict(orderInner, Value::Int(0), &[]);
return canceledInner;
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clOrdId".into()), Value::Str("clientOrderId".into()), &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clOrdId".into(), clientOrderId); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordId".into(), id); }
}
let mut query: Value = self.omit(params, Value::from(vec![Value::Str("clOrdId".into()), Value::Str("clientOrderId".into())]), &[]);
let __ws_arg_36 = self.extend(request, &[query]);
let mut response: Value = self.private_post_trade_cancel_order(&[__ws_arg_36]).await;
// {"code":"0","data":[{"clOrdId":"","ordId":"317251910906576896","sCode":"0","sMsg":""}],"msg":""}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut order: Value = self.safe_dict(data, Value::Int(0), &[]);
return self.parse_order(order, &[market]);
Value::Null
}
pub fn parse_ids(&self, mut ids: Value) -> Value {
/*
* @ignore
* @method
* @name okx#parseIds
* @param {string[]|string} ids order ids
* @returns {string[]} list of order ids
*/
if (ids != Value::Null) && matches!(&ids, Value::Str(_)) {
return split(&ids, &Value::Str(",".into()));
} else {
return ids;
}
Value::Null
}
/*
* @method
* @name okx#cancelOrders
* @description cancel multiple orders
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-multiple-orders
* @see https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order
* @param {string[]} ids order ids
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.trigger] whether the order is a stop/trigger order
* @param {boolean} [params.trailing] set to true if you want to cancel trailing orders
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::from(vec![]);
let mut options: Value = self.safe_dict_k(self.options.clone(), "cancelOrders", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("privatePostTradeCancelBatchOrders".into())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod]);
let mut clientOrderIds: Value = self.parse_ids(self.safe_value2(params.clone(), Value::Str("clOrdId".into()), Value::Str("clientOrderId".into()), &[]));
let mut algoIds: Value = self.parse_ids(self.safe_value_k(params.clone(), "algoId", &[]));
let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut trailing: Value = self.safe_bool_k(params.clone(), "trailing", &[Value::Bool(false)]);
let mut isTrigger: bool = trigger.as_bool() == Some(true);
if isTrigger || (trailing.as_bool() == Some(true)) {
method = Value::Str("privatePostTradeCancelAlgos".into());
}
if (clientOrderIds == Value::Null) {
let mut orderIds: Value = self.parse_ids(ids);
if (algoIds != Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_990: bool = true;
while { if !__for_first_990 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_990 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&algoIds).as_f64().unwrap_or(f64::NAN) } {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("algoId".to_string(), get_value(&algoIds, &i));
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_991: bool = true;
while { if !__for_first_991 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_991 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&orderIds).as_f64().unwrap_or(f64::NAN) } {
if (trailing.as_bool() == Some(true)) || isTrigger {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("algoId".to_string(), get_value(&orderIds, &i));
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
} else {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ordId".to_string(), get_value(&orderIds, &i));
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
}
}
}
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_992: bool = true;
while { if !__for_first_992 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_992 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&clientOrderIds).as_f64().unwrap_or(f64::NAN) } {
if (trailing.as_bool() == Some(true)) || isTrigger {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("algoClOrdId".to_string(), get_value(&clientOrderIds, &i));
m
}));
} else {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("clOrdId".to_string(), get_value(&clientOrderIds, &i));
m
}));
}
}
}
}
let mut response: Value = Value::Null;
if (method.as_str() == Some("privatePostTradeCancelAlgos")) {
response = self.private_post_trade_cancel_algos(&[request.clone()]).await; // * dont extend with params, otherwise ARRAY will be turned into OBJECT
} else {
response = self.private_post_trade_cancel_batch_orders(&[request]).await; // * dont extend with params, otherwise ARRAY will be turned into OBJECT
}
//
// {
// "code": "0",
// "data": [
// {
// "clOrdId": "e123456789ec4dBC1123456ba123b45e",
// "ordId": "405071912345641543",
// "sCode": "0",
// "sMsg": ""
// },
// ...
// ],
// "msg": ""
// }
//
// Algo order
//
// {
// "code": "0",
// "data": [
// {
// "algoId": "431375349042380800",
// "sCode": "0",
// "sMsg": ""
// }
// ],
// "msg": ""
// }
//
let mut ordersData: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
// the request-only keys must not be merged onto every parsed order: a clientOrderId[]
// request would otherwise come back as a list under the unified string field
let mut orderParams: Value = self.omit(params, Value::from(vec![Value::Str("clOrdId".into()), Value::Str("clientOrderId".into()), Value::Str("algoId".into()), Value::Str("stop".into()), Value::Str("trigger".into()), Value::Str("trailing".into()), Value::Str("method".into())]), &[]);
return self.parse_orders(ordersData, &[market, Value::Null, Value::Null, orderParams]);
Value::Null
}
/*
* @method
* @name okx#cancelOrdersForSymbols
* @description cancel multiple orders for multiple symbols
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-multiple-orders
* @see https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order
* @param {CancellationRequest[]} orders each order should contain the parameters required by cancelOrder namely id and symbol, example [{"id": "a", "symbol": "BTC/USDT"}, {"id": "b", "symbol": "ETH/USDT"}]
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.trigger] whether the order is a stop/trigger order
* @param {boolean} [params.trailing] set to true if you want to cancel trailing orders
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders_for_symbols(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::from(vec![]);
let mut options: Value = self.safe_dict_k(self.options.clone(), "cancelOrders", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("privatePostTradeCancelBatchOrders".into())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod]);
let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut trailing: Value = self.safe_bool_k(params.clone(), "trailing", &[Value::Bool(false)]);
let mut isStopOrTrailing: bool = (trigger.as_bool() == Some(true)) || (trailing.as_bool() == Some(true));
if (isStopOrTrailing) {
method = Value::Str("privatePostTradeCancelAlgos".into());
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_993: bool = true;
while { if !__for_first_993 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_993 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut order: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut id: Value = self.safe_string_k(order.clone(), "id", &[]);
let mut clientOrderId: Value = self.safe_string2(order.clone(), Value::Str("clOrdId".into()), Value::Str("clientOrderId".into()), &[]);
let mut symbol: Value = self.safe_string_k(order, "symbol", &[]);
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires a symbol for each order".into()))));
}
let mut market: Value = self.market(symbol);
let mut idKey: Value = Value::Str("ordId".into());
if (isStopOrTrailing) {
idKey = Value::Str("algoId".into());
} else if (clientOrderId != Value::Null) {
idKey = Value::Str("clOrdId".into());
}
let mut requestItem: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if let Value::Dict(__d) = &mut requestItem { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&idKey), (if (clientOrderId != Value::Null) { clientOrderId } else { id })); }
append_to_array(&mut request, requestItem);
}
}
let mut response: Value = Value::Null;
if (method.as_str() == Some("privatePostTradeCancelAlgos")) {
response = self.private_post_trade_cancel_algos(&[request.clone()]).await; // * dont extend with params, otherwise ARRAY will be turned into OBJECT
} else {
response = self.private_post_trade_cancel_batch_orders(&[request]).await; // * dont extend with params, otherwise ARRAY will be turned into OBJECT
}
//
// {
// "code": "0",
// "data": [
// {
// "clOrdId": "e123456789ec4dBC1123456ba123b45e",
// "ordId": "405071912345641543",
// "sCode": "0",
// "sMsg": ""
// },
// ...
// ],
// "msg": ""
// }
//
// Algo order
//
// {
// "code": "0",
// "data": [
// {
// "algoId": "431375349042380800",
// "sCode": "0",
// "sMsg": ""
// }
// ],
// "msg": ""
// }
//
let mut ordersData: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(ordersData, &[Value::Null, Value::Null, Value::Null, params]);
Value::Null
}
/*
* @method
* @name okx#cancelAllOrdersAfter
* @description dead man's switch, cancel all orders after the given timeout
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-cancel-all-after
* @param {number} timeout time in milliseconds, 0 represents cancel the timer
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the api result
*/
pub async fn cancel_all_orders_after(&mut self, mut timeout: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut timeOut: Value = Value::Int(0);
if (timeout != Value::Null) && (timeout.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
timeOut = self.parse_to_int((match ((timeout).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeOut".to_string(), timeOut);
m
});
let __ws_arg_37 = self.extend(request, &[params]);
let mut response: Value = self.private_post_trade_cancel_all_after(&[__ws_arg_37]).await;
return response;
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("order_failed".to_string(), Value::Str("canceled".into()));
m.insert("mmp_canceled".to_string(), Value::Str("canceled".into()));
m.insert("live".to_string(), Value::Str("open".into()));
m.insert("partially_filled".to_string(), Value::Str("open".into()));
m.insert("partially_effective".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("effective".to_string(), Value::Str("closed".into()));
m
});
if (status == Value::Null) {
return Value::Null;
}
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// createOrder
//
// {
// "clOrdId": "oktswap6",
// "ordId": "312269865356374016",
// "tag": "",
// "sCode": "0",
// "sMsg": ""
// }
//
// editOrder
//
// {
// "clOrdId": "e847386590ce4dBCc1a045253497a547",
// "ordId": "559176536793178112",
// "reqId": "",
// "sCode": "0",
// "sMsg": ""
// }
//
// Spot and Swap fetchOrder, fetchOpenOrders
//
// {
// "accFillSz": "0",
// "avgPx": "",
// "cTime": "1621910749815",
// "category": "normal",
// "ccy": "",
// "clOrdId": "",
// "fee": "0",
// "feeCcy": "ETH",
// "fillPx": "",
// "fillSz": "0",
// "fillTime": "",
// "instId": "ETH-USDT",
// "instType": "SPOT",
// "lever": "",
// "ordId": "317251910906576896",
// "ordType": "limit",
// "pnl": "0",
// "posSide": "net",
// "px": "2000",
// "rebate": "0",
// "rebateCcy": "USDT",
// "side": "buy",
// "slOrdPx": "",
// "slTriggerPx": "",
// "state": "live",
// "sz": "0.001",
// "tag": "",
// "tdMode": "cash",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tradeId": "",
// "uTime": "1621910749815"
// }
//
// watchOrders & fetchClosedOrders
//
// {
// "algoClOrdId": "",
// "algoId": "",
// "attachAlgoClOrdId": "",
// "attachAlgoOrds": [],
// "cancelSource": "",
// "cancelSourceReason": "", // not present in WS, but present in fetchClosedOrders
// "category": "normal",
// "ccy": "", // empty in WS, but eg. `USDT` in fetchClosedOrders
// "clOrdId": "",
// "cTime": "1751705801423",
// "feeCcy": "USDT",
// "instId": "LINK-USDT-SWAP",
// "instType": "SWAP",
// "isTpLimit": "false",
// "lever": "3",
// "linkedAlgoOrd": { "algoId": "" },
// "ordId": "2657625147249614848",
// "ordType": "limit",
// "posSide": "net",
// "px": "13.142",
// "pxType": "",
// "pxUsd": "",
// "pxVol": "",
// "quickMgnType": "",
// "rebate": "0",
// "rebateCcy": "USDT",
// "reduceOnly": "true",
// "side": "sell",
// "slOrdPx": "",
// "slTriggerPx": "",
// "slTriggerPxType": "",
// "source": "",
// "stpId": "",
// "stpMode": "cancel_maker",
// "sz": "0.1",
// "tag": "",
// "tdMode": "isolated",
// "tgtCcy": "",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tpTriggerPxType": "",
// "uTime": "1751705807467",
// "reqId": "", // field present only in WS
// "msg": "", // field present only in WS
// "amendResult": "", // field present only in WS
// "amendSource": "", // field present only in WS
// "code": "0", // field present only in WS
// "fillFwdPx": "", // field present only in WS
// "fillMarkVol": "", // field present only in WS
// "fillPxUsd": "", // field present only in WS
// "fillPxVol": "", // field present only in WS
// "lastPx": "13.142", // field present only in WS
// "notionalUsd": "1.314515408", // field present only in WS
//
// #### these below fields are empty on first omit from websocket, because of "creation" event. however, if order is executed, it also immediately sends another update with these fields filled ###
//
// "pnl": "-0.0001",
// "accFillSz": "0.1",
// "avgPx": "13.142",
// "state": "filled",
// "fee": "-0.00026284",
// "fillPx": "13.142",
// "tradeId": "293429690",
// "fillSz": "0.1",
// "fillTime": "1751705807467",
// "fillNotionalUsd": "1.314515408", // field present only in WS
// "fillPnl": "-0.0001", // field present only in WS
// "fillFee": "-0.00026284", // field present only in WS
// "fillFeeCcy": "USDT", // field present only in WS
// "execType": "M", // field present only in WS
// "fillMarkPx": "13.141", // field present only in WS
// "fillIdxPx": "13.147" // field present only in WS
// }
//
//
// Algo Order fetchOpenOrders, fetchCanceledOrders, fetchClosedOrders
//
// {
// "activePx": "",
// "activePxType": "",
// "actualPx": "",
// "actualSide": "buy",
// "actualSz": "0",
// "algoId": "431375349042380800",
// "cTime": "1649119897778",
// "callbackRatio": "",
// "callbackSpread": "",
// "ccy": "",
// "ctVal": "0.01",
// "instId": "BTC-USDT-SWAP",
// "instType": "SWAP",
// "last": "46538.9",
// "lever": "125",
// "moveTriggerPx": "",
// "notionalUsd": "467.059",
// "ordId": "",
// "ordPx": "50000",
// "ordType": "trigger",
// "posSide": "long",
// "pxLimit": "",
// "pxSpread": "",
// "pxVar": "",
// "side": "buy",
// "slOrdPx": "",
// "slTriggerPx": "",
// "slTriggerPxType": "",
// "state": "live",
// "sz": "1",
// "szLimit": "",
// "tag": "",
// "tdMode": "isolated",
// "tgtCcy": "",
// "timeInterval": "",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tpTriggerPxType": "",
// "triggerPx": "50000",
// "triggerPxType": "last",
// "triggerTime": "",
// "uly": "BTC-USDT"
// }
//
let mut scode: Option<String> = self.safe_string_k(order.clone(), "sCode", &[]).as_str().map(str::to_owned);
if (scode.is_some()) && (scode.as_deref() != Some("0")) {
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(order.clone(), "ordId", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(order.clone(), "clOrdId", &[]));
m.insert("status".to_string(), Value::Str("rejected".into()));
m.insert("info".to_string(), order.clone());
m
}), &[]);
}
let mut id: Value = self.safe_string2(order.clone(), Value::Str("algoId".into()), Value::Str("ordId".into()), &[]);
let mut timestamp: Value = self.safe_integer_k(order.clone(), "cTime", &[]);
let mut lastUpdateTimestamp: Value = self.safe_integer_k(order.clone(), "uTime", &[]);
let mut lastTradeTimestamp: Value = self.safe_integer_k(order.clone(), "fillTime", &[]);
let mut side: Value = self.safe_string_k(order.clone(), "side", &[]);
let mut type_var: Value = self.safe_string_k(order.clone(), "ordType", &[]);
let mut postOnly: Value = Value::Null;
let mut timeInForce: Value = Value::Null;
if (type_var.as_str() == Some("post_only")) {
postOnly = Value::Bool(true);
type_var = Value::Str("limit".into());
} else if (type_var.as_str() == Some("fok")) {
timeInForce = Value::Str("FOK".into());
type_var = Value::Str("limit".into());
} else if (type_var.as_str() == Some("ioc")) {
timeInForce = Value::Str("IOC".into());
type_var = Value::Str("limit".into());
} else if (type_var.as_str() == Some("rpi")) {
// retail price improvement orders are maker-only limit orders
postOnly = Value::Bool(true);
type_var = Value::Str("limit".into());
}
let mut marketId: Value = self.safe_string_k(order.clone(), "instId", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.clone(), market]);
let mut symbol: Value = self.safe_symbol(marketId, &[marketResolved.clone(), Value::Str("-".into())]);
let mut filled: Value = self.safe_string_k(order.clone(), "accFillSz", &[]);
let mut price: Value = self.safe_string2(order.clone(), Value::Str("px".into()), Value::Str("ordPx".into()), &[]);
let mut average: Value = self.safe_string_k(order.clone(), "avgPx", &[]);
let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "state", &[]));
let mut feeCostString: Value = self.safe_string_k(order.clone(), "fee", &[]);
let mut amount: Value = Value::Null;
let mut cost: Value = Value::Null;
// spot market buy: "sz" can refer either to base currency units or to quote currency units
// see documentation: https://www.okx.com/docs-v5/en/#rest-api-trade-place-order
let mut defaultTgtCcy: Value = self.safe_string_k(self.options.clone(), "tgtCcy", &[Value::Str("base_ccy".into())]);
let mut tgtCcy: Option<String> = self.safe_string_k(order.clone(), "tgtCcy", &[defaultTgtCcy]).as_str().map(str::to_owned);
let mut instType: Option<String> = self.safe_string_k(order.clone(), "instType", &[]).as_str().map(str::to_owned);
if (side.as_str() == Some("buy")) && (type_var.as_str() == Some("market")) && (instType.as_deref() == Some("SPOT")) && (tgtCcy.as_deref() == Some("quote_ccy")) {
// "sz" refers to the cost
cost = self.safe_string_k(order.clone(), "sz", &[]);
} else {
// "sz" refers to the trade currency amount
amount = self.safe_string_k(order.clone(), "sz", &[]);
}
let mut fee: Value = Value::Null;
if (feeCostString != Value::Null) {
let mut feeCostSigned: Value = crate::precise::Precise::stringNeg(&feeCostString);
let mut feeCurrencyId: Value = self.safe_string_k(order.clone(), "feeCcy", &[]);
let mut feeCurrencyCode: Value = self.safe_currency_code(feeCurrencyId, &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(feeCostSigned, &[]));
m.insert("currency".to_string(), feeCurrencyCode);
m
});
}
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "clOrdId", &[]);
if (clientOrderId != Value::Null) && (((clientOrderId.len() as i64) as f64) < ((1i64) as f64)) {
clientOrderId = Value::Null; // fix empty clientOrderId string
}
let mut stopLossPrice: Value = self.safe_number2(order.clone(), Value::Str("slTriggerPx".into()), Value::Str("slOrdPx".into()), &[]);
let mut takeProfitPrice: Value = self.safe_number2(order.clone(), Value::Str("tpTriggerPx".into()), Value::Str("tpOrdPx".into()), &[]);
let mut reduceOnlyRaw: Option<String> = self.safe_string_k(order.clone(), "reduceOnly", &[]).as_str().map(str::to_owned);
let mut reduceOnly: Value = Value::Bool(false);
if (reduceOnlyRaw.is_some()) {
reduceOnly = (Value::Bool(reduceOnlyRaw.as_deref() == Some("true")));
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), clientOrderId);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), lastTradeTimestamp);
m.insert("lastUpdateTimestamp".to_string(), lastUpdateTimestamp);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("timeInForce".to_string(), timeInForce);
m.insert("postOnly".to_string(), postOnly);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("triggerPrice".to_string(), self.safe_number_n(order, Value::from(vec![Value::Str("triggerPx".into()), Value::Str("moveTriggerPx".into())]), &[]));
m.insert("average".to_string(), average);
m.insert("cost".to_string(), cost);
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), fee);
m.insert("trades".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), reduceOnly);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name okx#fetchOrder
* @description fetch an order by the id
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-details
* @see https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-details
* @param {string} id the order id
* @param {string} symbol unified market symbol
* @param {object} [params] extra and exchange specific parameters
* @param {boolean} [params.trigger] true if fetching trigger orders
* @returns [an order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clOrdId".into()), Value::Str("clientOrderId".into()), &[]);
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchOrder", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("privateGetTradeOrder".into())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod]);
let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut isTrigger: bool = trigger.as_bool() == Some(true);
if isTrigger {
method = Value::Str("privateGetTradeOrderAlgo".into());
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("algoClOrdId".into(), clientOrderId.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("algoId".into(), id.clone()); }
}
} else {
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clOrdId".into(), clientOrderId); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordId".into(), id); }
}
}
let mut query: Value = self.omit(params, Value::from(vec![Value::Str("method".into()), Value::Str("clOrdId".into()), Value::Str("clientOrderId".into()), Value::Str("stop".into()), Value::Str("trigger".into())]), &[]);
let mut response: Value = Value::Null;
if (method.as_str() == Some("privateGetTradeOrderAlgo")) {
let __ws_arg_38 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_trade_order_algo(&[__ws_arg_38]).await;
} else {
let __ws_arg_39 = self.extend(request, &[query]);
response = self.private_get_trade_order(&[__ws_arg_39]).await;
}
//
// Spot and Swap
//
// {
// "code": "0",
// "data": [
// {
// "accFillSz": "0",
// "avgPx": "",
// "cTime": "1621910749815",
// "category": "normal",
// "ccy": "",
// "clOrdId": "",
// "fee": "0",
// "feeCcy": "ETH",
// "fillPx": "",
// "fillSz": "0",
// "fillTime": "",
// "instId": "ETH-USDT",
// "instType": "SPOT",
// "lever": "",
// "ordId": "317251910906576896",
// "ordType": "limit",
// "pnl": "0",
// "posSide": "net",
// "px":"20 00",
// "rebate": "0",
// "rebateCcy": "USDT",
// "side": "buy",
// "slOrdPx": "",
// "slTriggerPx": "",
// "state": "live",
// "sz":"0. 001",
// "tag": "",
// "tdMode": "cash",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tradeId": "",
// "uTime": "1621910749815"
// }
// ],
// "msg": ""
// }
//
// Algo order
// {
// "code":"0",
// "msg":"",
// "data":[
// {
// "instType":"FUTURES",
// "instId":"BTC-USD-200329",
// "ordId":"123445",
// "ccy":"BTC",
// "clOrdId":"",
// "algoId":"1234",
// "sz":"999",
// "closeFraction":"",
// "ordType":"oco",
// "side":"buy",
// "posSide":"long",
// "tdMode":"cross",
// "tgtCcy": "",
// "state":"effective",
// "lever":"20",
// "tpTriggerPx":"",
// "tpTriggerPxType":"",
// "tpOrdPx":"",
// "slTriggerPx":"",
// "slTriggerPxType":"",
// "triggerPx":"99",
// "triggerPxType":"last",
// "ordPx":"12",
// "actualSz":"",
// "actualPx":"",
// "actualSide":"",
// "pxVar":"",
// "pxSpread":"",
// "pxLimit":"",
// "szLimit":"",
// "tag": "adadadadad",
// "timeInterval":"",
// "callbackRatio":"",
// "callbackSpread":"",
// "activePx":"",
// "moveTriggerPx":"",
// "reduceOnly": "false",
// "triggerTime":"1597026383085",
// "last": "16012",
// "failCode": "",
// "algoClOrdId": "",
// "cTime":"1597026383000"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut order: Value = self.safe_dict(data, Value::Int(0), &[]);
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name okx#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-list
* @see https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-list
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.trigger] True if fetching trigger or conditional orders
* @param {string} [params.ordType] market, limit, post_only, fok, ioc and stop orders: conditional, oco, trigger, move_order_stop, iceberg, or twap
* @param {string} [params.algoId] Algo ID "'433845797218942976'"
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @param {boolean} [params.trailing] set to true if you want to fetch trailing orders
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut maxLimit: Value = Value::Int(100);
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchOpenOrders".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchOpenOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), maxLimit.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &maxLimit)); }; // default 100, max 100
}
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchOpenOrders", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut algoOrderTypes: Value = self.safe_dict_k(self.options.clone(), "algoOrderTypes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("privateGetTradeOrdersPending".into())]);
let mut method: Value = self.safe_string_k(paramsPaginate.clone(), "method", &[defaultMethod]);
let mut ordType: Value = self.safe_string_k(paramsPaginate.clone(), "ordType", &[]);
let mut trigger: Value = self.safe_bool2(paramsPaginate.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut trailing: Value = self.safe_bool_k(paramsPaginate.clone(), "trailing", &[Value::Bool(false)]);
let mut isTrigger: bool = trigger.as_bool() == Some(true);
if (trailing.as_bool() == Some(true)) || isTrigger || ((ordType != Value::Null) && (in_op(&algoOrderTypes, &ordType))) {
method = Value::Str("privateGetTradeOrdersAlgoPending".into());
}
if (trailing.as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordType".into(), Value::Str("move_order_stop".into())); }
} else if isTrigger && (ordType == Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordType".into(), Value::Str("trigger".into())); }
}
let mut query: Value = self.omit(paramsPaginate, Value::from(vec![Value::Str("method".into()), Value::Str("stop".into()), Value::Str("trigger".into()), Value::Str("trailing".into())]), &[]);
let mut response: Value = Value::Null;
if (method.as_str() == Some("privateGetTradeOrdersAlgoPending")) {
let __ws_arg_40 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_trade_orders_algo_pending(&[__ws_arg_40]).await;
} else {
let __ws_arg_41 = self.extend(request, &[query]);
response = self.private_get_trade_orders_pending(&[__ws_arg_41]).await;
}
//
// {
// "code": "0",
// "data": [
// {
// "accFillSz": "0",
// "avgPx": "",
// "cTime": "1621910749815",
// "category": "normal",
// "ccy": "",
// "clOrdId": "",
// "fee": "0",
// "feeCcy": "ETH",
// "fillPx": "",
// "fillSz": "0",
// "fillTime": "",
// "instId": "ETH-USDT",
// "instType": "SPOT",
// "lever": "",
// "ordId": "317251910906576896",
// "ordType": "limit",
// "pnl": "0",
// "posSide": "net",
// "px":"20 00",
// "rebate": "0",
// "rebateCcy": "USDT",
// "side": "buy",
// "slOrdPx": "",
// "slTriggerPx": "",
// "state": "live",
// "sz":"0. 001",
// "tag": "",
// "tdMode": "cash",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tradeId": "",
// "uTime": "1621910749815"
// }
// ],
// "msg":""
// }
//
// Algo order
//
// {
// "code": "0",
// "data": [
// {
// "activePx": "",
// "activePxType": "",
// "actualPx": "",
// "actualSide": "buy",
// "actualSz": "0",
// "algoId": "431375349042380800",
// "cTime": "1649119897778",
// "callbackRatio": "",
// "callbackSpread": "",
// "ccy": "",
// "ctVal": "0.01",
// "instId": "BTC-USDT-SWAP",
// "instType": "SWAP",
// "last": "46538.9",
// "lever": "125",
// "moveTriggerPx": "",
// "notionalUsd": "467.059",
// "ordId": "",
// "ordPx": "50000",
// "ordType": "trigger",
// "posSide": "long",
// "pxLimit": "",
// "pxSpread": "",
// "pxVar": "",
// "side": "buy",
// "slOrdPx": "",
// "slTriggerPx": "",
// "slTriggerPxType": "",
// "state": "live",
// "sz": "1",
// "szLimit": "",
// "tag": "",
// "tdMode": "isolated",
// "tgtCcy": "",
// "timeInterval": "",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tpTriggerPxType": "",
// "triggerPx": "50000",
// "triggerPxType": "last",
// "triggerTime": "",
// "uly": "BTC-USDT"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name okx#fetchCanceledOrders
* @description fetches information on multiple canceled orders made by the user
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-7-days
* @see https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-history
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] timestamp in ms of the earliest order, default is undefined
* @param {int} [limit] max number of orders to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.trigger] True if fetching trigger or conditional orders
* @param {string} [params.ordType] "conditional", "oco", "trigger", "move_order_stop", "iceberg", or "twap"
* @param {string} [params.algoId] Algo ID "'433845797218942976'"
* @param {int} [params.until] timestamp in ms to fetch orders for
* @param {boolean} [params.trailing] set to true if you want to fetch trailing orders
* @returns {object} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_canceled_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut type_var: Value = Value::Null;
let mut query: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchCanceledOrders".into()), &[market.clone(), params.clone()]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instType".into(), self.convert_to_instrument_type(type_var)); }
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100, max 100
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("state".into(), Value::Str("canceled".into())); }
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchCanceledOrders", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut algoOrderTypes: Value = self.safe_dict_k(self.options.clone(), "algoOrderTypes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("privateGetTradeOrdersHistory".into())]);
let mut method: Value = self.safe_string_k(params.clone(), "method", &[defaultMethod]);
let mut ordType: Value = self.safe_string_k(params.clone(), "ordType", &[]);
let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut trailing: Value = self.safe_bool_k(params.clone(), "trailing", &[Value::Bool(false)]);
let mut isTrigger: bool = trigger.as_bool() == Some(true);
if (trailing.as_bool() == Some(true)) {
method = Value::Str("privateGetTradeOrdersAlgoHistory".into());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordType".into(), Value::Str("move_order_stop".into())); }
} else if isTrigger || ((ordType != Value::Null) && (in_op(&algoOrderTypes, &ordType))) {
method = Value::Str("privateGetTradeOrdersAlgoHistory".into());
let mut algoId: Value = self.safe_string_k(params, "algoId", &[]);
if (algoId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("algoId".into(), algoId); }
}
if isTrigger {
if (ordType == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchCanceledOrders() requires an \"ordType\" string parameter, \"conditional\", \"oco\", \"trigger\", \"move_order_stop\", \"iceberg\", or \"twap\"".into()))));
}
}
} else {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("begin".into(), since.clone()); }
}
let mut until: Value = self.safe_integer_k(query.clone(), "until", &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), until); }
query = self.omit(query.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
}
}
let mut send: Value = self.omit(query, Value::from(vec![Value::Str("method".into()), Value::Str("stop".into()), Value::Str("trigger".into()), Value::Str("trailing".into())]), &[]);
let mut response: Value = Value::Null;
if (method.as_str() == Some("privateGetTradeOrdersAlgoHistory")) {
let __ws_arg_42 = self.extend(request.clone(), &[send.clone()]);
response = self.private_get_trade_orders_algo_history(&[__ws_arg_42]).await;
} else {
let __ws_arg_43 = self.extend(request, &[send]);
response = self.private_get_trade_orders_history(&[__ws_arg_43]).await;
}
//
// {
// "code": "0",
// "data": [
// {
// "accFillSz": "0",
// "avgPx": "",
// "cTime": "1644037822494",
// "category": "normal",
// "ccy": "",
// "clOrdId": "",
// "fee": "0",
// "feeCcy": "BTC",
// "fillPx": "",
// "fillSz": "0",
// "fillTime": "",
// "instId": "BTC-USDT",
// "instType": "SPOT",
// "lever": "",
// "ordId": "410059580352409602",
// "ordType": "limit",
// "pnl": "0",
// "posSide": "net",
// "px": "30000",
// "rebate": "0",
// "rebateCcy": "USDT",
// "side": "buy",
// "slOrdPx": "",
// "slTriggerPx": "",
// "slTriggerPxType": "",
// "source": "",
// "state": "canceled",
// "sz": "0.0005452",
// "tag": "",
// "tdMode": "cash",
// "tgtCcy": "",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tpTriggerPxType": "",
// "tradeId": "",
// "uTime": "1644038165667"
// }
// ],
// "msg": ""
// }
//
// Algo order
//
// {
// "code": "0",
// "data": [
// {
// "activePx": "",
// "activePxType": "",
// "actualPx": "",
// "actualSide": "buy",
// "actualSz": "0",
// "algoId": "433845797218942976",
// "cTime": "1649708898523",
// "callbackRatio": "",
// "callbackSpread": "",
// "ccy": "",
// "ctVal": "0.01",
// "instId": "BTC-USDT-SWAP",
// "instType": "SWAP",
// "last": "39950.4",
// "lever": "125",
// "moveTriggerPx": "",
// "notionalUsd": "1592.1760000000002",
// "ordId": "",
// "ordPx": "29000",
// "ordType": "trigger",
// "posSide": "long",
// "pxLimit": "",
// "pxSpread": "",
// "pxVar": "",
// "side": "buy",
// "slOrdPx": "",
// "slTriggerPx": "",
// "slTriggerPxType": "",
// "state": "canceled",
// "sz": "4",
// "szLimit": "",
// "tag": "",
// "tdMode": "isolated",
// "tgtCcy": "",
// "timeInterval": "",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tpTriggerPxType": "",
// "triggerPx": "30000",
// "triggerPxType": "last",
// "triggerTime": "",
// "uly": "BTC-USDT"
// },
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name okx#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-7-days
* @see https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-get-algo-order-history
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-3-months
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.trigger] True if fetching trigger or conditional orders
* @param {string} [params.ordType] "conditional", "oco", "trigger", "move_order_stop", "iceberg", or "twap"
* @param {string} [params.algoId] Algo ID "'433845797218942976'"
* @param {int} [params.until] timestamp in ms to fetch orders for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @param {string} [params.method] method to be used, either 'privateGetTradeOrdersHistory', 'privateGetTradeOrdersHistoryArchive' or 'privateGetTradeOrdersAlgoHistory' default is 'privateGetTradeOrdersHistory'
* @param {boolean} [params.trailing] set to true if you want to fetch trailing orders
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut maxLimit: Value = Value::Int(100);
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchClosedOrders".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchClosedOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), maxLimit.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut type_var: Value = Value::Null;
let mut query: Value = Value::Null;
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchClosedOrders".into()), &[market.clone(), paramsPaginate.clone()]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); query = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instType".into(), self.convert_to_instrument_type(type_var)); }
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &maxLimit)); }; // default 100, max 100
}
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchClosedOrders", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut algoOrderTypes: Value = self.safe_dict_k(self.options.clone(), "algoOrderTypes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultMethod: Value = self.safe_string_k(options, "method", &[Value::Str("privateGetTradeOrdersHistory".into())]);
let mut method: Value = self.safe_string_k(paramsPaginate.clone(), "method", &[defaultMethod]);
let mut ordType: Value = self.safe_string_k(paramsPaginate.clone(), "ordType", &[]);
let mut trigger: Value = self.safe_bool2(paramsPaginate.clone(), Value::Str("stop".into()), Value::Str("trigger".into()), &[]);
let mut trailing: Value = self.safe_bool_k(paramsPaginate, "trailing", &[Value::Bool(false)]);
if (trailing.as_bool() == Some(true)) || (trigger.as_bool() == Some(true)) || ((ordType != Value::Null) && (in_op(&algoOrderTypes, &ordType))) {
method = Value::Str("privateGetTradeOrdersAlgoHistory".into());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("state".into(), Value::Str("effective".into())); }
}
if (trailing.as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordType".into(), Value::Str("move_order_stop".into())); }
} else if (trigger.as_bool() == Some(true)) {
if (ordType == Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordType".into(), Value::Str("trigger".into())); }
}
} else {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("begin".into(), since.clone()); }
}
let mut until: Value = self.safe_integer_k(query.clone(), "until", &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), until); }
query = self.omit(query.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("state".into(), Value::Str("filled".into())); }
}
let mut send: Value = self.omit(query, Value::from(vec![Value::Str("method".into()), Value::Str("stop".into()), Value::Str("trigger".into()), Value::Str("trailing".into())]), &[]);
let mut response: Value = Value::Null;
if (method.as_str() == Some("privateGetTradeOrdersAlgoHistory")) {
let __ws_arg_44 = self.extend(request.clone(), &[send.clone()]);
response = self.private_get_trade_orders_algo_history(&[__ws_arg_44]).await;
} else if (method.as_str() == Some("privateGetTradeOrdersHistoryArchive")) {
let __ws_arg_45 = self.extend(request.clone(), &[send.clone()]);
response = self.private_get_trade_orders_history_archive(&[__ws_arg_45]).await;
} else {
let __ws_arg_46 = self.extend(request, &[send]);
response = self.private_get_trade_orders_history(&[__ws_arg_46]).await;
}
//
// {
// "code": "0",
// "data": [
// {
// "accFillSz": "0",
// "avgPx": "",
// "cTime": "1621910749815",
// "category": "normal",
// "ccy": "",
// "clOrdId": "",
// "fee": "0",
// "feeCcy": "ETH",
// "fillPx": "",
// "fillSz": "0",
// "fillTime": "",
// "instId": "ETH-USDT",
// "instType": "SPOT",
// "lever": "",
// "ordId": "317251910906576896",
// "ordType": "limit",
// "pnl": "0",
// "posSide": "net",
// "px": "2000",
// "rebate": "0",
// "rebateCcy": "USDT",
// "side": "buy",
// "slOrdPx": "",
// "slTriggerPx": "",
// "state": "live",
// "sz": "0.001",
// "tag": "",
// "tdMode": "cash",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tradeId": "",
// "uTime": "1621910749815"
// }
// ],
// "msg": ""
// }
//
// Algo order
//
// {
// "code": "0",
// "data": [
// {
// "activePx": "",
// "activePxType": "",
// "actualPx": "",
// "actualSide": "buy",
// "actualSz": "0",
// "algoId": "433845797218942976",
// "cTime": "1649708898523",
// "callbackRatio": "",
// "callbackSpread": "",
// "ccy": "",
// "ctVal": "0.01",
// "instId": "BTC-USDT-SWAP",
// "instType": "SWAP",
// "last": "39950.4",
// "lever": "125",
// "moveTriggerPx": "",
// "notionalUsd": "1592.1760000000002",
// "ordId": "",
// "ordPx": "29000",
// "ordType": "trigger",
// "posSide": "long",
// "pxLimit": "",
// "pxSpread": "",
// "pxVar": "",
// "side": "buy",
// "slOrdPx": "",
// "slTriggerPx": "",
// "slTriggerPxType": "",
// "state": "effective",
// "sz": "4",
// "szLimit": "",
// "tag": "",
// "tdMode": "isolated",
// "tgtCcy": "",
// "timeInterval": "",
// "tpOrdPx": "",
// "tpTriggerPx": "",
// "tpTriggerPxType": "",
// "triggerPx": "30000",
// "triggerPxType": "last",
// "triggerTime": "",
// "uly": "BTC-USDT"
// },
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name okx#fetchMyTrades
* @description fetch all trades made by the user
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-transaction-details-last-3-months
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] Timestamp in ms of the latest time to retrieve trades for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchMyTrades".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchMyTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("begin".into(), since.clone()); }
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("end".into()), request, paramsPaginate, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut type_varqueryVariable = self.handle_market_type_and_params(Value::Str("fetchMyTrades".into()), &[market.clone(), paramsUntil]);
let mut type_var: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
add_element_to_object(&mut requestUntil, &Value::Str("instType".into()), self.convert_to_instrument_type(type_var));
if (limit != Value::Null) && (since == Value::Null) {
add_element_to_object(&mut requestUntil, &Value::Str("limit".into()), limit.clone()); // default 100, max 100
}
let __ws_arg_47 = self.extend(requestUntil, &[query.clone()]);
let mut response: Value = self.private_get_trade_fills_history(&[__ws_arg_47]).await;
//
// {
// "code": "0",
// "data": [
// {
// "side": "buy",
// "fillSz": "0.007533",
// "fillPx": "2654.98",
// "fee": "-0.000007533",
// "ordId": "317321390244397056",
// "instType": "SPOT",
// "instId": "ETH-USDT",
// "clOrdId": "",
// "posSide": "net",
// "billId": "317321390265368576",
// "tag": "0",
// "execType": "T",
// "tradeId": "107601752",
// "feeCcy": "ETH",
// "ts": "1621927314985"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(data, &[market, since, limit, query]);
Value::Null
}
/*
* @method
* @name okx#fetchOrderTrades
* @description fetch all the trades made from a single order
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-transaction-details-last-3-months
* @param {string} id order id
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_order_trades(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ordId".to_string(), id);
m
});
let __ws_arg_48 = self.extend(request, &[params]);
return self.fetch_my_trades(&[symbol, since, limit, __ws_arg_48]).await;
Value::Null
}
/*
* @method
* @name okx#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered balance of the user
* @see https://www.okx.com/docs-v5/en/#rest-api-account-get-bills-details-last-7-days
* @see https://www.okx.com/docs-v5/en/#rest-api-account-get-bills-details-last-3-months
* @see https://www.okx.com/docs-v5/en/#rest-api-funding-asset-bills-details
* @param {string} [code] unified currency code, default is undefined
* @param {int} [since] timestamp in ms of the earliest ledger entry, default is undefined
* @param {int} [limit] max number of ledger entries to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @param {int} [params.until] the latest time in ms to fetch entries for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
*/
pub async fn fetch_ledger(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchLedger".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchLedger".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone()]).await;
}
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchLedger", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut method: Value = self.safe_string_k(options, "method", &[]);
method = self.safe_string_k(paramsPaginate.clone(), "method", &[method.clone()]);
let mut paramsOmitted: Value = self.omit(paramsPaginate, Value::Str("method".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut marginModeOptionparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("fetchLedger".into()), &[paramsOmitted]);
let mut marginModeOption: Value = marginModeOptionparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeOptionparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut marginMode: Value = (if (marginModeOption == Value::Null) { self.safe_string_k(paramsMarginMode.clone(), "mgnMode", &[]) } else { marginModeOption });
if (method.as_str() != Some("privateGetAssetBills")) {
if (marginMode != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("mgnMode".into(), marginMode); }
}
}
let mut type_varqueryVariable = self.handle_market_type_and_params(Value::Str("fetchLedger".into()), &[Value::Null, paramsMarginMode.clone()]);
let mut type_var: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (type_var != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instType".into(), self.convert_to_instrument_type(type_var)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let mut requestUntil: Value = self.handle_until_option(Value::Str("end".into()), request, paramsMarginMode, &[]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut response: Value = Value::Null;
if (method.as_str() == Some("privateGetAccountBillsArchive")) {
let __ws_arg_49 = self.extend(requestUntil.clone(), &[query.clone()]);
response = self.private_get_account_bills_archive(&[__ws_arg_49]).await;
} else if (method.as_str() == Some("privateGetAssetBills")) {
let __ws_arg_50 = self.extend(requestUntil.clone(), &[query.clone()]);
response = self.private_get_asset_bills(&[__ws_arg_50]).await;
} else {
let __ws_arg_51 = self.extend(requestUntil, &[query]);
response = self.private_get_account_bills(&[__ws_arg_51]).await;
}
//
// privateGetAccountBills, privateGetAccountBillsArchive
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "bal": "0.0000819307998198",
// "balChg": "-664.2679586599999802",
// "billId": "310394313544966151",
// "ccy": "USDT",
// "fee": "0",
// "from": "",
// "instId": "LTC-USDT",
// "instType": "SPOT",
// "mgnMode": "cross",
// "notes": "",
// "ordId": "310394313519800320",
// "pnl": "0",
// "posBal": "0",
// "posBalChg": "0",
// "subType": "2",
// "sz": "664.26795866",
// "to": "",
// "ts": "1620275771196",
// "type": "2"
// }
// ]
// }
//
// privateGetAssetBills
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "billId": "12344",
// "ccy": "BTC",
// "balChg": "2",
// "bal": "12",
// "type": "1",
// "ts": "1597026383085"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_ledger(data, &[currency, since, limit]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1".to_string(), Value::Str("transfer".into()));
m.insert("2".to_string(), Value::Str("trade".into()));
m.insert("3".to_string(), Value::Str("trade".into()));
m.insert("4".to_string(), Value::Str("rebate".into()));
m.insert("5".to_string(), Value::Str("trade".into()));
m.insert("6".to_string(), Value::Str("transfer".into()));
m.insert("7".to_string(), Value::Str("trade".into()));
m.insert("8".to_string(), Value::Str("fee".into()));
m.insert("9".to_string(), Value::Str("trade".into()));
m.insert("10".to_string(), Value::Str("trade".into()));
m.insert("11".to_string(), Value::Str("trade".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// privateGetAccountBills, privateGetAccountBillsArchive
//
// {
// "bal": "0.0000819307998198",
// "balChg": "-664.2679586599999802",
// "billId": "310394313544966151",
// "ccy": "USDT",
// "fee": "0",
// "from": "",
// "instId": "LTC-USDT",
// "instType": "SPOT",
// "mgnMode": "cross",
// "notes": "",
// "ordId": "310394313519800320",
// "pnl": "0",
// "posBal": "0",
// "posBalChg": "0",
// "subType": "2",
// "sz": "664.26795866",
// "to": "",
// "ts": "1620275771196",
// "type": "2"
// }
//
// privateGetAssetBills
//
// {
// "billId": "12344",
// "ccy": "BTC",
// "balChg": "2",
// "bal": "12",
// "type": "1",
// "ts": "1597026383085"
// }
//
let mut currencyId: Value = self.safe_string_k(item.clone(), "ccy", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
let mut currencyResolved: Value = self.safe_currency(currencyId, &[currency]);
let mut timestamp: Value = self.safe_integer_k(item.clone(), "ts", &[]);
let mut feeCostString: Value = self.safe_string_k(item.clone(), "fee", &[]);
let mut fee: Value = Value::Null;
if (feeCostString != Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(crate::precise::Precise::stringNeg(&feeCostString), &[]));
m.insert("currency".to_string(), code.clone());
m
});
}
let mut marketId: Value = self.safe_string_k(item.clone(), "instId", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[Value::Null, Value::Str("-".into())]);
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item.clone());
m.insert("id".to_string(), self.safe_string_k(item.clone(), "billId", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("account".to_string(), Value::Null);
m.insert("referenceId".to_string(), self.safe_string_k(item.clone(), "ordId", &[]));
m.insert("referenceAccount".to_string(), Value::Null);
m.insert("type".to_string(), self.parse_ledger_entry_type(self.safe_string_k(item.clone(), "type", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("currency".to_string(), code);
m.insert("symbol".to_string(), symbol);
m.insert("amount".to_string(), self.safe_number_k(item.clone(), "balChg", &[]));
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), self.safe_number_k(item, "bal", &[]));
m.insert("status".to_string(), Value::Str("ok".into()));
m.insert("fee".to_string(), fee);
m
}), &[currencyResolved]);
Value::Null
}
pub fn parse_deposit_address(&self, mut depositAddress: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "addr": "okbtothemoon",
// "memo": "971668", // may be missing
// "tag":"52055", // may be missing
// "pmtId": "", // may be missing
// "ccy": "BTC",
// "to": "6", // 1 SPOT, 3 FUTURES, 6 FUNDING, 9 SWAP, 12 OPTION, 18 Unified account
// "selected": true
// }
//
// {
// "ccy":"usdt-erc20",
// "to":"6",
// "addr":"0x696abb81974a8793352cbd33aadcf78eda3cfdfa",
// "selected":true
// }
//
// {
// "chain": "ETH-OKExChain",
// "addrEx": { "comment": "6040348" }, // some currencies like TON may have this field,
// "ctAddr": "72315c",
// "ccy": "ETH",
// "to": "6",
// "addr": "0x1c9f2244d1ccaa060bd536827c18925db10db102",
// "selected": true
// }
//
let mut address: Value = self.safe_string_k(depositAddress.clone(), "addr", &[]);
let mut tag: Value = self.safe_string_n(depositAddress.clone(), Value::from(vec![Value::Str("tag".into()), Value::Str("pmtId".into()), Value::Str("memo".into())]), &[]);
if (tag == Value::Null) {
let mut addrEx: Value = self.safe_dict_k(depositAddress.clone(), "addrEx", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
tag = self.safe_string_k(addrEx, "comment", &[]);
}
let mut currencyId: Value = self.safe_string_k(depositAddress.clone(), "ccy", &[]);
let mut currencyResolved: Value = self.safe_currency(currencyId, &[currency]);
let mut code: Value = currencyResolved.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null);
let mut chain: Value = self.safe_string_k(depositAddress.clone(), "chain", &[]);
let mut networks: Value = self.safe_dict_k(currencyResolved, "networks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut networksById: Value = self.index_by(networks, Value::Str("id".into()));
let mut networkData: Value = (if (chain == Value::Null) { Value::Null } else { self.safe_dict(networksById.clone(), chain.clone(), &[]) });
// inconsistent naming responses from exchange
// with respect to network naming provided in currency info vs address chain-names and ids
//
// response from address endpoint:
// {
// "chain": "USDT-Polygon",
// "ctAddr": "",
// "ccy": "USDT",
// "to":"6" ,
// "addr": "0x1903441e386cc49d937f6302955b5feb4286dcfa",
// "selected": true
// }
// network information from currency['networks'] field:
// Polygon: {
// info: {
// canDep: false,
// canInternal: false,
// canWd: false,
// ccy: 'USDT',
// chain: 'USDT-Polygon-Bridge',
// mainNet: false,
// maxFee: '26.879528',
// minFee: '13.439764',
// minWd: '0.001',
// name: ''
// },
// id: 'USDT-Polygon-Bridge',
// network: 'Polygon',
// active: false,
// deposit: false,
// withdraw: false,
// fee: 13.439764,
// precision: undefined,
// limits: {
// withdraw: {
// min: 0.001,
// max: undefined
// }
// }
// },
//
if (chain.as_str() == Some("USDT-Polygon")) {
networkData = self.safe_dict2(networksById, Value::Str("USDT-Polygon-Bridge".into()), Value::Str("USDT-Polygon".into()), &[]);
}
let mut network: Value = self.safe_string_k(networkData, "network", &[]);
let mut networkCode: Value = self.network_id_to_code(&[network, code.clone()]);
self.check_address(&[address.clone()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositAddress);
m.insert("currency".to_string(), code);
m.insert("network".to_string(), networkCode);
m.insert("address".to_string(), address);
m.insert("tag".to_string(), tag);
m
});
Value::Null
}
/*
* @method
* @name okx#fetchDepositAddressesByNetwork
* @description fetch a dictionary of addresses for a currency, indexed by network
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-deposit-address
* @param {string} code unified currency code of the currency for the deposit address
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [address structures]{@link https://docs.ccxt.com/?id=address-structure} indexed by the network
*/
pub async fn fetch_deposit_addresses_by_network(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ccy".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_52 = self.extend(request, &[params]);
let mut response: Value = self.private_get_asset_deposit_address(&[__ws_arg_52]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "addr": "okbtothemoon",
// "memo": "971668", // may be missing
// "tag":"52055", // may be missing
// "pmtId": "", // may be missing
// "ccy": "BTC",
// "to": "6", // 1 SPOT, 3 FUTURES, 6 FUNDING, 9 SWAP, 12 OPTION, 18 Unified account
// "selected": true
// },
// // {"ccy":"usdt-erc20","to":"6","addr":"0x696abb81974a8793352cbd33aadcf78eda3cfdfa","selected":true},
// // {"ccy":"usdt-trc20","to":"6","addr":"TRrd5SiSZrfQVRKm4e9SRSbn2LNTYqCjqx","selected":true},
// // {"ccy":"usdt_okexchain","to":"6","addr":"0x696abb81974a8793352cbd33aadcf78eda3cfdfa","selected":true},
// // {"ccy":"usdt_kip20","to":"6","addr":"0x696abb81974a8793352cbd33aadcf78eda3cfdfa","selected":true},
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut filtered: Value = self.filter_by(data, Value::Str("selected".into()), Value::Bool(true), &[]);
let mut parsed: Value = self.parse_deposit_addresses(filtered, &[Value::from(vec![currency.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null)]), Value::Bool(false)]);
return self.index_by(parsed, Value::Str("network".into()));
Value::Null
}
/*
* @method
* @name okx#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-deposit-address
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network] the network name for the deposit address
* @returns {object} an [address structure]{@link https://docs.ccxt.com/?id=address-structure}
*/
pub async fn fetch_deposit_address(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut rawNetwork: Value = self.safe_string_k(params.clone(), "network", &[]); // some networks are like "Dora Vota Mainnet"
let mut paramsOmitted: Value = self.omit(params, Value::Str("network".into()), &[]);
let mut codeValue: Value = self.safe_currency_code(code, &[]);
let mut network: Value = self.network_id_to_code(&[rawNetwork, codeValue.clone()]);
let mut responseRaw: Value = self.fetch_deposit_addresses_by_network(codeValue.clone(), &[paramsOmitted]).await;
let mut response: Value = responseRaw;
if (network != Value::Null) {
let mut result: Value = self.safe_dict(response.clone(), network.clone(), &[]);
if (result == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_address(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchDepositAddress() cannot find ".into())).into()), network).into()), Value::Str(" deposit address for ".into())).into()), codeValue)));
}
return result;
}
let mut codeNetwork: Value = self.network_id_to_code(&[codeValue.clone(), codeValue.clone()]);
if (codeNetwork != Value::Null) && (in_op(&response, &codeNetwork)) {
return response.as_map().and_then(|__m| codeNetwork.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
}
// if the network is not specified, return the first address
let mut keys: Value = object_keys(&response);
let mut first: Value = self.safe_string(keys, Value::Int(0), &[Value::Str("".into())]);
return self.safe_dict(response, first, &[]);
Value::Null
}
/*
* @method
* @name okx#withdraw
* @description make a withdrawal
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-withdrawal
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.tag] memo / destination tag, required for currencies in options['withdrawTagRequiredCurrencies']
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut tagWithdrawTagparamsWithdrawTagVariable = self.handle_param_string(params, Value::Str("tag".into()), &[]);
let mut tagWithdrawTag: Value = tagWithdrawTagparamsWithdrawTagVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWithdrawTag: Value = tagWithdrawTagparamsWithdrawTagVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
self.check_address(&[address.clone(), code.clone(), tagWithdrawTag.clone()]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut hasTag: bool = (tagWithdrawTag != Value::Null) && (((tagWithdrawTag.len() as i64) as f64) > ((0i64) as f64));
let mut addressWithTag: Value = address.clone();
if hasTag {
addressWithTag = Value::Str(format!("{}{}", Value::Str(format!("{}{}", address, Value::Str(":".into())).into()), tagWithdrawTag).into());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ccy".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("toAddr".to_string(), addressWithTag);
m.insert("dest".to_string(), Value::Str("4".into()));
m.insert("amt".to_string(), self.number_to_string(amount));
m
});
let mut network: Value = self.safe_string_k(paramsWithdrawTag.clone(), "network", &[]); // this line allows the user to specify either ERC20 or ETH
if (network != Value::Null) {
let mut networks: Value = self.safe_dict_k(self.options.clone(), "networks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
network = self.safe_string(networks, to_upper(&network), &[network.clone()]); // handle ETH>ERC20 alias
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("chain".into(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null), Value::Str("-".into())).into()), network).into())); }
}
let mut omitKeys: Value = Value::from(vec![Value::Str("fee".into())]);
if (network != Value::Null) {
append_to_array(&mut omitKeys, Value::Str("network".into()));
}
let mut fee: Value = self.safe_string_k(paramsWithdrawTag.clone(), "fee", &[]);
if (fee == Value::Null) {
let mut currencies: Value = self.fetch_currencies(&[]).await;
{ let __t = self.map_to_safe_map(self.deep_extend(self.currencies.clone(), &[currencies.clone()])); self.currencies = __t; }
let mut networkCodeResolved: Value = self.network_id_to_code(&[network, self.safe_string_k(currency.clone(), "code", &[])]);
let mut targetNetwork: Value = (if (networkCodeResolved == Value::Null) { Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) } else { self.safe_dict(currency.as_map().and_then(|__m| __m.get("networks")).cloned().unwrap_or(Value::Null), networkCodeResolved, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]) });
fee = self.safe_string_k(targetNetwork, "fee", &[]);
if (fee == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" withdraw() requires a \"fee\" string parameter, network transaction fee must be ≥ 0. Withdrawals to OKCoin or OKX are fee-free, please set \"0\". Withdrawing to external digital asset address requires network transaction fee.".into()))));
}
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("fee".into(), self.number_to_string(fee)); }; // withdrawals to OKCoin or OKX are fee-free, please set 0
let mut query: Value = self.omit(paramsWithdrawTag, omitKeys, &[]);
let __ws_arg_53 = self.extend(request, &[query]);
let mut response: Value = self.private_post_asset_withdrawal(&[__ws_arg_53]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "amt": "0.1",
// "wdId": "67485",
// "ccy": "BTC"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut transaction: Value = self.safe_dict(data, Value::Int(0), &[]);
return self.parse_transaction(transaction, &[currency]);
Value::Null
}
/*
* @method
* @name okx#fetchDeposits
* @description fetch all deposits made to an account
* @see https://www.okx.com/docs-v5/en/#rest-api-funding-get-deposit-history
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch entries for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchDeposits".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchDeposits".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), crate::runtime::Math::max(&(match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &Value::Int(0))); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100, max 100
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("after".into()), request, paramsPaginate, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_54 = self.extend(requestUntil, &[paramsUntil.clone()]);
let mut response: Value = self.private_get_asset_deposit_history(&[__ws_arg_54]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "amt": "0.01044408",
// "txId": "1915737_3_0_0_asset",
// "ccy": "BTC",
// "from": "13801825426",
// "to": "",
// "ts": "1597026383085",
// "state": "2",
// "depId": "4703879"
// },
// {
// "amt": "491.6784211",
// "txId": "1744594_3_184_0_asset",
// "ccy": "OKB",
// "from": "",
// "to": "",
// "ts": "1597026383085",
// "state": "2",
// "depId": "4703809"
// },
// {
// "amt": "223.18782496",
// "txId": "6d892c669225b1092c780bf0da0c6f912fc7dc8f6b8cc53b003288624c",
// "ccy": "USDT",
// "from": "",
// "to": "39kK4XvgEuM7rX9frgyHoZkWqx4iKu1spD",
// "ts": "1597026383085",
// "state": "2",
// "depId": "4703779"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_transactions(data, &[currency, since, limit, paramsUntil]);
Value::Null
}
/*
* @method
* @name okx#fetchDeposit
* @description fetch data on a currency deposit via the deposit id
* @see https://www.okx.com/docs-v5/en/#rest-api-funding-get-deposit-history
* @param {string} id deposit id
* @param {string} code filter by currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposit(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("depId".to_string(), id);
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_55 = self.extend(request, &[params]);
let mut response: Value = self.private_get_asset_deposit_history(&[__ws_arg_55]).await;
let mut data: Value = self.safe_list_k(response, "data", &[]);
let mut deposit: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(deposit, &[currency]);
Value::Null
}
/*
* @method
* @name okx#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://www.okx.com/docs-v5/en/#rest-api-funding-get-withdrawal-history
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch entries for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchWithdrawals".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchWithdrawals".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), crate::runtime::Math::max(&(match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &Value::Int(0))); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100, max 100
}
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("after".into()), request, paramsPaginate, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_56 = self.extend(requestUntil, &[paramsUntil.clone()]);
let mut response: Value = self.private_get_asset_withdrawal_history(&[__ws_arg_56]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "amt": "0.094",
// "wdId": "4703879",
// "fee": "0.01000000eth",
// "txId": "0x62477bac6509a04512819bb1455e923a60dea5966c7caeaa0b24eb8fb0432b85",
// "ccy": "ETH",
// "from": "13426335357",
// "to": "0xA41446125D0B5b6785f6898c9D67874D763A1519",
// "ts": "1597026383085",
// "state": "2"
// },
// {
// "amt": "0.01",
// "wdId": "4703879",
// "fee": "0.00000000btc",
// "txId": "",
// "ccy": "BTC",
// "from": "13426335357",
// "to": "13426335357",
// "ts": "1597026383085",
// "state": "2"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_transactions(data, &[currency, since, limit, paramsUntil]);
Value::Null
}
/*
* @method
* @name okx#fetchWithdrawal
* @description fetch data on a currency withdrawal via the withdrawal id
* @see https://www.okx.com/docs-v5/en/#rest-api-funding-get-withdrawal-history
* @param {string} id withdrawal id
* @param {string} code unified currency code of the currency withdrawn, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawal(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("wdId".to_string(), id);
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_57 = self.extend(request, &[params]);
let mut response: Value = self.private_get_asset_withdrawal_history(&[__ws_arg_57]).await;
//
// {
// "code": "0",
// "data": [
// {
// "chain": "USDT-TRC20",
// "clientId": '',
// "fee": "0.8",
// "ccy": "USDT",
// "amt": "54.561",
// "txId": "00cff6ec7fa7c7d7d184bd84e82b9ff36863f07c0421188607f87dfa94e06b70",
// "from": "example@email.com",
// "to": "TEY6qjnKDyyq5jDc3DJizWLCdUySrpQ4yp",
// "state": "2",
// "ts": "1641376485000",
// "wdId": "25147041"
// }
// ],
// "msg": ''
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut withdrawal: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(withdrawal, &[]);
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value) -> Value {
//
// deposit statuses
//
// {
// "0": "waiting for confirmation",
// "1": "deposit credited",
// "2": "deposit successful"
// }
//
// withdrawal statuses
//
// {
// '-3': "pending cancel",
// "-2": "canceled",
// "-1": "failed",
// "0": "pending",
// "1": "sending",
// "2": "sent",
// "3": "awaiting email verification",
// "4": "awaiting manual verification",
// "5": "awaiting identity verification"
// }
//
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("-3".to_string(), Value::Str("pending".into()));
m.insert("-2".to_string(), Value::Str("canceled".into()));
m.insert("-1".to_string(), Value::Str("failed".into()));
m.insert("0".to_string(), Value::Str("pending".into()));
m.insert("1".to_string(), Value::Str("pending".into()));
m.insert("2".to_string(), Value::Str("ok".into()));
m.insert("3".to_string(), Value::Str("pending".into()));
m.insert("4".to_string(), Value::Str("pending".into()));
m.insert("5".to_string(), Value::Str("pending".into()));
m.insert("6".to_string(), Value::Str("pending".into()));
m.insert("7".to_string(), Value::Str("pending".into()));
m.insert("8".to_string(), Value::Str("pending".into()));
m.insert("9".to_string(), Value::Str("pending".into()));
m.insert("10".to_string(), Value::Str("pending".into()));
m.insert("12".to_string(), Value::Str("pending".into()));
m.insert("15".to_string(), Value::Str("pending".into()));
m.insert("16".to_string(), Value::Str("pending".into()));
m
});
if (status == Value::Null) {
return Value::Null;
}
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// withdraw
//
// {
// "amt": "0.1",
// "wdId": "67485",
// "ccy": "BTC"
// }
//
// fetchWithdrawals
//
// {
// "amt": "0.094",
// "wdId": "4703879",
// "fee": "0.01000000eth",
// "txId": "0x62477bac6509a04512819bb1455e923a60dea5966c7caeaa0b24eb8fb0432b85",
// "ccy": "ETH",
// "from": "13426335357",
// "to": "0xA41446125D0B5b6785f6898c9D67874D763A1519",
// "tag",
// "pmtId",
// "memo",
// "ts": "1597026383085",
// "state": "2"
// }
//
// fetchDeposits
//
// {
// "amt": "0.01044408",
// "txId": "1915737_3_0_0_asset",
// "ccy": "BTC",
// "from": "13801825426",
// "to": "",
// "ts": "1597026383085",
// "state": "2",
// "depId": "4703879"
// }
//
let mut type_var: Value = Value::Null;
let mut id: Value = Value::Null;
let mut withdrawalId: Value = self.safe_string_k(transaction.clone(), "wdId", &[]);
let mut addressFrom: Value = self.safe_string_k(transaction.clone(), "from", &[]);
let mut addressTo: Value = self.safe_string_k(transaction.clone(), "to", &[]);
let mut address: Value = addressTo.clone();
let mut tagTo: Value = self.safe_string2(transaction.clone(), Value::Str("tag".into()), Value::Str("memo".into()), &[]);
if (tagTo == Value::Null) {
tagTo = self.safe_string_k(transaction.clone(), "pmtId", &[]);
} else {
tagTo = self.safe_string2(transaction.clone(), Value::Str("pmtId".into()), tagTo.clone(), &[]);
}
if (withdrawalId != Value::Null) {
type_var = Value::Str("withdrawal".into());
id = withdrawalId;
} else {
// the payment_id will appear on new deposits but appears to be removed from the response after 2 months
id = self.safe_string_k(transaction.clone(), "depId", &[]);
type_var = Value::Str("deposit".into());
}
let mut currencyId: Value = self.safe_string_k(transaction.clone(), "ccy", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut network: Value = Value::Null;
let mut chain: Value = self.safe_string_k(transaction.clone(), "chain", &[]);
if (chain != Value::Null) {
let mut chainParts: Value = split(&chain, &Value::Str("-".into()));
let mut networkParts: Value = self.array_slice(chainParts, Value::Int(1), &[]);
let mut networkId: Value = join(&networkParts, &Value::Str("-".into()));
network = self.network_id_to_code(&[networkId, code.clone()]);
}
let mut amount: Value = self.safe_number_k(transaction.clone(), "amt", &[]);
let mut status: Value = self.parse_transaction_status(self.safe_string_k(transaction.clone(), "state", &[]));
let mut txid: Value = self.safe_string_k(transaction.clone(), "txId", &[]);
let mut timestamp: Value = self.safe_integer_k(transaction.clone(), "ts", &[]);
let mut feeCost: Value = Value::Null;
if (type_var.as_str() == Some("deposit")) {
feeCost = Value::Int(0);
} else {
feeCost = self.safe_number_k(transaction.clone(), "fee", &[]);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction);
m.insert("id".to_string(), id);
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), amount);
m.insert("network".to_string(), network);
m.insert("addressFrom".to_string(), addressFrom);
m.insert("addressTo".to_string(), addressTo);
m.insert("address".to_string(), address);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("tagTo".to_string(), tagTo.clone());
m.insert("tag".to_string(), tagTo);
m.insert("status".to_string(), status);
m.insert("type".to_string(), type_var);
m.insert("updated".to_string(), Value::Null);
m.insert("txid".to_string(), txid);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("internal".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), code);
m.insert("cost".to_string(), feeCost);
m
}));
m
});
Value::Null
}
/*
* @method
* @name okx#fetchLeverage
* @description fetch the set leverage for a market
* @see https://www.okx.com/docs-v5/en/#rest-api-account-get-leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @returns {object} a [leverage structure]{@link https://docs.ccxt.com/?id=leverage-structure}
*/
pub async fn fetch_leverage(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
// cross as default marginMode
let mut defaultMarginMode: Value = self.safe_string_k(params.clone(), "mgnMode", &[Value::Str("cross".into())]);
let mut marginModeparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("fetchLeverage".into()), &[params, defaultMarginMode]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marginMode.as_str() != Some("cross")) && (marginMode.as_str() != Some("isolated")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchLeverage() requires a marginMode parameter that must be either cross or isolated".into()))));
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("mgnMode".to_string(), marginMode);
m
});
let __ws_arg_58 = self.extend(request, &[paramsMarginMode]);
let mut response: Value = self.private_get_account_leverage_info(&[__ws_arg_58]).await;
//
// {
// "code": "0",
// "data": [
// {
// "instId": "BTC-USDT-SWAP",
// "lever": "5.00000000",
// "mgnMode": "isolated",
// "posSide": "net"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_leverage(data, &[market]);
Value::Null
}
pub fn parse_leverage(&self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = Value::Null;
let mut marginMode: Value = Value::Null;
let mut longLeverage: Value = Value::Null;
let mut shortLeverage: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_994: bool = true;
while { if !__for_first_994 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_994 = false; i.as_f64().unwrap_or(f64::NAN) < ((leverage.len() as i64) as f64) } {
let mut entry: Value = self.safe_dict(leverage.clone(), i.clone(), &[]);
marginMode = self.safe_string_lower_k(entry.clone(), "mgnMode", &[]);
marketId = self.safe_string_k(entry.clone(), "instId", &[]);
let mut positionSide: Option<String> = self.safe_string_lower_k(entry.clone(), "posSide", &[]).as_str().map(str::to_owned);
if (positionSide.as_deref() == Some("long")) {
longLeverage = self.safe_integer_k(entry.clone(), "lever", &[]);
} else if (positionSide.as_deref() == Some("short")) {
shortLeverage = self.safe_integer_k(entry.clone(), "lever", &[]);
} else {
longLeverage = self.safe_integer_k(entry.clone(), "lever", &[]);
shortLeverage = self.safe_integer_k(entry, "lever", &[]);
}
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), leverage);
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("marginMode".to_string(), marginMode);
m.insert("longLeverage".to_string(), longLeverage);
m.insert("shortLeverage".to_string(), shortLeverage);
m
});
Value::Null
}
/*
* @method
* @name okx#fetchPosition
* @description fetch data on a single open contract trade position
* @see https://www.okx.com/docs-v5/en/#rest-api-account-get-positions
* @param {string} symbol unified market symbol of the market the position is held in, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.instType] MARGIN, SWAP, FUTURES, OPTION
* @returns {object} a [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut type_varqueryVariable = self.handle_market_type_and_params(Value::Str("fetchPosition".into()), &[market.clone(), params]);
let mut type_var: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (type_var != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instType".into(), self.convert_to_instrument_type(type_var)); }
}
let __ws_arg_59 = self.extend(request, &[query]);
let mut response: Value = self.private_get_account_positions(&[__ws_arg_59]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "adl": "1",
// "availPos": "1",
// "avgPx": "2566.31",
// "cTime": "1619507758793",
// "ccy": "ETH",
// "deltaBS": "",
// "deltaPA": "",
// "gammaBS": "",
// "gammaPA": "",
// "imr": "",
// "instId": "ETH-USD-210430",
// "instType": "FUTURES",
// "interest": "0",
// "last": "2566.22",
// "lever": "10",
// "liab": "",
// "liabCcy": "",
// "liqPx": "2352.8496681818233",
// "margin": "0.0003896645377994",
// "mgnMode": "isolated",
// "mgnRatio": "11.731726509588816",
// "mmr": "0.0000311811092368",
// "optVal": "",
// "pTime": "1619507761462",
// "pos": "1",
// "posCcy": "",
// "posId": "307173036051017730",
// "posSide": "long",
// "thetaBS": "",
// "thetaPA": "",
// "tradeId": "109844",
// "uTime": "1619507761462",
// "upl": "-0.0000009932766034",
// "uplRatio": "-0.0025490556801078",
// "vegaBS": "",
// "vegaPA": ""
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut position: Value = self.safe_dict(data, Value::Int(0), &[]);
if (position == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchPosition() could not find a position for ".into())).into()), symbol)));
}
return self.parse_position(position, &[market]);
Value::Null
}
/*
* @method
* @name okx#fetchPositions
* @see https://www.okx.com/docs-v5/en/#rest-api-account-get-positions
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions-history history
* @description fetch all open positions
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.instType] MARGIN, SWAP, FUTURES, OPTION
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (symbols != Value::Null) {
let mut marketIds: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_995: bool = true;
while { if !__for_first_995 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_995 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut entry: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(entry);
append_to_array(&mut marketIds, market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
}
let mut marketIdsLength: f64 = ((marketIds.len() as i64) as f64);
if marketIdsLength > ((0i64) as f64) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), join(&marketIds, &Value::Str(",".into()))); }
}
}
let mut fetchPositionsOptions: Value = self.safe_dict_k(self.options.clone(), "fetchPositions", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut method: Option<String> = self.safe_string_k(fetchPositionsOptions, "method", &[Value::Str("privateGetAccountPositions".into())]).as_str().map(str::to_owned);
let mut response: Value = Value::Null;
if (method.as_deref() == Some("privateGetAccountPositionsHistory")) {
let __ws_arg_60 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_account_positions_history(&[__ws_arg_60]).await;
} else {
let __ws_arg_61 = self.extend(request, &[params]);
response = self.private_get_account_positions(&[__ws_arg_61]).await;
}
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "adl": "1",
// "availPos": "1",
// "avgPx": "2566.31",
// "cTime": "1619507758793",
// "ccy": "ETH",
// "deltaBS": "",
// "deltaPA": "",
// "gammaBS": "",
// "gammaPA": "",
// "imr": "",
// "instId": "ETH-USD-210430",
// "instType": "FUTURES",
// "interest": "0",
// "last": "2566.22",
// "lever": "10",
// "liab": "",
// "liabCcy": "",
// "liqPx": "2352.8496681818233",
// "margin": "0.0003896645377994",
// "mgnMode": "isolated",
// "mgnRatio": "11.731726509588816",
// "mmr": "0.0000311811092368",
// "optVal": "",
// "pTime": "1619507761462",
// "pos": "1",
// "posCcy": "",
// "posId": "307173036051017730",
// "posSide": "long",
// "thetaBS": "",
// "thetaPA": "",
// "tradeId": "109844",
// "uTime": "1619507761462",
// "upl": "-0.0000009932766034",
// "uplRatio": "-0.0025490556801078",
// "vegaBS": "",
// "vegaPA": ""
// }
// ]
// }
//
let mut positions: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_996: bool = true;
while { if !__for_first_996 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_996 = false; i.as_f64().unwrap_or(f64::NAN) < ((positions.len() as i64) as f64) } {
append_to_array(&mut result, self.parse_position(positions.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[]));
}
}
return self.filter_by_array_positions(result, Value::Str("symbol".into()), &[self.market_symbols(&[symbols])]);
Value::Null
}
/*
* @method
* @name okx#fetchPositionsForSymbol
* @see https://www.okx.com/docs-v5/en/#rest-api-account-get-positions
* @description fetch all open positions for specific symbol
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.instType] MARGIN (if needed)
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions_for_symbol(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_positions(&[Value::from(vec![symbol]), params]).await;
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "adl": "3",
// "availPos": "1",
// "avgPx": "34131.1",
// "cTime": "1627227626502",
// "ccy": "USDT",
// "deltaBS": "",
// "deltaPA": "",
// "gammaBS": "",
// "gammaPA": "",
// "imr": "170.66093041794787",
// "instId": "BTC-USDT-SWAP",
// "instType": "SWAP",
// "interest": "0",
// "last": "34134.4",
// "lever": "2",
// "liab": "",
// "liabCcy": "",
// "liqPx": "12608.959083877446",
// "markPx": "4786.459271773621",
// "margin": "",
// "mgnMode": "cross",
// "mgnRatio": "140.49930117599155",
// "mmr": "1.3652874433435829",
// "notionalUsd": "341.5130010779638",
// "optVal": "",
// "pos": "1",
// "posCcy": "",
// "posId": "339552508062380036",
// "posSide": "long",
// "thetaBS": "",
// "thetaPA": "",
// "tradeId": "98617799",
// "uTime": "1627227626502",
// "upl": "0.0108608358957281",
// "uplRatio": "0.0000636418743944",
// "vegaBS": "",
// "vegaPA": ""
// }
// history
// {
// "cTime":"1708351230102",
// "ccy":"USDT",
// "closeAvgPx":"1.2567",
// "closeTotalPos":"40",
// "direction":"short",
// "fee":"-0.0351036",
// "fundingFee":"0",
// "instId":"SUSHI-USDT-SWAP",
// "instType":"SWAP",
// "lever":"10.0",
// "liqPenalty":"0",
// "mgnMode":"isolated",
// "openAvgPx":"1.2462",
// "openMaxPos":"40",
// "pnl":"-0.42",
// "pnlRatio":"-0.0912982667308618",
// "posId":"666159086676836352",
// "realizedPnl":"-0.4551036",
// "triggerPx":"",
// "type":"2",
// "uTime":"1708354805699",
// "uly":"SUSHI-USDT"
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "instId", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market, Value::Null, Value::Str("contract".into())]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut pos: Value = self.safe_string_k(position.clone(), "pos", &[]); // 'pos' field: One way mode: 0 if position is not open, 1 if open | Two way (hedge) mode: -1 if short, 1 if long, 0 if position is not open
let mut contractsAbs: Value = crate::precise::Precise::stringAbs(&pos);
let mut side: Value = self.safe_string2(position.clone(), Value::Str("posSide".into()), Value::Str("direction".into()), &[]);
let mut hedged: Value = Value::Bool(side.as_str() != Some("net"));
let mut contracts: Value = self.parse_number(contractsAbs.clone(), &[]);
if (marketResolved.as_map().and_then(|__m| __m.get("margin")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
// margin position
if (side.as_str() == Some("net")) {
let mut posCcy: Value = self.safe_string_k(position.clone(), "posCcy", &[]);
let mut parsedCurrency: Value = self.safe_currency_code(posCcy, &[]);
if (parsedCurrency != Value::Null) {
side = (if (marketResolved.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null).as_str() == parsedCurrency.as_str()) { Value::Str("long".into()) } else { Value::Str("short".into()) });
}
}
if (side == Value::Null) {
side = self.safe_string_k(position.clone(), "direction", &[]);
}
} else {
if (pos != Value::Null) {
if (side.as_str() == Some("net")) {
if is_true(&crate::precise::Precise::stringGt(&pos, &Value::Str("0".into()))) {
side = Value::Str("long".into());
} else if is_true(&crate::precise::Precise::stringLt(&pos, &Value::Str("0".into()))) {
side = Value::Str("short".into());
} else {
side = Value::Null;
}
}
}
}
let mut contractSize: Value = self.safe_number_k(marketResolved.clone(), "contractSize", &[]);
let mut contractSizeString: Value = self.number_to_string(contractSize.clone());
let mut markPriceString: Value = self.safe_string_k(position.clone(), "markPx", &[]);
let mut notionalString: Value = self.safe_string_k(position.clone(), "notionalUsd", &[]);
if (marketResolved.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
notionalString = crate::precise::Precise::stringDiv(&crate::precise::Precise::stringMul(&contractsAbs, &contractSizeString), &markPriceString);
}
let mut notional: Value = self.parse_number(notionalString.clone(), &[]);
let mut marginMode: Value = self.safe_string_k(position.clone(), "mgnMode", &[]);
let mut initialMarginString: Value = Value::Null;
let mut entryPriceString: Value = self.safe_string2(position.clone(), Value::Str("avgPx".into()), Value::Str("openAvgPx".into()), &[]);
let mut unrealizedPnlString: Value = self.safe_string_k(position.clone(), "upl", &[]);
let mut leverageString: Value = self.safe_string_k(position.clone(), "lever", &[]);
let mut initialMarginPercentage: Value = Value::Null;
let mut collateralString: Value = Value::Null;
if (marginMode.as_str() == Some("cross")) {
initialMarginString = self.safe_string_k(position.clone(), "imr", &[]);
collateralString = crate::precise::Precise::stringAdd(&initialMarginString, &unrealizedPnlString);
} else if (marginMode.as_str() == Some("isolated")) {
initialMarginPercentage = crate::precise::Precise::stringDiv(&Value::Str("1".into()), &leverageString);
collateralString = self.safe_string_k(position.clone(), "margin", &[]);
}
let mut maintenanceMarginString: Value = self.safe_string_k(position.clone(), "mmr", &[]);
let mut maintenanceMargin: Value = self.parse_number(maintenanceMarginString.clone(), &[]);
let mut maintenanceMarginPercentageString: Value = crate::precise::Precise::stringDiv(&maintenanceMarginString, ¬ionalString);
if (initialMarginPercentage == Value::Null) {
initialMarginPercentage = self.parse_number(crate::precise::Precise::stringDivPrec(&initialMarginString, ¬ionalString, &Value::Int(4)), &[]);
} else if (initialMarginString == Value::Null) {
if (marketResolved.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
let mut initialMarginPercentageString: Value = self.number_to_string(initialMarginPercentage.clone());
initialMarginString = crate::precise::Precise::stringMul(&initialMarginPercentageString, ¬ionalString);
} else {
initialMarginString = crate::precise::Precise::stringDiv(&crate::precise::Precise::stringDiv(&crate::precise::Precise::stringMul(&contractsAbs, &contractSizeString), &entryPriceString), &leverageString);
}
}
let mut rounder: Value = Value::Str("0.00005".into()); // round to closest 0.01%
let mut maintenanceMarginPercentage: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&crate::precise::Precise::stringAdd(&maintenanceMarginPercentageString, &rounder), &Value::Str("1".into()), &Value::Int(4)), &[]);
let mut liquidationPrice: Value = self.safe_number_k(position.clone(), "liqPx", &[]);
let mut percentageString: Value = self.safe_string_k(position.clone(), "uplRatio", &[]);
let mut percentage: Value = self.parse_number(crate::precise::Precise::stringMul(&percentageString, &Value::Str("100".into())), &[]);
let mut timestamp: Value = self.safe_integer_k(position.clone(), "cTime", &[]);
let mut marginRatio: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&maintenanceMarginString, &collateralString, &Value::Int(4)), &[]);
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), self.safe_string_k(position.clone(), "posId", &[]));
m.insert("symbol".to_string(), symbol);
m.insert("notional".to_string(), notional);
m.insert("marginMode".to_string(), marginMode);
m.insert("liquidationPrice".to_string(), liquidationPrice);
m.insert("entryPrice".to_string(), self.parse_number(entryPriceString, &[]));
m.insert("unrealizedPnl".to_string(), self.parse_number(unrealizedPnlString, &[]));
m.insert("realizedPnl".to_string(), self.safe_number_k(position.clone(), "realizedPnl", &[]));
m.insert("percentage".to_string(), percentage);
m.insert("contracts".to_string(), contracts);
m.insert("contractSize".to_string(), contractSize);
m.insert("markPrice".to_string(), self.parse_number(markPriceString, &[]));
m.insert("lastPrice".to_string(), self.safe_number_k(position.clone(), "closeAvgPx", &[]));
m.insert("side".to_string(), side);
m.insert("hedged".to_string(), hedged);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(position, "uTime", &[]));
m.insert("maintenanceMargin".to_string(), maintenanceMargin);
m.insert("maintenanceMarginPercentage".to_string(), maintenanceMarginPercentage);
m.insert("collateral".to_string(), self.parse_number(collateralString, &[]));
m.insert("initialMargin".to_string(), self.parse_number(initialMarginString, &[]));
m.insert("initialMarginPercentage".to_string(), self.parse_number(initialMarginPercentage, &[]));
m.insert("leverage".to_string(), self.parse_number(leverageString, &[]));
m.insert("marginRatio".to_string(), marginRatio);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name okx#transfer
* @description transfer currency internally between wallets on the same account
* @see https://www.okx.com/docs-v5/en/#rest-api-funding-funds-transfer
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount account to transfer from
* @param {string} toAccount account to transfer to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut accountsByType: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromId: Value = self.safe_string(accountsByType.clone(), fromAccount.clone(), &[fromAccount.clone()]);
let mut toId: Value = self.safe_string(accountsByType, toAccount.clone(), &[toAccount.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ccy".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("amt".to_string(), self.currency_to_precision(code, amount, &[]));
m.insert("type".to_string(), Value::Str("0".into()));
m.insert("from".to_string(), fromId.clone());
m.insert("to".to_string(), toId.clone());
m
});
if (fromId.as_str() == Some("master")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("1".into())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("subAcct".into(), toId.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("from".into(), self.safe_string_k(params.clone(), "from", &[Value::Str("6".into())])); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("to".into(), self.safe_string_k(params.clone(), "to", &[Value::Str("6".into())])); }
} else if (toId.as_str() == Some("master")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("2".into())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("subAcct".into(), fromId); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("from".into(), self.safe_string_k(params.clone(), "from", &[Value::Str("6".into())])); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("to".into(), self.safe_string_k(params.clone(), "to", &[Value::Str("6".into())])); }
}
let __ws_arg_62 = self.extend(request, &[params]);
let mut response: Value = self.private_post_asset_transfer(&[__ws_arg_62]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "transId": "754147",
// "ccy": "USDT",
// "from": "6",
// "amt": "0.1",
// "to": "18"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut rawTransfer: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transfer(rawTransfer, &[currency]);
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// transfer
//
// {
// "transId": "754147",
// "ccy": "USDT",
// "from": "6",
// "amt": "0.1",
// "to": "18"
// }
//
// fetchTransfer
//
// {
// "amt": "5",
// "ccy": "USDT",
// "from": "18",
// "instId": "",
// "state": "success",
// "subAcct": "",
// "to": "6",
// "toInstId": "",
// "transId": "464424732",
// "type": "0"
// }
//
// fetchTransfers
//
// {
// "bal": "70.6874353780312913",
// "balChg": "-4.0000000000000000", // negative means "to funding", positive meand "from funding"
// "billId": "588900695232225299",
// "ccy": "USDT",
// "execType": "",
// "fee": "",
// "from": "18",
// "instId": "",
// "instType": "",
// "mgnMode": "",
// "notes": "To Funding Account",
// "ordId": "",
// "pnl": "",
// "posBal": "",
// "posBalChg": "",
// "price": "0",
// "subType": "12",
// "sz": "-4",
// "to": "6",
// "ts": "1686676866989",
// "type": "1"
// }
//
let mut id: Value = self.safe_string2(transfer.clone(), Value::Str("transId".into()), Value::Str("billId".into()), &[]);
let mut currencyId: Value = self.safe_string_k(transfer.clone(), "ccy", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[currency]);
let mut amount: Value = self.safe_number_k(transfer.clone(), "amt", &[]);
let mut fromAccountId: Value = self.safe_string_k(transfer.clone(), "from", &[]);
let mut toAccountId: Value = self.safe_string_k(transfer.clone(), "to", &[]);
let mut accountsById: Value = self.safe_dict_k(self.options.clone(), "accountsById", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_k(transfer.clone(), "ts", &[]);
let mut balanceChange: Value = self.safe_string_k(transfer.clone(), "sz", &[]);
if (balanceChange != Value::Null) {
amount = self.parse_number(crate::precise::Precise::stringAbs(&balanceChange), &[]);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), id);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), amount);
m.insert("fromAccount".to_string(), (if (fromAccountId == Value::Null) { Value::Null } else { self.safe_string(accountsById.clone(), fromAccountId, &[]) }));
m.insert("toAccount".to_string(), (if (toAccountId == Value::Null) { Value::Null } else { self.safe_string(accountsById, toAccountId, &[]) }));
m.insert("status".to_string(), self.parse_transfer_status(self.safe_string_k(transfer, "state", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
Value::Null
}
pub fn parse_transfer_status(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("success".to_string(), Value::Str("ok".into()));
m
});
if (status == Value::Null) {
return None;
}
return self.safe_string(statuses, status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name okx#fetchTransfer
* @description fetch a transfer
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-funds-transfer-state
* @param {string} id transfer id
* @param {string} [code] unified currency code of the currency transferred
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn fetch_transfer(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("transId".to_string(), id);
m
});
let __ws_arg_63 = self.extend(request, &[params]);
let mut response: Value = self.private_get_asset_transfer_state(&[__ws_arg_63]).await;
//
// {
// "code": "0",
// "data": [
// {
// "amt": "5",
// "ccy": "USDT",
// "from": "18",
// "instId": "",
// "state": "success",
// "subAcct": "",
// "to": "6",
// "toInstId": "",
// "transId": "464424732",
// "type": "0"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut transfer: Value = self.safe_dict(data, Value::Int(0), &[]);
return self.parse_transfer(transfer, &[]);
Value::Null
}
/*
* @method
* @name okx#fetchTransfers
* @description fetch a history of internal transfers made on an account
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-3-months
* @param {string} code unified currency code of the currency transferred
* @param {int} [since] the earliest time in ms to fetch transfers for
* @param {int} [limit] the maximum number of transfers structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn fetch_transfers(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("1".into()));
m
});
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("begin".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_64 = self.extend(request, &[params.clone()]);
let mut response: Value = self.private_get_account_bills_archive(&[__ws_arg_64]).await;
//
// {
// "code": "0",
// "data": [
// {
// "bal": "70.6874353780312913",
// "balChg": "-4.0000000000000000",
// "billId": "588900695232225299",
// "ccy": "USDT",
// "execType": "",
// "fee": "",
// "from": "18",
// "instId": "",
// "instType": "",
// "mgnMode": "",
// "notes": "To Funding Account",
// "ordId": "",
// "pnl": "",
// "posBal": "",
// "posBalChg": "",
// "price": "0",
// "subType": "12",
// "sz": "-4",
// "to": "6",
// "ts": "1686676866989",
// "type": "1"
// },
// ...
// ],
// "msg": ""
// }
//
let mut transfers: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_transfers(transfers, &[currency, since, limit, params]);
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("public".into()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut isArray: bool = matches!(¶ms, Value::Arr(_));
let mut request: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("/api/".into()), self.version.clone()).into()), Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
let mut query: Value = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
let mut baseApiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("rest".into()), &[]);
if (baseApiUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
let mut url: Value = Value::Str(format!("{}{}", self.implode_hostname(baseApiUrl), request).into());
let mut privateHeaders: Value = Value::Null;
let mut hasJsonBody: bool = false;
let mut jsonBody: Value = Value::Null;
// const type = this.getPathAuthenticationType (path);
if (api.as_str() == Some("public")) {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
}
} else if (api.as_str() == Some("private")) {
self.check_required_credentials(&[]);
// inject id in implicit api call
if (method.as_str() == Some("POST")) && ((path.as_str() == Some("trade/batch-orders")) || (path.as_str() == Some("trade/order-algo")) || (path.as_str() == Some("trade/order"))) {
let mut brokerId: Value = self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("6b9ad766b55dBCDE".into())]);
if (matches!(¶ms, Value::Arr(_))) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_997: bool = true;
while { if !__for_first_997 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_997 = false; i.as_f64().unwrap_or(f64::NAN) < ((params.len() as i64) as f64) } {
let mut entry: Value = params.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut clientOrderId: Value = self.safe_string_k(entry.clone(), "clOrdId", &[]);
if (clientOrderId == Value::Null) {
add_element_to_object(&mut entry, &Value::Str("clOrdId".into()), Value::Str(format!("{}{}", brokerId, self.uuid16(&[])).into()));
add_element_to_object(&mut entry, &Value::Str("tag".into()), brokerId.clone());
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&i), entry); }
}
}
}
} else {
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clOrdId", &[]);
if (clientOrderId == Value::Null) {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("clOrdId".into(), Value::Str(format!("{}{}", brokerId, self.uuid16(&[])).into())); }
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("tag".into(), brokerId); }
}
}
}
hasJsonBody = (method.as_str() != Some("GET")) && (isArray || (((object_keys(&query).len() as i64) as f64) > ((0i64) as f64)));
jsonBody = (if hasJsonBody { json_stringify(&query) } else { Value::Null });
let mut timestamp: Value = self.iso8601(self.nonce());
privateHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("OK-ACCESS-KEY".to_string(), self.apiKey.clone());
m.insert("OK-ACCESS-PASSPHRASE".to_string(), self.password.clone());
m.insert("OK-ACCESS-TIMESTAMP".to_string(), timestamp.clone());
m
});
let mut auth: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", timestamp, method).into()), request).into());
if (method.as_str() == Some("GET")) {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
let mut urlencodedQuery: Value = Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into());
url = Value::Str(format!("{}{}", url, urlencodedQuery).into());
auth = Value::Str(format!("{}{}", auth, urlencodedQuery).into());
}
} else {
if hasJsonBody {
auth = Value::Str(format!("{}{}", auth, jsonBody).into());
}
add_element_to_object(&mut privateHeaders, &Value::Str("Content-Type".into()), Value::Str("application/json".into()));
}
let mut signature: Value = self.hmac(self.encode(auth), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[Value::Str("base64".into())]);
add_element_to_object(&mut privateHeaders, &Value::Str("OK-ACCESS-SIGN".into()), signature);
}
let mut requestBody: Value = body;
if hasJsonBody {
requestBody = jsonBody;
}
let mut requestHeaders: Value = (if (api.as_str() == Some("private")) { privateHeaders } else { headers });
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), requestBody);
m.insert("headers".to_string(), requestHeaders);
m
});
Value::Null
}
pub fn parse_funding_rate(&self, mut contract: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "fundingRate": "0.00027815",
// "fundingTime": "1634256000000",
// "instId": "BTC-USD-SWAP",
// "instType": "SWAP",
// "nextFundingRate": "0.00017",
// "nextFundingTime": "1634284800000"
// }
// ws
// {
// "fundingRate":"0.0001875391284828",
// "fundingTime":"1700726400000",
// "instId":"BTC-USD-SWAP",
// "instType":"SWAP",
// "method": "next_period",
// "maxFundingRate":"0.00375",
// "minFundingRate":"-0.00375",
// "nextFundingRate":"0.0002608059239328",
// "nextFundingTime":"1700755200000",
// "premium": "0.0001233824646391",
// "settFundingRate":"0.0001699799259033",
// "settState":"settled",
// "ts":"1700724675402"
// }
//
// in the response above nextFundingRate is actually two funding rates from now
//
let mut nextFundingRateTimestamp: Value = self.safe_integer_k(contract.clone(), "nextFundingTime", &[]);
let mut marketId: Value = self.safe_string_k(contract.clone(), "instId", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market]);
let mut nextFundingRate: Value = self.safe_number_k(contract.clone(), "nextFundingRate", &[]);
let mut fundingTime: Value = self.safe_integer_k(contract.clone(), "fundingTime", &[]);
let mut fundingTimeString: Value = self.safe_string_k(contract.clone(), "fundingTime", &[]);
let mut nextFundingTimeString: Value = self.safe_string_k(contract.clone(), "nextFundingTime", &[]);
let mut millisecondsInterval: Value = crate::precise::Precise::stringSub(&nextFundingTimeString, &fundingTimeString);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), symbol);
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
m.insert("interestRate".to_string(), self.parse_number(Value::Str("0".into()), &[]));
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("fundingRate".to_string(), self.safe_number_k(contract, "fundingRate", &[]));
m.insert("fundingTimestamp".to_string(), fundingTime.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(fundingTime));
m.insert("nextFundingRate".to_string(), nextFundingRate);
m.insert("nextFundingTimestamp".to_string(), nextFundingRateTimestamp.clone());
m.insert("nextFundingDatetime".to_string(), self.iso8601(nextFundingRateTimestamp));
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), self.parse_funding_interval(millisecondsInterval).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m
});
Value::Null
}
pub fn parse_funding_interval(&self, mut interval: Value) -> Option<String> {
let mut intervals: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("3600000".to_string(), Value::Str("1h".into()));
m.insert("7200000".to_string(), Value::Str("2h".into()));
m.insert("14400000".to_string(), Value::Str("4h".into()));
m.insert("28800000".to_string(), Value::Str("8h".into()));
m.insert("57600000".to_string(), Value::Str("16h".into()));
m.insert("86400000".to_string(), Value::Str("24h".into()));
m
});
return self.safe_string(intervals, interval.clone(), &[interval.clone()]).as_str().map(str::to_owned);
}
/*
* @method
* @name okx#fetchFundingInterval
* @description fetch the current funding rate interval
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-funding-rate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_interval(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.fetch_funding_rate(symbol, &[params]).await;
Value::Null
}
/*
* @method
* @name okx#fetchFundingRate
* @description fetch the current funding rate
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-funding-rate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marketInfo: Value = self.safe_dict_k(market.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ruleType: Option<String> = self.safe_string_k(marketInfo, "ruleType", &[]).as_str().map(str::to_owned);
let mut isExtendedPerpetual: bool = ruleType.as_deref() == Some("xperp"); // long-dated futures that still pay funding, e.g. ETH-USD_UM_XPERP-310404
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) && !isExtendedPerpetual {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRate() is only valid for swap markets or XPERP futures".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_65 = self.extend(request, &[params]);
let mut response: Value = self.public_get_public_funding_rate(&[__ws_arg_65]).await;
//
// {
// "code": "0",
// "data": [
// {
// "fundingRate": "0.00027815",
// "fundingTime": "1634256000000",
// "instId": "BTC-USD-SWAP",
// "instType": "SWAP",
// "nextFundingRate": "0.00017",
// "nextFundingTime": "1634284800000"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut entry: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_funding_rate(entry, &[market]);
Value::Null
}
/*
* @method
* @name okx#fetchFundingRates
* @description fetches the current funding rates for multiple symbols
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-funding-rate
* @param {string[]} symbols unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [funding rates structure]{@link https://docs.ccxt.com/?id=funding-rates-structure}
*/
pub async fn fetch_funding_rates(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(true)]);
if (symbolsNormalized != Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_998: bool = true;
while { if !__for_first_998 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_998 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsNormalized.len() as i64) as f64) } {
let mut market: Value = self.market(symbolsNormalized.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
let mut marketInfo: Value = self.safe_dict_k(market.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ruleType: Option<String> = self.safe_string_k(marketInfo, "ruleType", &[]).as_str().map(str::to_owned);
let mut isExtendedPerpetual: bool = ruleType.as_deref() == Some("xperp"); // long-dated futures that still pay funding, e.g. ETH-USD_UM_XPERP-310404
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) && !isExtendedPerpetual {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRates() symbols must be swap markets or XPERP futures, ".into())).into()), symbolsNormalized.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)).into()), Value::Str(" is not".into()))));
}
}
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), Value::Str("ANY".into()));
m
});
let __ws_arg_66 = self.extend(request, &[params]);
let mut response: Value = self.public_get_public_funding_rate(&[__ws_arg_66]).await;
//
// {
// "code": "0",
// "data": [
// {
// "fundingRate": "0.00027815",
// "fundingTime": "1634256000000",
// "instId": "BTC-USD-SWAP",
// "instType": "SWAP",
// "nextFundingRate": "0.00017",
// "nextFundingTime": "1634284800000"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_funding_rates(data, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name okx#fetchFundingHistory
* @description fetch the history of funding payments paid and received on this account
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-3-months
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch funding history for
* @param {int} [limit] the maximum number of funding history structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding history structure]{@link https://docs.ccxt.com/?id=funding-history-structure}
*/
pub async fn fetch_funding_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("8".into()));
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), to_string_val(&limit)); }; // default 100, max 100
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if (market.as_map().and_then(|__m| __m.get("linear")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ctType".into(), Value::Str("linear".into())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ctType".into(), Value::Str("inverse".into())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null)); }
}
}
}
let mut symbolResolved: Value = (if (market != Value::Null) { self.safe_string_k(market.clone(), "symbol", &[]) } else { symbol });
let mut type_varqueryVariable = self.handle_market_type_and_params(Value::Str("fetchFundingHistory".into()), &[market, params]);
let mut type_var: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut query: Value = type_varqueryVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (type_var.as_str() == Some("swap")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instType".into(), self.convert_to_instrument_type(type_var)); }
}
// AccountBillsArchive has the same cost as AccountBills but supports three months of data
let __ws_arg_67 = self.extend(request, &[query]);
let mut response: Value = self.private_get_account_bills_archive(&[__ws_arg_67]).await;
//
// {
// "bal": "0.0242946200998573",
// "balChg": "0.0000148752712240",
// "billId": "377970609204146187",
// "ccy": "ETH",
// "execType": "",
// "fee": "0",
// "from": "",
// "instId": "ETH-USD-SWAP",
// "instType": "SWAP",
// "mgnMode": "isolated",
// "notes": "",
// "ordId": "",
// "pnl": "0.000014875271224",
// "posBal": "0",
// "posBalChg": "0",
// "subType": "174",
// "sz": "9",
// "to": "",
// "ts": "1636387215588",
// "type": "8"
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_999: bool = true;
while { if !__for_first_999 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_999 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut entry: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_k(entry.clone(), "ts", &[]);
let mut instId: Value = self.safe_string_k(entry.clone(), "instId", &[]);
let mut marketInner: Value = self.safe_market(&[instId]);
let mut currencyId: Value = self.safe_string_k(entry.clone(), "ccy", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut balanceChange: Value = self.safe_string_k(entry.clone(), "balChg", &[]);
let mut positionBalanceChange: Value = self.safe_string_k(entry.clone(), "posBalChg", &[]);
let mut amount: Value = Value::Null;
if (balanceChange != Value::Null) && (!is_true(&crate::precise::Precise::stringEq(&balanceChange, &Value::Str("0".into())))) {
amount = balanceChange.clone();
} else {
amount = positionBalanceChange;
}
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("symbol".to_string(), marketInner.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("code".to_string(), code);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("id".to_string(), self.safe_string_k(entry, "billId", &[]));
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m
}));
}
}
let mut sorted: Value = self.sort_by(result, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[symbolResolved, since, limit]);
Value::Null
}
/*
* @method
* @name okx#setLeverage
* @description set the level of leverage for a market
* @see https://www.okx.com/docs-v5/en/#rest-api-account-set-leverage
* @param {float} leverage the rate of leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @param {string} [params.posSide] 'long' or 'short' or 'net' for isolated margin long/short mode on futures and swap markets, default is 'net'
* @returns {object} response from the exchange
*/
pub async fn set_leverage(&mut self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a symbol argument".into()))));
}
// WARNING: THIS WILL INCREASE LIQUIDATION PRICE FOR OPEN ISOLATED LONG POSITIONS
// AND DECREASE LIQUIDATION PRICE FOR OPEN ISOLATED SHORT POSITIONS
if (leverage.as_f64().unwrap_or(f64::NAN) < ((1i64) as f64)) || (leverage.as_f64().unwrap_or(f64::NAN) > ((125i64) as f64)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() leverage should be between 1 and 125".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
// cross as default marginMode
let mut defaultMarginMode: Value = self.safe_string_k(params.clone(), "mgnMode", &[Value::Str("cross".into())]);
let mut marginModeparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("setLeverage".into()), &[params, defaultMarginMode]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (marginMode.as_str() != Some("cross")) && (marginMode.as_str() != Some("isolated")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a marginMode parameter that must be either cross or isolated".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("lever".to_string(), leverage);
m.insert("mgnMode".to_string(), marginMode.clone());
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut posSide: Value = self.safe_string_k(paramsMarginMode.clone(), "posSide", &[Value::Str("net".into())]);
if (marginMode.as_str() == Some("isolated")) {
if (posSide.as_str() != Some("long")) && (posSide.as_str() != Some("short")) && (posSide.as_str() != Some("net")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires the posSide argument to be either \"long\", \"short\" or \"net\"".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("posSide".into(), posSide); }
}
let __ws_arg_68 = self.extend(request, &[paramsMarginMode]);
let mut response: Value = self.private_post_account_set_leverage(&[__ws_arg_68]).await;
return response;
Value::Null
}
/*
* @method
* @name okx#fetchPositionMode
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-account-configuration
* @description fetchs the position mode, hedged or one way, hedged for binance is set identically for all linear markets or all inverse markets
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountId] if you have multiple accounts, you must specify the account id to fetch the position mode
* @returns {object} an object detailing whether the market is in hedged or one-way mode
*/
pub async fn fetch_position_mode(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __params_empty = indexmap::IndexMap::new();
let params = params.as_map().unwrap_or(&__params_empty);
let mut accounts: Value = self.fetch_accounts(&[]).await;
let mut length: f64 = ((accounts.len() as i64) as f64);
let mut selectedAccount: Value = Value::Null;
if length > ((1i64) as f64) {
let mut accountId: Value = (match params.get("accountId") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (accountId == Value::Null) {
let mut accountIds: Value = self.get_list_from_object_values(accounts.clone(), Value::Str("id".into()));
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchPositionMode() can not detect position mode, because you have multiple accounts. Set params[\"accountId\"] to desired id from: ".into())).into()), join(&accountIds, &Value::Str(", ".into())))));
} else {
let mut accountsById: Value = self.index_by(accounts.clone(), Value::Str("id".into()));
selectedAccount = self.safe_dict(accountsById, accountId, &[]);
}
} else {
selectedAccount = accounts.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
}
let mut mainAccount: Value = selectedAccount.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null);
let mut posMode: Option<String> = self.safe_string_k(mainAccount.clone(), "posMode", &[]).as_str().map(str::to_owned); // long_short_mode, net_mode
let mut isHedged: Value = Value::Bool(posMode.as_deref() == Some("long_short_mode"));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), mainAccount);
m.insert("hedged".to_string(), isHedged);
m
});
Value::Null
}
/*
* @method
* @name okx#setPositionMode
* @description set hedged to true or false for a market
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-set-position-mode
* @param {bool} hedged set to true to use long_short_mode, false for net_mode
* @param {string} symbol not used by okx setPositionMode
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
pub async fn set_position_mode(&mut self, mut hedged: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut hedgeMode: Value = Value::Null;
if is_true(&hedged) {
hedgeMode = Value::Str("long_short_mode".into());
} else {
hedgeMode = Value::Str("net_mode".into());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("posMode".to_string(), hedgeMode);
m
});
let __ws_arg_69 = self.extend(request, &[params]);
let mut response: Value = self.private_post_account_set_position_mode(&[__ws_arg_69]).await;
return response;
Value::Null
}
/*
* @method
* @name okx#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-set-leverage
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.leverage] leverage
* @returns {object} response from the exchange
*/
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a symbol argument".into()))));
}
// WARNING: THIS WILL INCREASE LIQUIDATION PRICE FOR OPEN ISOLATED LONG POSITIONS
// AND DECREASE LIQUIDATION PRICE FOR OPEN ISOLATED SHORT POSITIONS
let mut marginModeValue: Value = to_lower(&marginMode);
if (marginModeValue.as_str() != Some("cross")) && (marginModeValue.as_str() != Some("isolated")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() marginMode must be either cross or isolated".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut lever: Value = self.safe_integer2(params.clone(), Value::Str("lever".into()), Value::Str("leverage".into()), &[]);
if (lever == Value::Null) || (lever.as_f64().unwrap_or(f64::NAN) < ((1i64) as f64)) || (lever.as_f64().unwrap_or(f64::NAN) > ((125i64) as f64)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() params[\"lever\"] should be between 1 and 125".into()))));
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("leverage".into())]), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("lever".to_string(), lever);
m.insert("mgnMode".to_string(), marginModeValue);
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_70 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_account_set_leverage(&[__ws_arg_70]).await;
return response;
Value::Null
}
/*
* @method
* @name okx#fetchCrossBorrowRates
* @description fetch the borrow interest rates of all currencies
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-interest-rate
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [borrow rate structures]{@link https://docs.ccxt.com/?id=borrow-rate-structure}
*/
pub async fn fetch_cross_borrow_rates(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.private_get_account_interest_rate(&[params]).await;
//
// {
// "code": "0",
// "data": [
// {
// "ccy": "BTC",
// "interestRate": "0.00000833"
// }
// ...
// ],
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
// code-keyed dict (CrossBorrowRates); base fetchCrossBorrowRate looks up by code
let mut rates: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1000: bool = true;
while { if !__for_first_1000 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1000 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut rate: Value = self.parse_borrow_rate(data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), &[]);
let mut code: Value = self.safe_string_k(rate.clone(), "currency", &[]);
if (code != Value::Null) {
if let Value::Dict(__d) = &mut rates { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), rate); }
}
}
}
return rates;
Value::Null
}
/*
* @method
* @name okx#fetchCrossBorrowRate
* @description fetch the rate of interest to borrow a currency for margin trading
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-interest-rate
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [borrow rate structure]{@link https://docs.ccxt.com/?id=borrow-rate-structure}
*/
pub async fn fetch_cross_borrow_rate(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ccy".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_71 = self.extend(request, &[params]);
let mut response: Value = self.private_get_account_interest_rate(&[__ws_arg_71]).await;
//
// {
// "code": "0",
// "data": [
// {
// "ccy": "USDT",
// "interestRate": "0.00002065"
// }
// ...
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut rate: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_borrow_rate(rate, &[]);
Value::Null
}
pub fn parse_borrow_rate(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "amt": "992.10341195",
// "ccy": "BTC",
// "rate": "0.01",
// "ts": "1643954400000"
// }
//
let mut ccy: Value = self.safe_string_k(info.clone(), "ccy", &[]);
let mut timestamp: Value = self.safe_integer_k(info.clone(), "ts", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), self.safe_currency_code(ccy, &[]));
m.insert("rate".to_string(), self.safe_number2(info.clone(), Value::Str("interestRate".into()), Value::Str("rate".into()), &[]));
m.insert("period".to_string(), Value::Int(3600000));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("info".to_string(), info);
m
});
Value::Null
}
pub fn parse_borrow_rate_histories(&self, mut response: Value, mut codes: Value, mut since: Value, mut limit: Value) -> Value {
//
// [
// {
// "amt": "992.10341195",
// "ccy": "BTC",
// "rate": "0.01",
// "ts": "1643954400000"
// },
// ...
// ]
//
let mut borrowRateHistories: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_1001: bool = true;
while { if !__for_first_1001 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1001 = false; i.as_f64().unwrap_or(f64::NAN) < ((response.len() as i64) as f64) } {
let mut item: Value = self.safe_dict(response.clone(), i.clone(), &[]);
let mut code: Value = self.safe_currency_code(self.safe_string_k(item.clone(), "ccy", &[]), &[]);
if (code != Value::Null) && ((codes == Value::Null) || self.in_array(code.clone(), codes.clone()).as_bool() == Some(true)) {
if !(in_op(&borrowRateHistories, &code)) {
if let Value::Dict(__d) = &mut borrowRateHistories { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), Value::from(vec![])); }
}
let mut borrowRateStructure: Value = self.parse_borrow_rate(item, &[]);
// GET /api/v5/finance/savings/lending-rate-history returns annualized rates, unlike the hourly cross-margin endpoint
add_element_to_object(&mut borrowRateStructure, &Value::Str("period".into()), Value::Int(31536000000));
let mut borrrowRateCode: Value = get_value(&borrowRateHistories, &code);
append_to_array(&mut borrrowRateCode, borrowRateStructure);
crate::set_value(&mut borrowRateHistories, &code, borrrowRateCode);
}
}
}
let mut keys: Value = object_keys(&borrowRateHistories);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1002: bool = true;
while { if !__for_first_1002 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1002 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut code: Value = keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
{ let __be_tmp = self.filter_by_currency_since_limit(get_value(&borrowRateHistories, &code), &[code.clone(), since.clone(), limit.clone()]); if let Value::Dict(__d) = &mut borrowRateHistories { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), __be_tmp); } }
}
}
return borrowRateHistories;
Value::Null
}
/*
* @method
* @name okx#fetchBorrowRateHistories
* @description retrieves a history of a multiple currencies borrow interest rate at specific time slots, returns all currencies if no symbols passed, default is undefined
* @see https://www.okx.com/docs-v5/en/#financial-product-savings-get-public-borrow-history-public
* @param {string[]|undefined} codes list of unified currency codes, default is undefined
* @param {int} [since] timestamp in ms of the earliest borrowRate, default is undefined
* @param {int} [limit] max number of borrow rate prices to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [borrow rate structures]{@link https://docs.ccxt.com/?id=borrow-rate-structure} indexed by the market symbol
*/
pub async fn fetch_borrow_rate_histories(&mut self, optional_args: &[Value]) -> Value {
let mut codes = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_72 = self.extend(request, &[params]);
let mut response: Value = self.public_get_finance_savings_lending_rate_history(&[__ws_arg_72]).await;
//
// {
// "code": "0",
// "data": [
// {
// "amt": "992.10341195",
// "ccy": "BTC",
// "rate": "0.01",
// "ts": "1643954400000"
// },
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_borrow_rate_histories(data, codes, since, limit);
Value::Null
}
/*
* @method
* @name okx#fetchBorrowRateHistory
* @description retrieves a history of a currencies borrow interest rate at specific time slots
* @see https://www.okx.com/docs-v5/en/#financial-product-savings-get-public-borrow-history-public
* @param {string} code unified currency code
* @param {int} [since] timestamp for the earliest borrow rate
* @param {int} [limit] the maximum number of [borrow rate structures]{@link https://docs.ccxt.com/?id=borrow-rate-structure} to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of [borrow rate structures]{@link https://docs.ccxt.com/?id=borrow-rate-structure}
*/
pub async fn fetch_borrow_rate_history(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ccy".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_73 = self.extend(request, &[params]);
let mut response: Value = self.public_get_finance_savings_lending_rate_history(&[__ws_arg_73]).await;
//
// {
// "code": "0",
// "data": [
// {
// "amt": "992.10341195",
// "ccy": "BTC",
// "rate": "0.01",
// "ts": "1643954400000"
// },
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_borrow_rate_history(data, code, since, limit);
Value::Null
}
pub async fn modify_margin_helper(&mut self, mut symbol: Value, mut amount: Value, mut type_var: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut posSide: Value = self.safe_string_k(params.clone(), "posSide", &[Value::Str("net".into())]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("posSide".into())]), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("amt".to_string(), amount);
m.insert("type".to_string(), type_var);
m.insert("posSide".to_string(), posSide);
m
});
let __ws_arg_74 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_account_position_margin_balance(&[__ws_arg_74]).await;
//
// {
// "code": "0",
// "data": [
// {
// "amt": "0.01",
// "instId": "ETH-USD-SWAP",
// "posSide": "net",
// "type": "reduce"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
let mut entry: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut errorCode: Option<String> = self.safe_string_k(response, "code", &[]).as_str().map(str::to_owned);
let __ws_arg_75 = self.parse_margin_modification(entry, &[market]);
return self.extend(__ws_arg_75, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if (errorCode.as_deref() == Some("0")) { Value::Str("ok".into()) } else { Value::Str("failed".into()) }));
m
})]);
Value::Null
}
pub fn parse_margin_modification(&self, mut data: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// addMargin/reduceMargin
//
// {
// "amt": "0.01",
// "instId": "ETH-USD-SWAP",
// "posSide": "net",
// "type": "reduce"
// }
//
// fetchMarginAdjustmentHistory
//
// {
// bal: '67621.4325135010619812',
// balChg: '-10.0000000000000000',
// billId: '691293628710342659',
// ccy: 'USDT',
// clOrdId: '',
// execType: '',
// fee: '0',
// fillFwdPx: '',
// fillIdxPx: '',
// fillMarkPx: '',
// fillMarkVol: '',
// fillPxUsd: '',
// fillPxVol: '',
// fillTime: '1711089244850',
// from: '',
// instId: 'XRP-USDT-SWAP',
// instType: 'SWAP',
// interest: '0',
// mgnMode: 'isolated',
// notes: '',
// ordId: '',
// pnl: '0',
// posBal: '73.12',
// posBalChg: '10.00',
// px: '',
// subType: '160',
// sz: '10',
// tag: '',
// to: '',
// tradeId: '0',
// ts: '1711089244699',
// type: '6'
// }
//
let mut amountRaw: Value = self.safe_string2(data.clone(), Value::Str("amt".into()), Value::Str("posBalChg".into()), &[]);
let mut typeRaw: Value = self.safe_string_k(data.clone(), "type", &[]);
// ledger uses numeric '6' (+/- amount); addMargin/reduceMargin already send 'add'/'reduce'
let mut type_var: Value = Value::Null;
if (typeRaw.as_str() == Some("6")) {
type_var = (if is_true(&crate::precise::Precise::stringGt(&amountRaw, &Value::Str("0".into()))) { Value::Str("add".into()) } else { Value::Str("reduce".into()) });
} else {
type_var = typeRaw;
}
let mut amount: Value = crate::precise::Precise::stringAbs(&amountRaw);
let mut marketId: Value = self.safe_string_k(data.clone(), "instId", &[]);
let mut responseMarket: Value = self.safe_market(&[marketId, market]);
let mut code: Value = (if (responseMarket.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { responseMarket.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null) } else { responseMarket.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null) });
let mut timestamp: Value = self.safe_integer_k(data.clone(), "ts", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data);
m.insert("symbol".to_string(), responseMarket.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), type_var);
m.insert("marginMode".to_string(), Value::Str("isolated".into()));
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("code".to_string(), code);
m.insert("total".to_string(), Value::Null);
m.insert("status".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
});
Value::Null
}
/*
* @method
* @name okx#reduceMargin
* @description remove margin from a position
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-increase-decrease-margin
* @param {string} symbol unified market symbol
* @param {float} amount the amount of margin to remove
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn reduce_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Str("reduce".into()), &[params]).await;
Value::Null
}
/*
* @method
* @name okx#addMargin
* @description add margin
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-increase-decrease-margin
* @param {string} symbol unified market symbol
* @param {float} amount amount of margin to add
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin structure]{@link https://docs.ccxt.com/?id=margin-structure}
*/
pub async fn add_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Str("add".into()), &[params]).await;
Value::Null
}
/*
* @method
* @name okx#fetchMarketLeverageTiers
* @description retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market
* @see https://www.okx.com/docs-v5/en/#rest-api-public-data-get-position-tiers
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @returns {object} a [leverage tiers structure]{@link https://docs.ccxt.com/?id=leverage-tiers-structure}
*/
pub async fn fetch_market_leverage_tiers(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut type_var: Value = (if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) { Value::Str("MARGIN".into()) } else { self.convert_to_instrument_type(market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null)) });
let mut uly: Value = self.safe_string(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("uly".into()), &[]);
if (uly == Value::Null) || (uly.as_str() == Some("")) {
if (type_var.as_str() != Some("MARGIN")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchMarketLeverageTiers() cannot fetch leverage tiers for ".into())).into()), symbol)));
}
}
// cross as default marginMode
let mut defaultMarginMode: Value = self.safe_string_k(params.clone(), "tdMode", &[Value::Str("cross".into())]);
let mut marginModeparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("fetchMarketLeverageTiers".into()), &[params, defaultMarginMode]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instType".to_string(), type_var.clone());
m.insert("tdMode".to_string(), marginMode);
m.insert("uly".to_string(), uly);
m
});
if (type_var.as_str() == Some("MARGIN")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_76 = self.extend(request, &[paramsMarginMode]);
let mut response: Value = self.public_get_public_position_tiers(&[__ws_arg_76]).await;
//
// {
// "code": "0",
// "data": [
// {
// "baseMaxLoan": "500",
// "imr": "0.1",
// "instId": "ETH-USDT",
// "maxLever": "10",
// "maxSz": "500",
// "minSz": "0",
// "mmr": "0.03",
// "optMgnFactor": "0",
// "quoteMaxLoan": "200000",
// "tier": "1",
// "uly": ""
// },
// ...
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_market_leverage_tiers(data, &[market]);
Value::Null
}
pub fn parse_market_leverage_tiers(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
/*
* @ignore
* @method
* @param {object} info Exchange response for 1 market
* @param {object} market CCXT market
*/
//
// [
// {
// "baseMaxLoan": "500",
// "imr": "0.1",
// "instId": "ETH-USDT",
// "maxLever": "10",
// "maxSz": "500",
// "minSz": "0",
// "mmr": "0.03",
// "optMgnFactor": "0",
// "quoteMaxLoan": "200000",
// "tier": "1",
// "uly": ""
// },
// ...
// ]
//
let mut tiers: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1003: bool = true;
while { if !__for_first_1003 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1003 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&info).as_f64().unwrap_or(f64::NAN) } {
let mut tier: Value = self.safe_dict(info.clone(), i.clone(), &[]);
let mut marketId: Value = self.safe_string_k(tier.clone(), "instId", &[]);
append_to_array(&mut tiers, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tier".to_string(), self.safe_integer_k(tier.clone(), "tier", &[]));
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market.clone()]));
m.insert("currency".to_string(), self.safe_string_k(market.clone(), "quote", &[]));
m.insert("minNotional".to_string(), self.safe_number_k(tier.clone(), "minSz", &[]));
m.insert("maxNotional".to_string(), self.safe_number_k(tier.clone(), "maxSz", &[]));
m.insert("maintenanceMarginRate".to_string(), self.safe_number_k(tier.clone(), "mmr", &[]));
m.insert("maxLeverage".to_string(), self.safe_number_k(tier.clone(), "maxLever", &[]));
m.insert("info".to_string(), tier);
m
}));
}
}
return tiers;
Value::Null
}
/*
* @method
* @name okx#fetchBorrowInterest
* @description fetch the interest owed b the user for borrowing currency for margin trading
* @see https://www.okx.com/docs-v5/en/#rest-api-account-get-interest-accrued-data
* @param {string} code the unified currency code for the currency of the interest
* @param {string} symbol the market symbol of an isolated margin market, if undefined, the interest for cross margin markets is returned
* @param {int} [since] timestamp in ms of the earliest time to receive interest records for
* @param {int} [limit] the number of [borrow interest structures]{@link https://docs.ccxt.com/?id=borrow-interest-structure} to retrieve
* @param {object} [params] exchange specific parameters
* @param {int} [params.type] Loan type 1 - VIP loans 2 - Market loans *Default is Market loans*
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @returns {object[]} An list of [borrow interest structures]{@link https://docs.ccxt.com/?id=borrow-interest-structure}
*/
pub async fn fetch_borrow_interest(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut symbol = get_arg(optional_args, 1, Value::Null);
let mut since = get_arg(optional_args, 2, Value::Null);
let mut limit = get_arg(optional_args, 3, Value::Null);
let mut params = get_arg(optional_args, 4, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
// cross as default marginMode
let mut defaultMarginMode: Value = self.safe_string_k(params.clone(), "mgnMode", &[Value::Str("cross".into())]);
let mut marginModeparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("fetchBorrowInterest".into()), &[params, defaultMarginMode]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mgnMode".to_string(), marginMode);
m
});
let mut market: Value = Value::Null;
if (code != Value::Null) {
let mut currency: Value = self.currency(code.clone());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), (match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_77 = self.extend(request, &[paramsMarginMode]);
let mut response: Value = self.private_get_account_interest_accrued(&[__ws_arg_77]).await;
//
// {
// "code": "0",
// "data": [
// {
// "ccy": "USDT",
// "instId": "",
// "interest": "0.0003960833333334",
// "interestRate": "0.0000040833333333",
// "liab": "97",
// "mgnMode": "",
// "ts": "1637312400000",
// "type": "1"
// },
// ...
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut interest: Value = self.parse_borrow_interests(data, &[]);
return self.filter_by_currency_since_limit(interest, &[code, since, limit]);
Value::Null
}
pub fn parse_borrow_interest(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut instId: Value = self.safe_string_k(info.clone(), "instId", &[]);
let mut marketResolved: Value = (if (instId != Value::Null) { self.safe_market(&[instId, market.clone()]) } else { market });
let mut timestamp: Value = self.safe_integer_k(info.clone(), "ts", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info.clone());
m.insert("symbol".to_string(), self.safe_string_k(marketResolved, "symbol", &[]));
m.insert("currency".to_string(), self.safe_currency_code(self.safe_string_k(info.clone(), "ccy", &[]), &[]));
m.insert("interest".to_string(), self.safe_number_k(info.clone(), "interest", &[]));
m.insert("interestRate".to_string(), self.safe_number_k(info.clone(), "interestRate", &[]));
m.insert("amountBorrowed".to_string(), self.safe_number_k(info.clone(), "liab", &[]));
m.insert("marginMode".to_string(), self.safe_string_k(info, "mgnMode", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
});
Value::Null
}
/*
* @method
* @name okx#borrowCrossMargin
* @description create a loan to borrow margin (need to be VIP 5 and above)
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-vip-loans-borrow-and-repay
* @param {string} code unified currency code of the currency to borrow
* @param {float} amount the amount to borrow
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/?id=margin-loan-structure}
*/
pub async fn borrow_cross_margin(&mut self, mut code: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ccy".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("amt".to_string(), self.currency_to_precision(code, amount, &[]));
m.insert("side".to_string(), Value::Str("borrow".into()));
m
});
let __ws_arg_78 = self.extend(request, &[params]);
let mut response: Value = self.private_post_account_borrow_repay(&[__ws_arg_78]).await;
//
// {
// "code": "0",
// "data": [
// {
// "amt": "102",
// "ccy": "USDT",
// "ordId": "544199684697214976",
// "side": "borrow",
// "state": "1"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut loan: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_loan(loan, &[currency]);
Value::Null
}
/*
* @method
* @name okx#repayCrossMargin
* @description repay borrowed margin and interest
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-vip-loans-borrow-and-repay
* @param {string} code unified currency code of the currency to repay
* @param {float} amount the amount to repay
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.id] the order ID of borrowing, it is necessary while repaying
* @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/?id=margin-loan-structure}
*/
pub async fn repay_cross_margin(&mut self, mut code: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut id: Value = self.safe_string2(params.clone(), Value::Str("id".into()), Value::Str("ordId".into()), &[]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("id".into()), &[]);
if (id == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" repayCrossMargin() requires an id parameter".into()))));
}
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ccy".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("amt".to_string(), self.currency_to_precision(code, amount, &[]));
m.insert("side".to_string(), Value::Str("repay".into()));
m.insert("ordId".to_string(), id);
m
});
let __ws_arg_79 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_account_borrow_repay(&[__ws_arg_79]).await;
//
// {
// "code": "0",
// "data": [
// {
// "amt": "102",
// "ccy": "USDT",
// "ordId": "544199684697214976",
// "side": "repay",
// "state": "1"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut loan: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_loan(loan, &[currency]);
Value::Null
}
pub fn parse_margin_loan(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "amt": "102",
// "availLoan": "97",
// "ccy": "USDT",
// "loanQuota": "6000000",
// "posLoan": "0",
// "side": "repay",
// "usedLoan": "97"
// }
//
let mut currencyId: Value = self.safe_string_k(info.clone(), "ccy", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Null);
m.insert("currency".to_string(), self.safe_currency_code(currencyId, &[currency]));
m.insert("amount".to_string(), self.safe_number_k(info.clone(), "amt", &[]));
m.insert("symbol".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("info".to_string(), info);
m
});
Value::Null
}
/*
* @method
* @name okx#fetchOpenInterest
* @description Retrieves the open interest of a currency
* @see https://www.okx.com/docs-v5/en/#rest-api-public-data-get-open-interest
* @param {string} symbol Unified CCXT market symbol
* @param {object} [params] exchange specific parameters
* @returns {object} an open interest structure{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interest(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("contract")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterest() supports contract markets only".into()))));
}
let mut type_var: Value = self.convert_to_instrument_type(market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null));
let mut uly: Value = self.safe_string(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("uly".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instType".to_string(), type_var);
m.insert("uly".to_string(), uly);
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_80 = self.extend(request, &[params]);
let mut response: Value = self.public_get_public_open_interest(&[__ws_arg_80]).await;
//
// {
// "code": "0",
// "data": [
// {
// "instId": "BTC-USDT-SWAP",
// "instType": "SWAP",
// "oi": "2125419",
// "oiCcy": "21254.19",
// "ts": "1664005108969"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_open_interest(data.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), &[market]);
Value::Null
}
/*
* @method
* @name okx#fetchOpenInterests
* @description Retrieves the open interests of some currencies
* @see https://www.okx.com/docs-v5/en/#rest-api-public-data-get-open-interest
* @param {string[]} symbols Unified CCXT market symbols
* @param {object} [params] exchange specific parameters
* @param {string} params.instType Instrument type, options: 'SWAP', 'FUTURES', 'OPTION', default to 'SWAP'
* @param {string} params.uly Underlying, Applicable to FUTURES/SWAP/OPTION, if instType is 'OPTION', either uly or instFamily is required
* @param {string} params.instFamily Instrument family, Applicable to FUTURES/SWAP/OPTION, if instType is 'OPTION', either uly or instFamily is required
* @returns {object} an dictionary of [open interest structures]{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interests(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(true), Value::Bool(true)]);
let mut market: Value = Value::Null;
if (symbolsNormalized != Value::Null) {
market = self.market(symbolsNormalized.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
}
let mut marketType: Value = Value::Null;
let mut paramsSubType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{ let __destr_tmp = self.handle_sub_type_and_params(Value::Str("fetchOpenInterests".into()), &[market, params, Value::Str("swap".into())]); marketType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsSubType = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut instType: Value = Value::Str("SWAP".into());
if (marketType.as_str() == Some("future")) {
instType = Value::Str("FUTURES".into());
} else if (instType.as_str() == Some("option")) {
instType = Value::Str("OPTION".into());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instType".to_string(), instType.clone());
m
});
let mut uly: Value = self.safe_string_k(paramsSubType.clone(), "uly", &[]);
if (uly != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("uly".into(), uly.clone()); }
}
let mut instFamily: Value = self.safe_string_k(paramsSubType.clone(), "instFamily", &[]);
if (instFamily != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instFamily".into(), instFamily.clone()); }
}
if (instType.as_str() == Some("OPTION")) && (uly == Value::Null) && (instFamily == Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterests() requires either uly or instFamily parameter for OPTION markets".into()))));
}
let __ws_arg_81 = self.extend(request, &[paramsSubType]);
let mut response: Value = self.public_get_public_open_interest(&[__ws_arg_81]).await;
//
// {
// "code": "0",
// "data": [
// {
// "instId": "BTC-USDT-SWAP",
// "instType": "SWAP",
// "oi": "2125419",
// "oiCcy": "21254.19",
// "ts": "1664005108969"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_open_interests(data, &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name okx#fetchOpenInterestHistory
* @description Retrieves the open interest history of a swap or future market, or of a currency when a currency code is given
* @see https://www.okx.com/docs-v5/en/#trading-statistics-rest-api-get-contract-open-interest-history
* @see https://www.okx.com/docs-v5/en/#trading-statistics-rest-api-get-contracts-open-interest-and-volume
* @see https://www.okx.com/docs-v5/en/#trading-statistics-rest-api-get-options-open-interest-and-volume
* @param {string} symbol unified symbol of a swap or future market for the history of that instrument, otherwise a unified currency code, or the symbol of a spot or option market, for the aggregate over all contracts of the currency
* @param {string} timeframe "5m", "1h", or "1d" for option only "1d" or "8h"
* @param {int} [since] The time in ms of the earliest record to retrieve as a unix timestamp
* @param {int} [limit] the maximum number of records to retrieve, at most 100 for a swap or future market; not used by the currency aggregate
* @param {object} [params] Exchange specific parameters
* @param {int} [params.until] The time in ms of the latest record to retrieve as a unix timestamp
* @returns An array of [open interest structures]{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interest_history(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1d".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchOpenInterestHistory", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timeframes: Value = self.safe_dict_k(options, "timeframes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timeframeValue: Value = self.safe_string(timeframes, timeframe.clone(), &[timeframe.clone()]);
if (timeframeValue.as_str() != Some("5m")) && (timeframeValue.as_str() != Some("1H")) && (timeframeValue.as_str() != Some("1D")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterestHistory cannot only use the 5m, 1h, and 1d timeframe".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
// handle unified currency code or symbol
let mut currencyId: Value = Value::Null;
let mut market: Value = Value::Null;
if ((self.markets.clone() != Value::Null) && (in_op(&self.markets, &symbol))) || ((self.markets_by_id.clone() != Value::Null) && (in_op(&self.markets_by_id, &symbol))) {
market = self.market(symbol.clone());
currencyId = self.safe_string_k(market.clone(), "baseId", &[]);
} else {
let mut currency: Value = self.currency(symbol);
currencyId = self.safe_string_k(currency, "id", &[]);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ccy".to_string(), currencyId);
m.insert("period".to_string(), timeframeValue.clone());
m
});
let mut response: Value = Value::Null;
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchOpenInterestHistory".into()), &[market.clone(), params]);
let mut type_var: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (market != Value::Null) && ((market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) || (market.as_map().and_then(|__m| __m.get("future")).cloned().unwrap_or(Value::Null).as_bool() == Some(true))) {
let mut instrumentRequest: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("period".to_string(), timeframeValue.clone());
m
});
let mut instrumentRequestWindowparamsWindowVariable = self.handle_trading_statistics_window(instrumentRequest, timeframeValue, &[since.clone(), limit.clone(), paramsMarketType.clone()]);
let mut instrumentRequestWindow: Value = instrumentRequestWindowparamsWindowVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWindow: Value = instrumentRequestWindowparamsWindowVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_82 = self.extend(instrumentRequestWindow, &[paramsWindow]);
response = self.public_get_rubik_stat_contracts_open_interest_history(&[__ws_arg_82]).await;
//
// {
// "code": "0",
// "data": [
// [
// "1790550000000", // timestamp
// "2800476.45", // open interest (contracts)
// "28006.5419", // open interest (base currency)
// "2360916466.88", // open interest (USD)
// ],
// ...
// ],
// "msg": ""
// }
//
let mut instrumentData: Value = self.safe_list_k(response.clone(), "data", &[Value::from(vec![])]);
return self.parse_open_interests_history(instrumentData, &[market, since.clone(), limit.clone()]);
}
if (type_var.as_str() == Some("option")) {
let __ws_arg_83 = self.extend(request.clone(), &[paramsMarketType.clone()]);
response = self.public_get_rubik_stat_option_open_interest_volume(&[__ws_arg_83]).await;
} else {
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("begin".into(), since.clone()); }
}
let mut until: Value = self.safe_integer_k(paramsMarketType.clone(), "until", &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), until.clone()); }
}
let mut paramsOmitted: Value = (if (until != Value::Null) { self.omit(paramsMarketType.clone(), Value::from(vec![Value::Str("until".into())]), &[]) } else { paramsMarketType });
let __ws_arg_84 = self.extend(request, &[paramsOmitted]);
response = self.public_get_rubik_stat_contracts_open_interest_volume(&[__ws_arg_84]).await;
}
//
// {
// "code": "0",
// "data": [
// [
// "1648221300000", // timestamp
// "2183354317.945", // open interest (USD)
// "74285877.617", // volume (USD)
// ],
// ...
// ],
// "msg": ''
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_open_interests_history(data, &[Value::Null, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name okx#handleTradingStatisticsWindow
* @description sets begin, end and limit of a trading statistics history request: okx treats both bounds as exclusive and returns the latest entries first, while since and until are inclusive and since with a limit asks for the earliest entries from since on
* @param {object} request the request of the history endpoint
* @param {string} period the okx period of the request, e.g. 5m, 1H, 2D, 1M or 6Hutc
* @param {int} [since] the earliest time in ms of the entries to fetch
* @param {int} [limit] the maximum number of entries to fetch, at most 100
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms of the entries to fetch
* @returns {object[]} the request and the remaining params
*/
pub fn handle_trading_statistics_window(&self, mut request: Value, mut period: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut maxLimit: Value = Value::Int(100);
let mut effectiveLimit: Value = (if (limit == Value::Null) { maxLimit.clone() } else { crate::runtime::Math::min(&limit, &maxLimit) });
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), effectiveLimit.clone()); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("begin".into(), (match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })); }
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("until".into()), &[]);
let mut end: Value = Value::Null;
if (until != Value::Null) {
end = self.sum(&[until, Value::Int(1)]);
}
if (since != Value::Null) {
// end the window after limit periods, so that the earliest entries from since on come back
// okx periods are 5m, 1H, 2D, 1W, 1M, 3M and so on, optionally with a utc suffix that only moves the opening time
let mut unitPeriod: Value = (if (ends_with(&period, &Value::Str("utc".into()))) { period.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = (__l - 3).max(0); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null) } else { period.clone() });
let mut unit: Value = unitPeriod.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 1).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut windowDuration: Value = Value::Null;
if (unit.as_str() == Some("M")) {
// calendar months last 28 to 31 days: the window spans limit of the longest months, but no more than 100 of the shortest,
// all entries in it are requested and the caller keeps the earliest limit of them
let mut months: Value = self.parse_to_int(unitPeriod.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = __l.min(0); let __j = (__l - 1).max(0); if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
let mut day: Value = Value::Int(86400000);
windowDuration = crate::runtime::Math::min(&(match (&((match (&((match (&(effectiveLimit), &(months)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(31))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(day)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }), &(match (&((match (&((match (&(maxLimit), &(months)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(28))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(day)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), maxLimit); }
} else {
windowDuration = (match (&((match (&(effectiveLimit), &(self.parse_timeframe(to_lower(&unitPeriod)))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
}
let mut windowEnd: Value = self.sum(&[since, windowDuration]);
end = (if (end == Value::Null) { windowEnd.clone() } else { crate::runtime::Math::min(&end, &windowEnd) });
}
if (end != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), end); }
}
return Value::from(vec![request, paramsOmitted]);
Value::Null
}
pub fn parse_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchOpenInterestHistory
//
// [
// "1648221300000", // timestamp
// "2183354317.945", // open interest (USD) - (coin) for options
// "74285877.617", // volume (USD) - (coin) for options
// ]
//
// fetchOpenInterestHistory for a swap or future market
//
// [
// "1790550000000", // timestamp
// "2800476.45", // open interest (contracts)
// "28006.5419", // open interest (base currency)
// "2360916466.88", // open interest (USD)
// ]
//
// fetchOpenInterest
//
// {
// "instId": "BTC-USD-230520-25500-P",
// "instType": "OPTION",
// "oi": "300",
// "oiCcy": "3",
// "oiUsd": "3",
// "ts": "1684551166251"
// }
//
let mut id: Value = self.safe_string_k(interest.clone(), "instId", &[]);
let mut marketResolved: Value = self.safe_market(&[id.clone(), market]);
let mut time: Value = self.safe_integer_k(interest.clone(), "ts", &[]);
let mut timestamp: Value = self.safe_integer(interest.clone(), Value::Int(0), &[time]);
let mut baseVolume: Value = Value::Null;
let mut quoteVolume: Value = Value::Null;
let mut openInterestAmount: Value = Value::Null;
let mut openInterestValue: Value = Value::Null;
let mut type_var: Option<String> = self.safe_string_k(self.options.clone(), "defaultType", &[]).as_str().map(str::to_owned);
if (matches!(&interest, Value::Arr(_))) {
let mut numFields: f64 = ((interest.len() as i64) as f64);
if numFields > ((3i64) as f64) {
openInterestAmount = self.safe_number(interest.clone(), Value::Int(1), &[]);
baseVolume = self.safe_number(interest.clone(), Value::Int(2), &[]);
openInterestValue = self.safe_number(interest.clone(), Value::Int(3), &[]);
} else if (type_var.as_deref() == Some("option")) {
openInterestAmount = self.safe_number(interest.clone(), Value::Int(1), &[]);
baseVolume = self.safe_number(interest.clone(), Value::Int(2), &[]);
} else {
openInterestValue = self.safe_number(interest.clone(), Value::Int(1), &[]);
quoteVolume = self.safe_number(interest.clone(), Value::Int(2), &[]);
}
} else {
baseVolume = self.safe_number_k(interest.clone(), "oiCcy", &[]);
openInterestAmount = self.safe_number_k(interest.clone(), "oi", &[]);
openInterestValue = self.safe_number_k(interest.clone(), "oiUsd", &[]);
}
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_symbol(id, &[]));
m.insert("baseVolume".to_string(), baseVolume);
m.insert("quoteVolume".to_string(), quoteVolume);
m.insert("openInterestAmount".to_string(), openInterestAmount);
m.insert("openInterestValue".to_string(), openInterestValue);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("info".to_string(), interest);
m
}), &[marketResolved]);
Value::Null
}
pub fn set_sandbox_mode(&mut self, mut enable: Value) {
self.super_set_sandbox_mode(enable.clone());
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("sandboxMode".into(), enable.clone()); }
if is_true(&enable) {
add_element_to_object(&mut self.headers, &Value::Str("x-simulated-trading".into()), Value::Str("1".into()));
} else if (matches!(&self.headers, Value::Dict(__d) if __d.contains_key("x-simulated-trading"))) {
{ let __t = self.omit(self.headers.clone(), Value::Str("x-simulated-trading".into()), &[]); self.headers = __t; }
}
}
/*
* @method
* @name okx#fetchDepositWithdrawFees
* @description fetch deposit and withdraw fees
* @see https://www.okx.com/docs-v5/en/#rest-api-funding-get-currencies
* @param {string[]|undefined} codes list of unified currency codes
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [fees structures]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_deposit_withdraw_fees(&mut self, optional_args: &[Value]) -> Value {
let mut codes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (codes != Value::Null) {
let mut ids: Value = self.currency_ids(&[codes.clone()]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), join(&ids, &Value::Str(",".into()))); }
}
let __ws_arg_85 = self.extend(request, &[params]);
let mut response: Value = self.private_get_asset_currencies(&[__ws_arg_85]).await;
//
// {
// "code": "0",
// "data": [
// {
// "canDep": true,
// "canInternal": false,
// "canWd": true,
// "ccy": "USDT",
// "chain": "USDT-TRC20",
// "logoLink": "https://static.coinall.ltd/cdn/assets/imgs/221/5F74EB20302D7761.png",
// "mainNet": false,
// "maxFee": "1.6",
// "maxWd": "8852150",
// "minFee": "0.8",
// "minWd": "2",
// "name": "Tether",
// "usedWdQuota": "0",
// "wdQuota": "500",
// "wdTickSz": "3"
// },
// {
// "canDep": true,
// "canInternal": false,
// "canWd": true,
// "ccy": "USDT",
// "chain": "USDT-ERC20",
// "logoLink": "https://static.coinall.ltd/cdn/assets/imgs/221/5F74EB20302D7761.png",
// "mainNet": false,
// "maxFee": "16",
// "maxWd": "8852150",
// "minFee": "8",
// "minWd": "2",
// "name": "Tether",
// "usedWdQuota": "0",
// "wdQuota": "500",
// "wdTickSz": "3"
// },
// ...
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[]);
return self.parse_deposit_withdraw_fees(data, &[codes]);
Value::Null
}
pub fn parse_deposit_withdraw_fees(&self, mut response: Value, optional_args: &[Value]) -> Value {
let mut codes = get_arg(optional_args, 0, Value::Null);
let mut currencyIdKey = get_arg(optional_args, 1, Value::Null);
//
// [
// {
// "canDep": true,
// "canInternal": false,
// "canWd": true,
// "ccy": "USDT",
// "chain": "USDT-TRC20",
// "logoLink": "https://static.coinall.ltd/cdn/assets/imgs/221/5F74EB20302D7761.png",
// "mainNet": false,
// "maxFee": "1.6",
// "maxWd": "8852150",
// "minFee": "0.8",
// "minWd": "2",
// "name": "Tether",
// "usedWdQuota": "0",
// "wdQuota": "500",
// "wdTickSz": "3"
// }
// ]
//
let mut depositWithdrawFees: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut codesValue: Value = self.market_codes(&[codes]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1004: bool = true;
while { if !__for_first_1004 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1004 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&response).as_f64().unwrap_or(f64::NAN) } {
let mut feeInfo: Value = get_value(&response, &i);
let mut feeInfo: Value = get_value(&response, &i);
let mut currencyId: Value = self.safe_string_k(feeInfo.clone(), "ccy", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
if (code != Value::Null) && ((codesValue == Value::Null) || self.in_array(code.clone(), codesValue.clone()).as_bool() == Some(true)) {
let mut depositWithdrawFee: Value = self.safe_dict(depositWithdrawFees.clone(), code.clone(), &[]);
if (depositWithdrawFee == Value::Null) {
if let Value::Dict(__d) = &mut depositWithdrawFees { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), self.deposit_withdraw_fee(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}))); }
}
if (currencyId != Value::Null) {
add_element_to_object(get_value_mut(get_value_mut(&mut depositWithdrawFees, &code), &Value::Str("info".into())), ¤cyId, feeInfo.clone());
}
let mut chain: Value = self.safe_string_k(feeInfo.clone(), "chain", &[]);
if (chain == Value::Null) {
continue;
}
let mut chainSplit: Value = split(&chain, &Value::Str("-".into()));
let mut networkId: Value = self.safe_string(chainSplit, Value::Int(1), &[]);
let mut withdrawFee: Value = self.safe_number_k(feeInfo, "fee", &[]);
let mut withdrawResult: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), withdrawFee.clone());
m.insert("percentage".to_string(), (if (withdrawFee != Value::Null) { Value::Bool(false) } else { Value::Null }));
m
});
let mut depositResult: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("fee".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
});
let mut networkCode: Value = self.network_id_to_code(&[networkId, code.clone()]);
if (networkCode != Value::Null) {
add_element_to_object(get_value_mut(get_value_mut(&mut depositWithdrawFees, &code), &Value::Str("networks".into())), &networkCode, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("withdraw".to_string(), withdrawResult);
m.insert("deposit".to_string(), depositResult);
m
}));
}
}
}
}
let mut depositWithdrawCodes: Value = object_keys(&depositWithdrawFees);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1005: bool = true;
while { if !__for_first_1005 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1005 = false; i.as_f64().unwrap_or(f64::NAN) < ((depositWithdrawCodes.len() as i64) as f64) } {
let mut code: Value = depositWithdrawCodes.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut currency: Value = self.currency(code.clone());
{ let __be_tmp = self.assign_default_deposit_withdraw_fees(get_value(&depositWithdrawFees, &code), &[currency]); if let Value::Dict(__d) = &mut depositWithdrawFees { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), __be_tmp); } }
}
}
return depositWithdrawFees;
Value::Null
}
/*
* @method
* @name okx#fetchSettlementHistory
* @description fetches historical settlement records
* @see https://www.okx.com/docs-v5/en/#rest-api-public-data-get-delivery-exercise-history
* @param {string} symbol unified market symbol to fetch the settlement history for
* @param {int} [since] timestamp in ms
* @param {int} [limit] number of records
* @param {object} [params] exchange specific params
* @returns {object[]} a list of [settlement history objects]{@link https://docs.ccxt.com/?id=settlement-history-structure}
*/
pub async fn fetch_settlement_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchSettlementHistory() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut type_varparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchSettlementHistory".into()), &[market.clone(), params]);
let mut type_var: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = type_varparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (type_var.as_str() != Some("future")) && (type_var.as_str() != Some("option")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchSettlementHistory() supports futures and options markets only".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instType".to_string(), self.convert_to_instrument_type(type_var));
m.insert("uly".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null), Value::Str("-".into())).into()), market.as_map().and_then(|__m| __m.get("quoteId")).cloned().unwrap_or(Value::Null)).into()));
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), (match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let __ws_arg_86 = self.extend(request, &[paramsMarketType]);
let mut response: Value = self.public_get_public_delivery_exercise_history(&[__ws_arg_86]).await;
//
// {
// "code": "0",
// "data": [
// {
// "details": [
// {
// "insId": "BTC-USD-230523-25750-C",
// "px": "27290.1486867000556483",
// "type": "exercised"
// },
// ],
// "ts":"1684656000000"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut settlements: Value = self.parse_settlements(data, market.clone());
let mut sorted: Value = self.sort_by(settlements, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[self.safe_string_k(market, "symbol", &[]), since, limit]);
Value::Null
}
pub fn parse_settlement(&self, mut settlement: Value, mut market: Value) -> Value {
//
// {
// "insId": "BTC-USD-230521-28500-P",
// "px": "27081.2007345984751516",
// "type": "exercised"
// }
//
let mut marketId: Value = self.safe_string_k(settlement.clone(), "insId", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), settlement.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("price".to_string(), self.safe_number_k(settlement, "px", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
Value::Null
}
pub fn parse_settlements(&self, mut settlements: Value, mut market: Value) -> Value {
//
// {
// "details": [
// {
// "insId": "BTC-USD-230523-25750-C",
// "px": "27290.1486867000556483",
// "type": "exercised"
// },
// ],
// "ts":"1684656000000"
// }
//
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1007: bool = true;
while { if !__for_first_1007 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1007 = false; i.as_f64().unwrap_or(f64::NAN) < ((settlements.len() as i64) as f64) } {
let mut entry: Value = self.safe_dict(settlements.clone(), i.clone(), &[]);
let mut timestamp: Value = self.safe_integer_k(entry.clone(), "ts", &[]);
let mut details: Value = self.safe_list_k(entry, "details", &[Value::from(vec![])]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1006: bool = true;
while { if !__for_first_1006 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1006 = false; j.as_f64().unwrap_or(f64::NAN) < ((details.len() as i64) as f64) } {
let mut settlement: Value = self.parse_settlement(details.as_array().and_then(|__arr| match &j { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), market.clone());
let __ws_arg_87 = self.iso8601(timestamp.clone());
append_to_array(&mut result, self.extend(settlement, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), __ws_arg_87);
m
})]));
}
}
}
}
return result;
Value::Null
}
/*
* @method
* @name okx#fetchUnderlyingAssets
* @description fetches the market ids of underlying assets for a specific contract market type
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-underlying
* @param {object} [params] exchange specific params
* @param {string} [params.type] the contract market type, 'option', 'swap' or 'future', the default is 'option'
* @returns {object[]} a list of [underlying assets]{@link https://docs.ccxt.com/?id=underlying-assets-structure}
*/
pub async fn fetch_underlying_assets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut marketTypeOptionparamsMarketTypeVariable = self.handle_market_type_and_params(Value::Str("fetchUnderlyingAssets".into()), &[Value::Null, params]);
let mut marketTypeOption: Value = marketTypeOptionparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = marketTypeOptionparamsMarketTypeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut isSpotOrUndefined: bool = (marketTypeOption == Value::Null) || (marketTypeOption.as_str() == Some("spot"));
let mut marketType: Value = marketTypeOption;
if isSpotOrUndefined {
marketType = Value::Str("option".into());
}
if (marketType.as_str() != Some("option")) && (marketType.as_str() != Some("swap")) && (marketType.as_str() != Some("future")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchUnderlyingAssets() supports contract markets only".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instType".to_string(), self.convert_to_instrument_type(marketType));
m
});
let __ws_arg_88 = self.extend(request, &[paramsMarketType]);
let mut response: Value = self.public_get_public_underlying(&[__ws_arg_88]).await;
//
// {
// "code": "0",
// "data": [
// [
// "BTC-USD",
// "ETH-USD"
// ]
// ],
// "msg": ""
// }
//
let mut underlyings: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return underlyings.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
Value::Null
}
/*
* @method
* @name okx#fetchGreeks
* @description fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-option-market-data
* @param {string} symbol unified symbol of the market to fetch greeks for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [greeks structure]{@link https://docs.ccxt.com/?id=greeks-structure}
*/
pub async fn fetch_greeks(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut marketId: Value = self.safe_string_k(market.clone(), "id", &[Value::Str("".into())]);
let mut optionParts: Value = split(&marketId, &Value::Str("-".into()));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("uly".to_string(), crate::value::get_value_k(&market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), "uly"));
m.insert("instFamily".to_string(), crate::value::get_value_k(&market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), "instFamily"));
m.insert("expTime".to_string(), self.safe_string(optionParts, Value::Int(2), &[]));
m
});
let __ws_arg_89 = self.extend(request, &[params]);
let mut response: Value = self.public_get_public_opt_summary(&[__ws_arg_89]).await;
//
// {
// "code": "0",
// "data": [
// {
// "askVol": "0",
// "bidVol": "0",
// "delta": "0.5105464486882039",
// "deltaBS": "0.7325502184143025",
// "fwdPx": "37675.80158694987186",
// "gamma": "-0.13183515090501083",
// "gammaBS": "0.000024139685826358558",
// "instId": "BTC-USD-240329-32000-C",
// "instType": "OPTION",
// "lever": "4.504428015946619",
// "markVol": "0.5916253554539876",
// "realVol": "0",
// "theta": "-0.0004202992014012855",
// "thetaBS": "-18.52354631567909",
// "ts": "1699586421976",
// "uly": "BTC-USD",
// "vega": "0.0020207455080045846",
// "vegaBS": "74.44022302387287",
// "volLv": "0.5948549730405797"
// },
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1008: bool = true;
while { if !__for_first_1008 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1008 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut entry: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut entryMarketId: Value = self.safe_string_k(entry.clone(), "instId", &[]);
if (entryMarketId.as_str() == marketId.as_str()) {
return self.parse_greeks(entry, &[market.clone()]);
}
}
}
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchGreeks() could not find greeks for ".into())).into()), symbol)));
Value::Null
}
/*
* @method
* @name okx#fetchAllGreeks
* @description fetches all option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract
* @see https://www.okx.com/docs-v5/en/#public-data-rest-api-get-option-market-data
* @param {string[]} [symbols] unified symbols of the markets to fetch greeks for, all markets are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} params.uly Underlying, either uly or instFamily is required
* @param {string} params.instFamily Instrument family, either uly or instFamily is required
* @returns {object} a dictionary of [greeks structures]{@link https://docs.ccxt.com/?id=greeks-structure} indexed by market symbol
*/
pub async fn fetch_all_greeks(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut symbolsNormalized: Value = self.market_symbols(&[symbols, Value::Null, Value::Bool(true), Value::Bool(true), Value::Bool(true)]);
let mut symbolsLength: Value = Value::Null;
if (symbolsNormalized != Value::Null) {
symbolsLength = Value::Int(symbolsNormalized.len() as i64);
}
if (symbolsNormalized == Value::Null) || (symbolsLength.as_f64() != Some(1.0)) {
let mut uly: Value = self.safe_string_k(params.clone(), "uly", &[]);
if (uly != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("uly".into(), uly.clone()); }
}
let mut instFamily: Value = self.safe_string_k(params.clone(), "instFamily", &[]);
if (instFamily != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instFamily".into(), instFamily.clone()); }
}
if (uly == Value::Null) && (instFamily == Value::Null) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchAllGreeks() requires either a uly or instFamily parameter".into()))));
}
}
let mut market: Value = Value::Null;
if (symbolsNormalized != Value::Null) {
if (symbolsLength.as_f64() == Some(1.0)) {
market = self.market(symbolsNormalized.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
let mut marketId: Value = self.safe_string_k(market.clone(), "id", &[Value::Str("".into())]);
let mut optionParts: Value = split(&marketId, &Value::Str("-".into()));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("uly".into(), crate::value::get_value_k(&market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), "uly")); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instFamily".into(), crate::value::get_value_k(&market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), "instFamily")); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("expTime".into(), self.safe_string(optionParts, Value::Int(2), &[])); }
}
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("uly".into()), Value::Str("instFamily".into())]), &[]);
let __ws_arg_90 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.public_get_public_opt_summary(&[__ws_arg_90]).await;
//
// {
// "code": "0",
// "data": [
// {
// "askVol": "0",
// "bidVol": "0",
// "delta": "0.5105464486882039",
// "deltaBS": "0.7325502184143025",
// "fwdPx": "37675.80158694987186",
// "gamma": "-0.13183515090501083",
// "gammaBS": "0.000024139685826358558",
// "instId": "BTC-USD-240329-32000-C",
// "instType": "OPTION",
// "lever": "4.504428015946619",
// "markVol": "0.5916253554539876",
// "realVol": "0",
// "theta": "-0.0004202992014012855",
// "thetaBS": "-18.52354631567909",
// "ts": "1699586421976",
// "uly": "BTC-USD",
// "vega": "0.0020207455080045846",
// "vegaBS": "74.44022302387287",
// "volLv": "0.5948549730405797"
// },
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_all_greeks(data, &[symbolsNormalized]);
Value::Null
}
pub fn parse_greeks(&self, mut greeks: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "askVol": "0",
// "bidVol": "0",
// "delta": "0.5105464486882039",
// "deltaBS": "0.7325502184143025",
// "fwdPx": "37675.80158694987186",
// "gamma": "-0.13183515090501083",
// "gammaBS": "0.000024139685826358558",
// "instId": "BTC-USD-240329-32000-C",
// "instType": "OPTION",
// "lever": "4.504428015946619",
// "markVol": "0.5916253554539876",
// "realVol": "0",
// "theta": "-0.0004202992014012855",
// "thetaBS": "-18.52354631567909",
// "ts": "1699586421976",
// "uly": "BTC-USD",
// "vega": "0.0020207455080045846",
// "vegaBS": "74.44022302387287",
// "volLv": "0.5948549730405797"
// }
//
let mut timestamp: Value = self.safe_integer_k(greeks.clone(), "ts", &[]);
let mut marketId: Value = self.safe_string_k(greeks.clone(), "instId", &[]);
let mut symbol: Value = self.safe_symbol(marketId, &[market]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("delta".to_string(), self.safe_number_k(greeks.clone(), "delta", &[]));
m.insert("gamma".to_string(), self.safe_number_k(greeks.clone(), "gamma", &[]));
m.insert("theta".to_string(), self.safe_number_k(greeks.clone(), "theta", &[]));
m.insert("vega".to_string(), self.safe_number_k(greeks.clone(), "vega", &[]));
m.insert("rho".to_string(), Value::Null);
m.insert("bidSize".to_string(), Value::Null);
m.insert("askSize".to_string(), Value::Null);
m.insert("bidImpliedVolatility".to_string(), self.safe_number_k(greeks.clone(), "bidVol", &[]));
m.insert("askImpliedVolatility".to_string(), self.safe_number_k(greeks.clone(), "askVol", &[]));
m.insert("markImpliedVolatility".to_string(), self.safe_number_k(greeks.clone(), "markVol", &[]));
m.insert("bidPrice".to_string(), Value::Null);
m.insert("askPrice".to_string(), Value::Null);
m.insert("markPrice".to_string(), Value::Null);
m.insert("lastPrice".to_string(), Value::Null);
m.insert("underlyingPrice".to_string(), Value::Null);
m.insert("info".to_string(), greeks);
m
});
Value::Null
}
/*
* @method
* @name okx#closePosition
* @description closes open positions for a market
* @see https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-close-positions
* @param {string} symbol Unified CCXT market symbol
* @param {string} [side] 'buy' or 'sell', leave as undefined in net mode
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] a unique identifier for the order
* @param {string} [params.marginMode] 'cross' or 'isolated', default is 'cross;
* @param {string} [params.code] *required in the case of closing cross MARGIN position for Single-currency margin* margin currency
*
* EXCHANGE SPECIFIC PARAMETERS
* @param {boolean} [params.autoCxl] whether any pending orders for closing out needs to be automatically canceled when close position via a market order. false or true, the default is false
* @param {string} [params.tag] order tag a combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters
* @returns {object[]} [A list of position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn close_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut side = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[]);
let mut code: Value = self.safe_string_k(params.clone(), "code", &[]);
let mut marginModeparamsMarginModeVariable = self.handle_margin_mode_and_params(Value::Str("closePosition".into()), &[params, Value::Str("cross".into())]);
let mut marginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("mgnMode".to_string(), marginMode);
m
});
if (side != Value::Null) {
if (side.as_str() == Some("buy")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("posSide".into(), Value::Str("long".into())); }
} else if (side.as_str() == Some("sell")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("posSide".into(), Value::Str("short".into())); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("posSide".into(), side); }
}
}
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clOrdId".into(), clientOrderId); }
}
if (code != Value::Null) {
let mut currency: Value = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ccy".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
let __ws_arg_91 = self.extend(request, &[paramsMarginMode]);
let mut response: Value = self.private_post_trade_close_position(&[__ws_arg_91]).await;
//
// {
// "code": "1",
// "data": [
// {
// "clOrdId":"e847386590ce4dBCe903bbc394dc88bf",
// "ordId":"",
// "sCode":"51000",
// "sMsg":"Parameter posSide error ",
// "tag":"e847386590ce4dBC"
// }
// ],
// "inTime": "1701877077101064",
// "msg": "All operations failed",
// "outTime": "1701877077102579"
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut order: Value = self.safe_dict(data, Value::Int(0), &[]);
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name okx#fetchOption
* @description fetches option data that is commonly found in an option chain
* @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-ticker
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [option chain structure]{@link https://docs.ccxt.com/?id=option-chain-structure}
*/
pub async fn fetch_option(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_92 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_ticker(&[__ws_arg_92]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "instType": "OPTION",
// "instId": "BTC-USD-241227-60000-P",
// "last": "",
// "lastSz": "0",
// "askPx": "",
// "askSz": "0",
// "bidPx": "",
// "bidSz": "0",
// "open24h": "",
// "high24h": "",
// "low24h": "",
// "volCcy24h": "0",
// "vol24h": "0",
// "ts": "1711176035035",
// "sodUtc0": "",
// "sodUtc8": ""
// }
// ]
// }
//
let mut result: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut chain: Value = self.safe_dict(result, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_option(chain, &[Value::Null, market]);
Value::Null
}
/*
* @method
* @name okx#fetchOptionChain
* @description fetches data for an underlying asset that is commonly found in an option chain
* @see https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-tickers
* @param {string} code base currency to fetch an option chain for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.uly] the underlying asset, can be obtained from fetchUnderlyingAssets ()
* @returns {object} a list of [option chain structures]{@link https://docs.ccxt.com/?id=option-chain-structure}
*/
pub async fn fetch_option_chain(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("uly".to_string(), Value::Str(format!("{}{}", currency.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null), Value::Str("-USD".into())).into()));
m.insert("instType".to_string(), Value::Str("OPTION".into()));
m
});
let __ws_arg_93 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_tickers(&[__ws_arg_93]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "instType": "OPTION",
// "instId": "BTC-USD-240323-52000-C",
// "last": "",
// "lastSz": "0",
// "askPx": "",
// "askSz": "0",
// "bidPx": "",
// "bidSz": "0",
// "open24h": "",
// "high24h": "",
// "low24h": "",
// "volCcy24h": "0",
// "vol24h": "0",
// "ts": "1711176207008",
// "sodUtc0": "",
// "sodUtc8": ""
// },
// ]
// }
//
let mut result: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_option_chain(result, &[Value::Null, Value::Str("instId".into())]);
Value::Null
}
pub fn parse_option(&self, mut chain: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let mut market = get_arg(optional_args, 1, Value::Null);
//
// {
// "instType": "OPTION",
// "instId": "BTC-USD-241227-60000-P",
// "last": "",
// "lastSz": "0",
// "askPx": "",
// "askSz": "0",
// "bidPx": "",
// "bidSz": "0",
// "open24h": "",
// "high24h": "",
// "low24h": "",
// "volCcy24h": "0",
// "vol24h": "0",
// "ts": "1711176035035",
// "sodUtc0": "",
// "sodUtc8": ""
// }
//
let mut marketId: Value = self.safe_string_k(chain.clone(), "instId", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut timestamp: Value = self.safe_integer_k(chain.clone(), "ts", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), chain.clone());
m.insert("currency".to_string(), Value::Null);
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("impliedVolatility".to_string(), Value::Null);
m.insert("openInterest".to_string(), Value::Null);
m.insert("bidPrice".to_string(), self.safe_number_k(chain.clone(), "bidPx", &[]));
m.insert("askPrice".to_string(), self.safe_number_k(chain.clone(), "askPx", &[]));
m.insert("midPrice".to_string(), Value::Null);
m.insert("markPrice".to_string(), Value::Null);
m.insert("lastPrice".to_string(), self.safe_number_k(chain.clone(), "last", &[]));
m.insert("underlyingPrice".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("baseVolume".to_string(), self.safe_number_k(chain, "volCcy24h", &[]));
m.insert("quoteVolume".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name okx#fetchConvertQuote
* @description fetch a quote for converting from one currency to another
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-estimate-quote
* @param {string} fromCode the currency that you want to sell and convert from
* @param {string} toCode the currency that you want to buy and convert into
* @param {float} [amount] how much you want to trade in units of the from currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [conversion structure]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn fetch_convert_quote(&mut self, mut fromCode: Value, mut toCode: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("baseCcy".to_string(), to_upper(&fromCode));
m.insert("quoteCcy".to_string(), to_upper(&toCode));
m.insert("rfqSzCcy".to_string(), to_upper(&fromCode));
m.insert("rfqSz".to_string(), self.number_to_string(amount));
m.insert("side".to_string(), Value::Str("sell".into()));
m
});
let __ws_arg_94 = self.extend(request, &[params]);
let mut response: Value = self.private_post_asset_convert_estimate_quote(&[__ws_arg_94]).await;
//
// {
// "code": "0",
// "data": [
// {
// "baseCcy": "ETH",
// "baseSz": "0.01023052",
// "clQReqId": "",
// "cnvtPx": "2932.40104429",
// "origRfqSz": "30",
// "quoteCcy": "USDT",
// "quoteId": "quoterETH-USDT16461885104612381",
// "quoteSz": "30",
// "quoteTime": "1646188510461",
// "rfqSz": "30",
// "rfqSzCcy": "USDT",
// "side": "buy",
// "ttlMs": "10000"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromCurrencyId: Value = self.safe_string_k(result.clone(), "baseCcy", &[fromCode]);
let mut fromCurrency: Value = self.currency(fromCurrencyId);
let mut toCurrencyId: Value = self.safe_string_k(result.clone(), "quoteCcy", &[toCode]);
let mut toCurrency: Value = self.currency(toCurrencyId);
return self.parse_conversion(result, &[fromCurrency, toCurrency]);
Value::Null
}
/*
* @method
* @name okx#createConvertTrade
* @description convert from one currency to another
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-convert-trade
* @param {string} id the id of the trade that you want to make
* @param {string} fromCode the currency that you want to sell and convert from
* @param {string} toCode the currency that you want to buy and convert into
* @param {float} [amount] how much you want to trade in units of the from currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [conversion structure]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn create_convert_trade(&mut self, mut id: Value, mut fromCode: Value, mut toCode: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("quoteId".to_string(), id);
m.insert("baseCcy".to_string(), fromCode.clone());
m.insert("quoteCcy".to_string(), toCode.clone());
m.insert("szCcy".to_string(), fromCode.clone());
m.insert("sz".to_string(), self.number_to_string(amount));
m.insert("side".to_string(), Value::Str("sell".into()));
m
});
let __ws_arg_95 = self.extend(request, &[params]);
let mut response: Value = self.private_post_asset_convert_trade(&[__ws_arg_95]).await;
//
// {
// "code": "0",
// "data": [
// {
// "baseCcy": "ETH",
// "clTReqId": "",
// "fillBaseSz": "0.01023052",
// "fillPx": "2932.40104429",
// "fillQuoteSz": "30",
// "instId": "ETH-USDT",
// "quoteCcy": "USDT",
// "quoteId": "quoterETH-USDT16461885104612381",
// "side": "buy",
// "state": "fullyFilled",
// "tradeId": "trader16461885203381437",
// "ts": "1646188520338"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromCurrencyId: Value = self.safe_string_k(result.clone(), "baseCcy", &[fromCode]);
let mut fromCurrency: Value = self.currency(fromCurrencyId);
let mut toCurrencyId: Value = self.safe_string_k(result.clone(), "quoteCcy", &[toCode]);
let mut toCurrency: Value = self.currency(toCurrencyId);
return self.parse_conversion(result, &[fromCurrency, toCurrency]);
Value::Null
}
/*
* @method
* @name okx#fetchConvertTrade
* @description fetch the data for a conversion trade
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-convert-history
* @param {string} id the id of the trade that you want to fetch
* @param {string} [code] the unified currency code of the conversion trade
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [conversion structure]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn fetch_convert_trade(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("clTReqId".to_string(), id);
m
});
let __ws_arg_96 = self.extend(request, &[params]);
let mut response: Value = self.private_get_asset_convert_history(&[__ws_arg_96]).await;
//
// {
// "code": "0",
// "data": [
// {
// "clTReqId": "",
// "instId": "ETH-USDT",
// "side": "buy",
// "fillPx": "2932.401044",
// "baseCcy": "ETH",
// "quoteCcy": "USDT",
// "fillBaseSz": "0.01023052",
// "state": "fullyFilled",
// "tradeId": "trader16461885203381437",
// "fillQuoteSz": "30",
// "ts": "1646188520000"
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromCurrencyId: Value = self.safe_string_k(result.clone(), "baseCcy", &[]);
let mut toCurrencyId: Value = self.safe_string_k(result.clone(), "quoteCcy", &[]);
let mut fromCurrency: Value = Value::Null;
let mut toCurrency: Value = Value::Null;
if (fromCurrencyId != Value::Null) {
fromCurrency = self.currency(fromCurrencyId);
}
if (toCurrencyId != Value::Null) {
toCurrency = self.currency(toCurrencyId);
}
return self.parse_conversion(result, &[fromCurrency, toCurrency]);
Value::Null
}
/*
* @method
* @name okx#fetchConvertTradeHistory
* @description fetch the users history of conversion trades
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-convert-history
* @param {string} [code] the unified currency code
* @param {int} [since] the earliest time in ms to fetch conversions for
* @param {int} [limit] the maximum number of conversion structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest conversion to fetch
* @returns {object[]} a list of [conversion structures]{@link https://docs.ccxt.com/?id=conversion-structure}
*/
pub async fn fetch_convert_trade_history(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut requestUntilparamsUntilVariable = self.handle_until_option(Value::Str("after".into()), request, params, &[]);
let mut requestUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (since != Value::Null) {
add_element_to_object(&mut requestUntil, &Value::Str("before".into()), since.clone());
}
if (limit != Value::Null) {
add_element_to_object(&mut requestUntil, &Value::Str("limit".into()), limit.clone());
}
let __ws_arg_97 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.private_get_asset_convert_history(&[__ws_arg_97]).await;
//
// {
// "code": "0",
// "data": [
// {
// "clTReqId": "",
// "instId": "ETH-USDT",
// "side": "buy",
// "fillPx": "2932.401044",
// "baseCcy": "ETH",
// "quoteCcy": "USDT",
// "fillBaseSz": "0.01023052",
// "state": "fullyFilled",
// "tradeId": "trader16461885203381437",
// "fillQuoteSz": "30",
// "ts": "1646188520000"
// }
// ],
// "msg": ""
// }
//
let mut rows: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_conversions(rows, &[code, Value::Str("baseCcy".into()), Value::Str("quoteCcy".into()), since, limit]);
Value::Null
}
pub fn parse_conversion(&self, mut conversion: Value, optional_args: &[Value]) -> Value {
let mut fromCurrency = get_arg(optional_args, 0, Value::Null);
let mut toCurrency = get_arg(optional_args, 1, Value::Null);
//
// fetchConvertQuote
//
// {
// "baseCcy": "ETH",
// "baseSz": "0.01023052",
// "clQReqId": "",
// "cnvtPx": "2932.40104429",
// "origRfqSz": "30",
// "quoteCcy": "USDT",
// "quoteId": "quoterETH-USDT16461885104612381",
// "quoteSz": "30",
// "quoteTime": "1646188510461",
// "rfqSz": "30",
// "rfqSzCcy": "USDT",
// "side": "buy",
// "ttlMs": "10000"
// }
//
// createConvertTrade
//
// {
// "baseCcy": "ETH",
// "clTReqId": "",
// "fillBaseSz": "0.01023052",
// "fillPx": "2932.40104429",
// "fillQuoteSz": "30",
// "instId": "ETH-USDT",
// "quoteCcy": "USDT",
// "quoteId": "quoterETH-USDT16461885104612381",
// "side": "buy",
// "state": "fullyFilled",
// "tradeId": "trader16461885203381437",
// "ts": "1646188520338"
// }
//
// fetchConvertTrade, fetchConvertTradeHistory
//
// {
// "clTReqId": "",
// "instId": "ETH-USDT",
// "side": "buy",
// "fillPx": "2932.401044",
// "baseCcy": "ETH",
// "quoteCcy": "USDT",
// "fillBaseSz": "0.01023052",
// "state": "fullyFilled",
// "tradeId": "trader16461885203381437",
// "fillQuoteSz": "30",
// "ts": "1646188520000"
// }
//
let mut timestamp: Value = self.safe_integer2(conversion.clone(), Value::Str("quoteTime".into()), Value::Str("ts".into()), &[]);
let mut fromCoin: Value = self.safe_string_k(conversion.clone(), "baseCcy", &[]);
let mut fromCode: Value = self.safe_currency_code(fromCoin, &[fromCurrency]);
let mut to: Value = self.safe_string_k(conversion.clone(), "quoteCcy", &[]);
let mut toCode: Value = self.safe_currency_code(to, &[toCurrency]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), conversion.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("id".to_string(), self.safe_string_n(conversion.clone(), Value::from(vec![Value::Str("clQReqId".into()), Value::Str("tradeId".into()), Value::Str("quoteId".into())]), &[]));
m.insert("fromCurrency".to_string(), fromCode);
m.insert("fromAmount".to_string(), self.safe_number2(conversion.clone(), Value::Str("baseSz".into()), Value::Str("fillBaseSz".into()), &[]));
m.insert("toCurrency".to_string(), toCode);
m.insert("toAmount".to_string(), self.safe_number2(conversion.clone(), Value::Str("quoteSz".into()), Value::Str("fillQuoteSz".into()), &[]));
m.insert("price".to_string(), self.safe_number2(conversion, Value::Str("cnvtPx".into()), Value::Str("fillPx".into()), &[]));
m.insert("fee".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name okx#fetchConvertCurrencies
* @description fetches all available currencies that can be converted
* @see https://www.okx.com/docs-v5/en/#funding-account-rest-api-get-convert-currencies
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_convert_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.private_get_asset_convert_currencies(&[params]).await;
//
// {
// "code": "0",
// "data": [
// {
// "ccy": "BTC",
// "max": "",
// "min": ""
// },
// ],
// "msg": ""
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1009: bool = true;
while { if !__for_first_1009 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1009 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut entry: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut id: Value = self.safe_string_k(entry.clone(), "ccy", &[]);
let mut code: Value = self.safe_currency_code(id.clone(), &[]);
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("id".to_string(), id);
m.insert("code".to_string(), code.clone());
m.insert("networks".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("name".to_string(), Value::Null);
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), Value::Null);
m.insert("withdraw".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Null);
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(entry.clone(), "min", &[]));
m.insert("max".to_string(), self.safe_number_k(entry, "max", &[]));
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m
})); }
}
}
}
return result;
Value::Null
}
pub fn handle_errors(&self, mut httpCode: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) {
return Value::Null;
}
//
// {
// "code": "1",
// "data": [
// {
// "clOrdId": "",
// "ordId": "",
// "sCode": "51119",
// "sMsg": "Order placement failed due to insufficient balance. ",
// "tag": ""
// }
// ],
// "msg": ""
// },
// {
// "code": "58001",
// "data": [],
// "msg": "Incorrect trade password"
// }
//
let mut code: Value = self.safe_string_k(response.clone(), "code", &[]);
if (code.as_str() != Some("0")) && (code.as_str() != Some("2")) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1010: bool = true;
while { if !__for_first_1010 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1010 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut error: Value = self.safe_dict(data.clone(), i.clone(), &[]);
let mut errorCode: Value = self.safe_string_k(error.clone(), "sCode", &[]);
let mut message: Value = self.safe_string_k(error, "sMsg", &[]);
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorCode, feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message, feedback.clone());
}
}
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), code, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
/*
* @method
* @name okx#fetchMarginAdjustmentHistory
* @description fetches the history of margin added or reduced from contract isolated positions
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-7-days
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-bills-details-last-3-months
* @param {string} [symbol] not used by okx fetchMarginAdjustmentHistory
* @param {string} [type] "add" or "reduce"
* @param {int} [since] the earliest time in ms to fetch margin adjustment history for
* @param {int} [limit] the maximum number of entries to retrieve
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {boolean} [params.auto] true if fetching auto margin increases
* @returns {object[]} a list of [margin structures]{@link https://docs.ccxt.com/?id=margin-loan-structure}
*/
pub async fn fetch_margin_adjustment_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut type_var = get_arg(optional_args, 1, Value::Null);
let mut since = get_arg(optional_args, 2, Value::Null);
let mut limit = get_arg(optional_args, 3, Value::Null);
let mut params = get_arg(optional_args, 4, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut auto: Value = self.safe_bool_k(params.clone(), "auto", &[]);
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchMarginAdjustmentHistory () requires a type argument".into()))));
}
let mut isAdd: bool = type_var.as_str() == Some("add");
let mut subType: Value = (if isAdd { Value::Str("160".into()) } else { Value::Str("161".into()) });
if (auto.as_bool() == Some(true)) {
if isAdd {
subType = Value::Str("162".into());
} else {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" cannot fetch margin adjustments for type ".into())).into()), type_var)));
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("subType".to_string(), subType);
m.insert("mgnMode".to_string(), Value::Str("isolated".into()));
m
});
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("until".into()), &[]);
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
}
let mut response: Value = Value::Null;
let mut now: Value = self.milliseconds();
let mut oneWeekAgo: Value = (match (&(now), &(Value::Int(604800000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut threeMonthsAgo: Value = (match (&(now), &(Value::Int(7776000000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
if (since == Value::Null) || (since.as_f64().unwrap_or(f64::NAN) > oneWeekAgo.as_f64().unwrap_or(f64::NAN)) {
let __ws_arg_98 = self.extend(request.clone(), &[paramsOmitted.clone()]);
response = self.private_get_account_bills(&[__ws_arg_98]).await;
} else if since.as_f64().unwrap_or(f64::NAN) > threeMonthsAgo.as_f64().unwrap_or(f64::NAN) {
let __ws_arg_99 = self.extend(request, &[paramsOmitted]);
response = self.private_get_account_bills_archive(&[__ws_arg_99]).await;
} else {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchMarginAdjustmentHistory () cannot fetch margin adjustments older than 3 months".into()))));
}
//
// {
// code: '0',
// data: [
// {
// bal: '67621.4325135010619812',
// balChg: '-10.0000000000000000',
// billId: '691293628710342659',
// ccy: 'USDT',
// clOrdId: '',
// execType: '',
// fee: '0',
// fillFwdPx: '',
// fillIdxPx: '',
// fillMarkPx: '',
// fillMarkVol: '',
// fillPxUsd: '',
// fillPxVol: '',
// fillTime: '1711089244850',
// from: '',
// instId: 'XRP-USDT-SWAP',
// instType: 'SWAP',
// interest: '0',
// mgnMode: 'isolated',
// notes: '',
// ordId: '',
// pnl: '0',
// posBal: '73.12',
// posBalChg: '10.00',
// px: '',
// subType: '160',
// sz: '10',
// tag: '',
// to: '',
// tradeId: '0',
// ts: '1711089244699',
// type: '6'
// }
// ],
// msg: ''
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut modifications: Value = self.parse_margin_modifications(data, &[]);
return self.filter_by_symbol_since_limit(modifications, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name okx#fetchPositionsHistory
* @description fetches historical positions
* @see https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions-history
* @param {string} [symbols] unified market symbols
* @param {int} [since] timestamp in ms of the earliest position to fetch
* @param {int} [limit] the maximum amount of records to fetch, default=100, max=100
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] "cross" or "isolated"
*
* EXCHANGE SPECIFIC PARAMETERS
* @param {string} [params.instType] margin, swap, futures or option
* @param {string} [params.type] the type of latest close position 1: close position partially, 2:close all, 3:liquidation, 4:partial liquidation; 5:adl, is it is the latest type if there are several types for the same position
* @param {string} [params.posId] position id, there is attribute expiration, the posid will be expired if it is more than 30 days after the last full close position, then position will use new posid
* @param {string} [params.before] timestamp in ms of the earliest position to fetch based on the last update time of the position
* @param {string} [params.after] timestamp in ms of the latest position to fetch based on the last update time of the position
* @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut marginMode: Value = self.safe_string_k(params.clone(), "marginMode", &[]);
let mut instType: Value = self.safe_string_upper_k(params.clone(), "instType", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("until".into()), Value::Str("marginMode".into()), Value::Str("instType".into())]), &[]);
let mut limitResolved: Value = (if (limit == Value::Null) { Value::Int(100) } else { limit });
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), limitResolved.clone());
m
});
if (symbols != Value::Null) {
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
if (symbolsLength == 1.0) {
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
}
if (marginMode != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("mgnMode".into(), marginMode); }
}
if (instType != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instType".into(), instType); }
}
let __ws_arg_100 = self.extend(request, &[paramsOmitted.clone()]);
let mut response: Value = self.private_get_account_positions_history(&[__ws_arg_100]).await;
//
// {
// code: '0',
// data: [
// {
// cTime: '1708735940395',
// ccy: 'USDT',
// closeAvgPx: '0.6330444444444444',
// closeTotalPos: '27',
// direction: 'long',
// fee: '-1.69566',
// fundingFee: '-11.870404179341788',
// instId: 'XRP-USDT-SWAP',
// instType: 'SWAP',
// lever: '3.0',
// liqPenalty: '0',
// mgnMode: 'cross',
// openAvgPx: '0.623',
// openMaxPos: '15',
// pnl: '27.11999999999988',
// pnlRatio: '0.0241732402722634',
// posId: '681423155054862336',
// realizedPnl: '13.553935820658092',
// triggerPx: '',
// type: '2',
// uTime: '1711088748170',
// uly: 'XRP-USDT'
// },
// ...
// ],
// msg: ''
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut positions: Value = self.parse_positions(data, &[symbols, paramsOmitted]);
return self.filter_by_since_limit(positions, &[since, limitResolved]);
Value::Null
}
/*
* @method
* @name okx#fetchLongShortRatioHistory
* @description fetches the long short ratio history for a unified market symbol
* @see https://www.okx.com/docs-v5/en/#trading-statistics-rest-api-get-contract-long-short-ratio
* @param {string} symbol unified symbol of the market to fetch the long short ratio for
* @param {string} [timeframe] the period for the ratio
* @param {int} [since] the earliest time in ms to fetch ratios for
* @param {int} [limit] the maximum number of long short ratio structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest ratio to fetch
* @returns {object[]} an array of [long short ratio structures]{@link https://docs.ccxt.com/?id=long-short-ratio-structure}
*/
pub async fn fetch_long_short_ratio_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut timeframe = get_arg(optional_args, 1, Value::Null);
let mut since = get_arg(optional_args, 2, Value::Null);
let mut limit = get_arg(optional_args, 3, Value::Null);
let mut params = get_arg(optional_args, 4, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchLongShortRatioHistory() requires a symbol argument".into()))));
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut period: Value = Value::Str("5m".into()); // the default period of the endpoint
if (timeframe != Value::Null) {
period = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("period".into(), period.clone()); }
}
let mut requestWindowparamsWindowVariable = self.handle_trading_statistics_window(request, period, &[since.clone(), limit.clone(), params]);
let mut requestWindow: Value = requestWindowparamsWindowVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWindow: Value = requestWindowparamsWindowVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
let __ws_arg_101 = self.extend(requestWindow, &[paramsWindow]);
let mut response: Value = self.public_get_rubik_stat_contracts_long_short_account_ratio_contract(&[__ws_arg_101]).await;
//
// {
// "code": "0",
// "data": [
// ["1729323600000", "0.9398602814619824"],
// ["1729323300000", "0.9398602814619824"],
// ["1729323000000", "0.9398602814619824"],
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1011: bool = true;
while { if !__for_first_1011 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_1011 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut entry: Value = self.safe_list(data.clone(), i.clone(), &[]);
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timestamp".to_string(), self.safe_string(entry.clone(), Value::Int(0), &[]));
m.insert("longShortRatio".to_string(), self.safe_string(entry, Value::Int(1), &[]));
m
}));
}
}
return self.parse_long_short_ratio_history(result, &[market, since, limit]);
Value::Null
}
pub fn parse_long_short_ratio(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Value = self.safe_integer_k(info.clone(), "timestamp", &[]);
let mut symbol: Value = Value::Null;
if (market != Value::Null) {
symbol = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info.clone());
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("timeframe".to_string(), Value::Null);
m.insert("longShortRatio".to_string(), self.safe_number_k(info, "longShortRatio", &[]));
m
});
Value::Null
}
}