#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
use crate::exchange::CallDynamicChecked;
pub struct KrakenfuturesCore {
pub exchange: crate::exchange::Exchange,
}
impl KrakenfuturesCore {
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 = KrakenfuturesCore::describe(self);
self.initialize_properties(described);
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for KrakenfuturesCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_order(self, order, &[market])
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_funding_rate(self, rate, &[market])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_transfer(self, transfer, &[currency])
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_income(self, info, &[market])
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_leverage(self, leverage, &[market])
}
fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
KrakenfuturesCore::parse_market_leverage_tiers(self, info, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
KrakenfuturesCore::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 {
KrakenfuturesCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for KrakenfuturesCore {
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 {
"cancel_all_orders" => self.cancel_all_orders(&args[..]).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,
"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,
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args[..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args[..]).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_leverage_tiers" => self.fetch_leverage_tiers(&args[..]).await,
"fetch_leverages" => self.fetch_leverages(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).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_orders" => self.fetch_open_orders(&args[..]).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_orders" => self.fetch_orders(&args[..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_positions_history" => self.fetch_positions_history(&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_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trading_fees" => self.fetch_trading_fees(&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)),
"parse_balance" => self.parse_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_income" => self.parse_income(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_kraken_account_name" => self.parse_kraken_account_name(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_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_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"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_fee" => self.parse_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"set_leverage" => self.set_leverage(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,
"transfer_out" => self.transfer_out(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for KrakenfuturesCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for KrakenfuturesCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl KrakenfuturesCore {
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("krakenfutures".into()));
m.insert("name".to_string(), Value::Str("Kraken Futures".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
m.insert("version".to_string(), Value::Str("v3".into()));
m.insert("userAgent".to_string(), Value::Null);
m.insert("rateLimit".to_string(), Value::Int(600));
m.insert("pro".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(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(true));
m.insert("option".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
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("createMarketOrder".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".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("createStopMarketOrder".to_string(), Value::Bool(true));
m.insert("createStopOrder".to_string(), Value::Bool(true));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchDepositAddress".to_string(), Value::Bool(false));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(false));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRate".to_string(), Value::Str("emulated".into()));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".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("fetchIsolatedPositions".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLeverage".to_string(), Value::Bool(true));
m.insert("fetchLeverages".to_string(), Value::Bool(true));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(true));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Str("emulated".into()));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsHistory".to_string(), Value::Bool(true));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Str("emulated".into()));
m.insert("fetchTradingFees".to_string(), Value::Bool(true));
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMarginMode".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(true));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://demo-futures.kraken.com/derivatives/api/".into()));
m.insert("private".to_string(), Value::Str("https://demo-futures.kraken.com/derivatives/api/".into()));
m.insert("charts".to_string(), Value::Str("https://demo-futures.kraken.com/api/charts/".into()));
m.insert("history".to_string(), Value::Str("https://demo-futures.kraken.com/api/history/".into()));
m.insert("www".to_string(), Value::Str("https://demo-futures.kraken.com".into()));
m
}));
m.insert("logo".to_string(), Value::Str("https://user-images.githubusercontent.com/24300605/81436764-b22fd580-9172-11ea-9703-742783e6376d.jpg".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("charts".to_string(), Value::Str("https://futures.kraken.com/api/charts/".into()));
m.insert("history".to_string(), Value::Str("https://futures.kraken.com/api/history/".into()));
m.insert("feeschedules".to_string(), Value::Str("https://futures.kraken.com/api/feeschedules/".into()));
m.insert("public".to_string(), Value::Str("https://futures.kraken.com/derivatives/api/".into()));
m.insert("private".to_string(), Value::Str("https://futures.kraken.com/derivatives/api/".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://futures.kraken.com/".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.kraken.com/exchange/guides/futures/rest".into())]));
m.insert("fees".to_string(), Value::Str("https://support.kraken.com/hc/en-us/articles/360022835771-Transaction-fees-and-rebates-for-Kraken-Futures".into()));
m.insert("referral".to_string(), Value::Null);
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("feeschedules".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("instruments/status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("instruments/{symbol}/status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tickers/{symbol}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("historicalfundingrates".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("feeschedules/volumes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("openpositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("notifications".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("openorders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("transfers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("leveragepreferences".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("pnlpreferences".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("assignmentprogram/current".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("assignmentprogram/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orders/status".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("unwindqueue".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("self-trade-strategy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("subaccounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("subaccount/{uid}/trading-enabled".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq-assignment/max-leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sendorder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("editorder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("cancelorder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("transfer/subaccount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("batchorder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("cancelallorders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("cancelallordersafter".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("withdrawal".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("assignmentprogram/add".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("assignmentprogram/delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("put".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leveragepreferences".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("pnlpreferences".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("self-trade-strategy".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("subaccount/{uid}/trading-enabled".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq-assignment/max-leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rfq-assignment/max-leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("charts".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("{price_type}/{symbol}/{interval}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("analytics/liquidity-pool".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("history".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("orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("executions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("triggers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountlogcsv".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account-log".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/{symbol}/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/{symbol}/executions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/{symbol}/price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
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("tierBased".to_string(), Value::Bool(true));
m.insert("percentage".to_string(), Value::Bool(true));
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.insert("tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.0005".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000".into()), &[]), self.parse_number(Value::Str("0.0004".into()), &[])]),
Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.0003".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.00025".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]),
self.parse_number(Value::Str("0.0002".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("20000000".into()), &[]), self.parse_number(Value::Str("0.00015".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.000125".into()), &[])]),
Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0.0001".into()), &[])])]));
m.insert("maker".to_string(), Value::from(vec![Value::from(vec![self.parse_number(Value::Str("0".into()), &[]), self.parse_number(Value::Str("0.0002".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000".into()), &[]), self.parse_number(Value::Str("0.0015".into()), &[])]),
Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.000125".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.0001".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]),
self.parse_number(Value::Str("0.000075".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("20000000".into()), &[]), self.parse_number(Value::Str("0.00005".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000000".into()), &[]), self.parse_number(Value::Str("0.000025".into()), &[])]),
Value::from(vec![self.parse_number(Value::Str("100000000".into()), &[]), self.parse_number(Value::Str("0".into()), &[])])]));
m
}));
m
}));
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("apiLimitExceeded".to_string(), Value::Str("RateLimitExceeded".into()));
m.insert("marketUnavailable".to_string(), Value::Str("ContractUnavailable".into()));
m.insert("requiredArgumentMissing".to_string(), Value::Str("BadRequest".into()));
m.insert("unavailable".to_string(), Value::Str("ExchangeNotAvailable".into()));
m.insert("authenticationError".to_string(), Value::Str("AuthenticationError".into()));
m.insert("accountInactive".to_string(), Value::Str("ExchangeError".into()));
m.insert("invalidAccount".to_string(), Value::Str("BadRequest".into()));
m.insert("invalidAmount".to_string(), Value::Str("BadRequest".into()));
m.insert("insufficientFunds".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("INSUFFICIENT_MARGIN".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("Bad Request".to_string(), Value::Str("BadRequest".into()));
m.insert("Unavailable".to_string(), Value::Str("ExchangeNotAvailable".into()));
m.insert("invalidUnit".to_string(), Value::Str("BadRequest".into()));
m.insert("Json Parse Error".to_string(), Value::Str("ExchangeError".into()));
m.insert("nonceBelowThreshold".to_string(), Value::Str("InvalidNonce".into()));
m.insert("nonceDuplicate".to_string(), Value::Str("InvalidNonce".into()));
m.insert("notFound".to_string(), Value::Str("BadRequest".into()));
m.insert("Server Error".to_string(), Value::Str("ExchangeError".into()));
m.insert("unknownError".to_string(), Value::Str("ExchangeError".into()));
m.insert("contractNotFound".to_string(), Value::Str("BadSymbol".into()));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("invalidArgument".to_string(), Value::Str("BadRequest".into()));
m.insert("nonceBelowThreshold".to_string(), Value::Str("InvalidNonce".into()));
m.insert("nonceDuplicate".to_string(), Value::Str("InvalidNonce".into()));
m
}));
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("access".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("history".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("orders".to_string(), Value::Str("private".into()));
m.insert("executions".to_string(), Value::Str("private".into()));
m.insert("triggers".to_string(), Value::Str("private".into()));
m.insert("accountlogcsv".to_string(), Value::Str("private".into()));
m.insert("account-log".to_string(), Value::Str("private".into()));
m.insert("positions".to_string(), Value::Str("private".into()));
m
}));
m
}));
m
}));
m.insert("settlementCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("flex".to_string(), Value::from(vec![Value::Str("USDT".into()), Value::Str("BTC".into()), Value::Str("USD".into()), Value::Str("GBP".into()), Value::Str("EUR".into()), Value::Str("USDC".into())]));
m
}));
m.insert("symbol".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("quoteIds".to_string(), Value::from(vec![Value::Str("USD".into()), Value::Str("XBT".into())]));
m.insert("reversed".to_string(), Value::Bool(false));
m
}));
m.insert("versions".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("historicalfundingrates".to_string(), Value::Str("v4".into()));
m
}));
m
}));
m.insert("charts".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("{price_type}/{symbol}/{interval}".to_string(), Value::Str("v1".into()));
m.insert("analytics/liquidity-pool".to_string(), Value::Str("v1".into()));
m
}));
m
}));
m.insert("history".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("orders".to_string(), Value::Str("v2".into()));
m.insert("executions".to_string(), Value::Str("v2".into()));
m.insert("triggers".to_string(), Value::Str("v2".into()));
m.insert("accountlogcsv".to_string(), Value::Str("v2".into()));
m
}));
m
}));
m
}));
m.insert("fetchTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("historyGetMarketSymbolExecutions".into()));
m
}));
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(false));
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::Null);
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(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("iceberg".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(100));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Null);
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Int(100000));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Null);
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::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
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::Null);
m.insert("daysBack".to_string(), Value::Null);
m.insert("daysBackCanceled".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
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(2000));
m
}));
m
}));
m.insert("spot".to_string(), Value::Null);
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("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".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("4h".to_string(), Value::Str("4h".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
}));
m
})]);
Value::Null
}
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
}));
let mut response: Value = self.public_get_instruments(&[params]).await;
let mut instruments: Vec<Value> = self.safe_list_k(response, "instruments", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_867: bool = true;
while { if !__for_first_867 { i += 1; } __for_first_867 = false; i < (instruments.len() as i64) } {
let mut market: Value = instruments.get(i as usize).cloned().unwrap_or(Value::Null);
let mut id: Option<String> = self.safe_string_k_opt(market.clone(), "symbol", &[]);
let mut marketType: Option<String> = self.safe_string_k_opt(market.clone(), "type", &[]);
let mut type_var: Value = Value::Null;
let mut index: Value = (Value::Bool(marketType.as_deref().unwrap_or("").contains(" index")));
let mut linear: Value = Value::Null;
let mut inverse: Value = Value::Null;
let mut expiry: Value = Value::Null;
if !(matches!(&index, Value::Bool(true))) {
linear = (Value::Bool(marketType.as_deref().unwrap_or("").contains("_vanilla")));
inverse = Value::Bool(!(linear.as_bool() == Some(true)));
let mut settleTime: Option<String> = self.safe_string_k_opt(market.clone(), "lastTradingTime", &[]);
type_var = (if (settleTime.is_none()) { Value::Str("swap".into()) } else { Value::Str("future".into()) });
expiry = self.parse8601(settleTime.map(Value::from).unwrap_or(Value::Null));
} else {
type_var = Value::Str("index".into());
}
let mut swap: Value = (Value::Bool(type_var.as_str() == Some("swap")));
let mut future: Value = (Value::Bool(type_var.as_str() == Some("future")));
let mut symbol: Value = id.clone().map(Value::from).unwrap_or(Value::Null);
let mut split: Value = Value::Array(if let Some(__s) = id.as_deref() { __s.split("_").map(Value::from).collect() } else { Vec::new() });
let mut splitMarket: Value = self.safe_string(split, Value::Int(1), &[Value::Str("".into())]);
let mut baseId: Value = (match (&(splitMarket), 0i64, (match &((match (&(Value::Int(splitMarket.len() as i64)), &(Value::Int(3))) { (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(__n) => Some(*__n), Value::Float(__f) => Some(*__f as i64), Value::Str(__s) => __s.parse::<i64>().ok(), Value::Bool(__b) => Some(if *__b { 1 } else { 0 }), _ => None })) { (Value::Str(__sv), __b,
__e) => match (__sv.chars().count() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l, Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i,
__j) => if __i <= __j { Value::Str(__sv.chars().skip(__i as usize).take((__j - __i) as usize).collect::<String>().into()) } else { Value::Str(String::new().into()) } } }, (Value::Arr(__a), __b, __e) => match (__a.len() as i64) { __l => match (if __b < 0 { (__l + __b).max(0) } else { __b.min(__l) }, match __e { None => __l,
Some(__k) => if __k < 0 { (__l + __k).max(0) } else { __k.min(__l) } }) { (__i, __j) => if __i <= __j { Value::Array(__a[__i as usize..__j as usize].to_vec()) } else { Value::Array(vec![]) } } }, _ => Value::Null });
let mut quoteId: String = "usd".to_string(); let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(Value::from(quoteId.clone()), &[]);
if (base == Value::Null) || (quote == Value::Null) {
continue;
}
let mut settle: Value = Value::Null;
let mut settleId: Value = Value::Null;
let mut cvtp: Option<String> = self.safe_string_k_opt(market.clone(), "contractValueTradePrecision", &[]);
let mut amountPrecision: Value = self.parse_number(self.integer_precision_to_amount(cvtp.map(Value::from).unwrap_or(Value::Null)), &[]);
let mut pricePrecision: Value = self.safe_number_k(market.clone(), "tickSize", &[]);
let mut contract: Value = Value::Bool(matches!(&swap, Value::Bool(true)) || matches!(&future, Value::Bool(true)) || matches!(&index, Value::Bool(true)));
let mut swapOrFutures: bool = matches!(&swap, Value::Bool(true)) || matches!(&future, Value::Bool(true));
if swapOrFutures {
let mut exchangeType: Option<String> = self.safe_string_k(market.clone(), "type", &[]).as_str().map(str::to_owned);
if (exchangeType.as_deref() == Some("futures_inverse")) {
settle = base.clone();
settleId = baseId.clone();
inverse = Value::Bool(true);
} else {
settle = quote.clone();
settleId = Value::from(quoteId.clone());
inverse = Value::Bool(false);
}
linear = Value::Bool(!(inverse.as_bool() == Some(true)));
symbol = 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());
if matches!(&future, Value::Bool(true)) {
symbol = 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()), self.yymmdd(expiry.clone(), &[])).into());
}
}
result.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
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(), Value::from(quoteId));
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), type_var);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), swap);
m.insert("future".to_string(), future);
m.insert("option".to_string(), Value::Bool(false));
m.insert("index".to_string(), index);
m.insert("active".to_string(), self.safe_bool_k(market.clone(), "tradeable", &[]));
m.insert("contract".to_string(), contract);
m.insert("linear".to_string(), linear);
m.insert("inverse".to_string(), inverse);
m.insert("contractSize".to_string(), self.safe_number_k(market.clone(), "contractSize", &[]));
m.insert("taker".to_string(), self.safe_number(self.fees.as_map().and_then(|__m| __m.get("trading")).cloned().unwrap_or(Value::Null), Value::Str("taker".into()), &[]));
m.insert("maker".to_string(), self.safe_number(self.fees.as_map().and_then(|__m| __m.get("trading")).cloned().unwrap_or(Value::Null), Value::Str("maker".into()), &[]));
m.insert("maintenanceMarginRate".to_string(), Value::Null);
m.insert("expiry".to_string(), expiry.clone());
m.insert("expiryDatetime".to_string(), self.iso8601(expiry));
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), amountPrecision);
m.insert("price".to_string(), pricePrecision);
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(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
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("created".to_string(), self.parse8601(self.safe_string_k(market.clone(), "openingDate", &[])));
m.insert("info".to_string(), market);
m
}));
}
}
let mut settlementCurrencies: Value = self.safe_list(self.safe_dict_k(self.options.clone(), "settlementCurrencies", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("flex".into()), &[Value::from(vec![])]);
let mut currencies: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_868: bool = true;
while { if !__for_first_868 { i += 1; } __for_first_868 = false; i < (settlementCurrencies.len() as i64) } {
let mut code: Value = self.safe_string(settlementCurrencies.clone(), Value::Int(i), &[Value::Str("".into())]);
if let Value::Arr(__a) = &mut currencies { std::sync::Arc::make_mut(__a).push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), (if let Some(__s) = code.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null }));
m.insert("numericId".to_string(), Value::Null);
m.insert("code".to_string(), code);
m.insert("precision".to_string(), Value::Null);
m
})); }
}
}
{ let __t = self.map_to_safe_map(self.deep_extend(currencies.clone(), &[self.currencies.clone()])); self.currencies = __t; }
return Value::from(result);
Value::Null
}
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: indexmap::IndexMap<String, Value> = self.market(symbol.clone()).as_map().cloned().unwrap_or_default();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.get("id").cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_0 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_get_orderbook(&[__ws_arg_0]).await;
let mut timestamp: Value = self.parse8601(self.safe_string_k(response.clone(), "serverTime", &[]));
let mut orderBook: Value = self.safe_dict_k(response, "orderBook", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order_book(orderBook, symbol, &[timestamp]);
Value::Null
}
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
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_1 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_get_tickers_symbol(&[__ws_arg_1]).await;
let mut ticker: Value = self.safe_dict_k(response, "ticker", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(ticker, &[market]);
Value::Null
}
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 response: Value = self.public_get_tickers(&[params]).await;
let mut tickers: Value = self.safe_list_k(response, "tickers", &[]);
return self.parse_tickers(tickers, &[symbols]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string_k_opt(ticker.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut symbol: Option<String> = self.safe_string_k_opt(marketResolved.clone(), "symbol", &[]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(ticker.clone(), "lastTime", &[]));
let mut open: Option<String> = self.safe_string_k_opt(ticker.clone(), "open24h", &[]);
let mut last: Option<String> = self.safe_string_k_opt(ticker.clone(), "last", &[]);
let mut change: Value = crate::precise::Precise::stringSub(&last.clone().map(Value::from).unwrap_or(Value::Null), &open.clone().map(Value::from).unwrap_or(Value::Null));
let mut percentage: Value = crate::precise::Precise::stringMul(&crate::precise::Precise::stringDiv(&change, &open.clone().map(Value::from).unwrap_or(Value::Null)), &Value::Str("100".into()));
let mut average: Value = crate::precise::Precise::stringDiv(&crate::precise::Precise::stringAdd(&open.clone().map(Value::from).unwrap_or(Value::Null), &last.clone().map(Value::from).unwrap_or(Value::Null)), &Value::Str("2".into()));
let mut volume: Option<String> = self.safe_string_k_opt(ticker.clone(), "vol24h", &[]);
let mut quoteVolume: Option<String> = self.safe_string_k_opt(ticker.clone(), "volumeQuote", &[]);
let mut vwap: Option<String> = self.safe_string_k_opt(ticker.clone(), "vwap24h", &[]);
let mut baseVolume: Value = Value::Null;
let mut isIndex: bool = self.safe_bool_k_opt(marketResolved.clone(), "index", &[Value::Bool(false)]).unwrap_or(false);
if !(isIndex) {
if matches!(self.safe_bool_k(marketResolved.clone(), "linear", &[Value::Bool(false)]), Value::Bool(true)) {
baseVolume = volume.map(Value::from).unwrap_or(Value::Null);
} else if matches!(self.safe_bool_k(marketResolved, "inverse", &[Value::Bool(false)]), Value::Bool(true)) {
baseVolume = crate::precise::Precise::stringDiv("eVolume.clone().map(Value::from).unwrap_or(Value::Null), &vwap.clone().map(Value::from).unwrap_or(Value::Null));
}
}
let mut high: Option<String> = self.safe_string_k_opt(ticker.clone(), "high24h", &[]);
let mut low: Option<String> = self.safe_string_k_opt(ticker.clone(), "low24h", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.map(Value::from).unwrap_or(Value::Null));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), high.map(Value::from).unwrap_or(Value::Null));
m.insert("low".to_string(), low.map(Value::from).unwrap_or(Value::Null));
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "bid", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(ticker.clone(), "bidSize", &[]));
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "ask", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(ticker.clone(), "askSize", &[]));
m.insert("vwap".to_string(), vwap.map(Value::from).unwrap_or(Value::Null));
m.insert("open".to_string(), open.map(Value::from).unwrap_or(Value::Null));
m.insert("close".to_string(), last.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("last".to_string(), last.map(Value::from).unwrap_or(Value::Null));
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), change);
m.insert("percentage".to_string(), percentage);
m.insert("average".to_string(), average);
m.insert("baseVolume".to_string(), baseVolume);
m.insert("quoteVolume".to_string(), quoteVolume.map(Value::from).unwrap_or(Value::Null));
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "markPrice", &[]));
m.insert("indexPrice".to_string(), self.safe_string_k(ticker.clone(), "indexPrice", &[]));
m.insert("info".to_string(), ticker);
m
}), &[]);
Value::Null
}
pub async fn fetch_trading_fees(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut response: Value = self.public_get_feeschedules(&[params]).await;
let mut volumes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if self.check_required_credentials(&[Value::Bool(false)]).as_bool() == Some(true) {
let mut volumesResponse: Value = self.private_get_feeschedules_volumes(&[]).await;
volumes = self.safe_dict_k(volumesResponse, "volumesByFeeSchedule", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).as_map().cloned().unwrap_or_default();
}
let mut feeSchedules: Vec<Value> = self.safe_list_k(response, "feeSchedules", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut schedulesByUid: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: i64 = 0;
let mut __for_first_869: bool = true;
while { if !__for_first_869 { i += 1; } __for_first_869 = false; i < (feeSchedules.len() as i64) } {
let mut schedule: Value = feeSchedules.get(i as usize).cloned().unwrap_or(Value::Null);
let mut uid: Option<String> = self.safe_string_k_opt(schedule.clone(), "uid", &[]);
if (uid.is_some()) {
schedulesByUid.insert(uid.as_deref().unwrap_or("null").to_string(), schedule.clone());
}
}
}
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut symbols: Value = self.symbols.clone();
{
let mut i: i64 = 0;
let mut __for_first_870: bool = true;
while { if !__for_first_870 { i += 1; } __for_first_870 = false; i < (symbols.len() as i64) } {
let mut symbol: Value = symbols.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol.clone());
let mut uid: Option<String> = self.safe_string_opt(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("feeScheduleUid".into()), &[]);
let mut schedule: Value = self.safe_dict(Value::Map(schedulesByUid.clone()), uid.clone().map(Value::from).unwrap_or(Value::Null), &[]);
if (schedule == Value::Null) {
continue;
}
let mut volume: Value = self.safe_string(Value::Map(volumes.clone()), uid.map(Value::from).unwrap_or(Value::Null), &[Value::Str("0".into())]);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), self.parse_trading_fee(schedule, &[market, volume])); }
}
}
return 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);
let mut volume = get_arg(optional_args, 1, Value::Null);
let mut tiers: Value = self.safe_list_k(fee.clone(), "tiers", &[Value::from(vec![])]);
let mut makerFee: Value = Value::Null;
let mut takerFee: Value = Value::Null;
{
let mut i: i64 = 0;
let mut __for_first_871: bool = true;
while { if !__for_first_871 { i += 1; } __for_first_871 = false; i < (tiers.len() as i64) } {
let mut tier: Value = self.safe_dict(tiers.clone(), Value::Int(i), &[]);
let mut tierVolume: Option<String> = self.safe_string_k_opt(tier.clone(), "usdVolume", &[]);
if (volume == Value::Null) || crate::precise::Precise::stringGe(&volume, &tierVolume.clone().map(Value::from).unwrap_or(Value::Null)).as_bool() == Some(true) {
makerFee = self.safe_string_k(tier.clone(), "makerFee", &[]);
takerFee = self.safe_string_k(tier, "takerFee", &[]);
if (volume == Value::Null) {
break;
}
}
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee);
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market]));
m.insert("maker".to_string(), self.parse_number(crate::precise::Precise::stringDiv(&makerFee, &Value::Str("100".into())), &[]));
m.insert("taker".to_string(), self.parse_number(crate::precise::Precise::stringDiv(&takerFee, &Value::Str("100".into())), &[]));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(true));
m
});
Value::Null
}
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 paginateparamsPaginateVariable: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("fetchOHLCV".into()), Value::Str("paginate".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default();
let mut paginate: Value = paginateparamsPaginateVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.get(1).cloned().unwrap_or(Value::Null);
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".into()), &[symbol, since.clone(), limit.clone(), timeframe.clone(), paramsPaginate.clone(), Value::Int(2000)]).await;
}
let mut priceType: Value = self.safe_string_k(paramsPaginate.clone(), "price", &[Value::Str("trade".into())]);
if (priceType.as_str() == Some("index")) {
priceType = Value::Str("spot".into()); } else if (priceType.as_str() != Some("trade")) && (priceType.as_str() != Some("mark")) && (priceType.as_str() != Some("spot")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() price parameter must be one of \"trade\", \"mark\", \"index\" or \"spot\"".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("price_type".to_string(), priceType);
m.insert("interval".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m
});
let mut paramsOmitted: Value = self.omit(paramsPaginate, Value::Str("price".into()), &[]);
let mut windowLimit: Value = (if ((limit == Value::Null) || (limit.as_f64().unwrap_or(f64::NAN) > ((2000i64) as f64))) { Value::Int(2000) } else { limit.clone() });
let mut windowSize: Value = self.parse_to_int(windowLimit);
let mut limitResolved: Value = Value::Null;
if (since != Value::Null) || (limit != Value::Null) {
limitResolved = windowSize.clone();
}
if (since != Value::Null) {
let mut duration: Value = self.parse_timeframe(timeframe.clone());
let mut fromTimestamp: Value = self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
request.insert("from".into(), fromTimestamp.clone());
let mut toTimestamp: Value = self.parse_to_int(self.sum(&[fromTimestamp, (match (&((match (&(windowSize), &(duration)) { (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(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 currentTimestamp: Value = self.seconds();
request.insert("to".into(), (if (toTimestamp.as_f64().unwrap_or(f64::NAN) < currentTimestamp.as_f64().unwrap_or(f64::NAN)) { toTimestamp.clone() } else { currentTimestamp }));
} else if (limitResolved != Value::Null) {
let mut duration: Value = self.parse_timeframe(timeframe.clone());
let mut toTimestamp: Value = self.seconds();
request.insert("to".into(), toTimestamp.clone());
request.insert("from".into(), self.parse_to_int((match (&(toTimestamp), &(((match (&(duration), &(windowSize)) { (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 })));
}
let __ws_arg_2 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.charts_get_price_type_symbol_interval(&[__ws_arg_2]).await;
let mut candles: Value = self.safe_list_k(response, "candles", &[]);
return self.parse_ohlc_vs(candles, &[market, timeframe, since, limitResolved]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_integer_k(ohlcv.clone(), "time", &[]), self.safe_number_k(ohlcv.clone(), "open", &[]), self.safe_number_k(ohlcv.clone(), "high", &[]), self.safe_number_k(ohlcv.clone(), "low", &[]), self.safe_number_k(ohlcv.clone(), "close", &[]), self.safe_number_k(ohlcv, "volume", &[])]);
Value::Null
}
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 paginateparamsPaginateVariable: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("fetchTrades".into()), Value::Str("paginate".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default();
let mut paginate: Value = paginateparamsPaginateVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.get(1).cloned().unwrap_or(Value::Null);
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone()]).await;
}
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let methodparamsMethodVariable: Vec<Value> = self.handle_option_string_and_params(paramsPaginate, Value::Str("fetchTrades".into()), Value::Str("method".into()), &[Value::Str("historyGetMarketSymbolExecutions".into())]).as_array().cloned().unwrap_or_default();
let mut method: Value = methodparamsMethodVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsMethod: Value = methodparamsMethodVariable.get(1).cloned().unwrap_or(Value::Null);
let mut rawTrades: Value = Value::from(vec![]);
let mut isFullHistoryEndpoint: bool = method.as_str() == Some("historyGetMarketSymbolExecutions");
if isFullHistoryEndpoint {
if (since != Value::Null) {
request.insert("since".into(), since.clone());
request.insert("sort".into(), Value::Str("asc".into()));
}
if (limit != Value::Null) {
request.insert("count".into(), limit.clone());
}
let requestUntilparamsUntilVariable: Vec<Value> = self.handle_until_option(Value::Str("before".into()), Value::Map(request.clone()), paramsMethod.clone(), &[]).as_array().cloned().unwrap_or_default();
let mut requestUntil: Value = requestUntilparamsUntilVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.get(1).cloned().unwrap_or(Value::Null);
let __ws_arg_3 = self.extend(requestUntil.clone(), &[paramsUntil.clone()]);
let mut response: Value = self.history_get_market_symbol_executions(&[__ws_arg_3]).await;
let mut elements: Value = self.safe_list_k(response.clone(), "elements", &[Value::from(vec![])]);
rawTrades = Value::from(vec![]);
let mut length: Value = Value::Int(elements.len() as i64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_872: bool = true;
while { if !__for_first_872 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_872 = false; i.as_f64().unwrap_or(f64::NAN) < length.as_f64().unwrap_or(f64::NAN) } {
let mut index: Value = (match (&((match (&(length), &(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 })),
&(i)) { (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 element: Value = self.safe_dict(elements.clone(), index, &[]);
let mut event: Value = self.safe_dict_k(element, "event", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut executionContainer: Value = self.safe_dict_k(event, "Execution", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawTrade: Value = self.safe_dict_k(executionContainer, "execution", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Arr(__a) = &mut rawTrades { std::sync::Arc::make_mut(__a).push(rawTrade); }
}
}
} else {
let requestUntilparamsUntilVariable: Vec<Value> = self.handle_until_option(Value::Str("lastTime".into()), Value::Map(request), paramsMethod, &[]).as_array().cloned().unwrap_or_default();
let mut requestUntil: Value = requestUntilparamsUntilVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = requestUntilparamsUntilVariable.get(1).cloned().unwrap_or(Value::Null);
let __ws_arg_4 = self.extend(requestUntil, &[paramsUntil]);
let mut response: Value = self.public_get_history(&[__ws_arg_4]).await;
rawTrades = self.safe_list_k(response, "history", &[Value::from(vec![])]);
}
return self.parse_trades(rawTrades, &[market, since, limit]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Value = self.parse8601(self.safe_string2(trade.clone(), Value::Str("time".into()), Value::Str("fillTime".into()), &[]));
let mut price: Option<String> = self.safe_string_k_opt(trade.clone(), "price", &[]);
let mut amount: Value = self.safe_string_n(trade.clone(), Value::from(vec![Value::Str("size".into()), Value::Str("amount".into()), Value::Str("quantity".into())]), &[Value::Str("0.0".into())]);
let mut id: Value = self.safe_string2(trade.clone(), Value::Str("uid".into()), Value::Str("fill_id".into()), &[]);
if (id == Value::Null) {
id = self.safe_string_k(trade.clone(), "executionId", &[]);
}
let mut order: Option<String> = self.safe_string_k_opt(trade.clone(), "order_id", &[]);
let mut marketId: Option<String> = self.safe_string_k_opt(trade.clone(), "symbol", &[]);
let mut side: Option<String> = self.safe_string_k_opt(trade.clone(), "side", &[]);
let mut rawType: Value = Value::Null;
let mut priorEdit: Value = self.safe_dict_k(trade.clone(), "orderPriorEdit", &[]);
let mut priorExecution: Value = self.safe_dict_k(trade.clone(), "orderPriorExecution", &[]);
if (priorExecution != Value::Null) {
order = self.safe_string_k_opt(priorExecution.clone(), "orderId", &[]);
marketId = self.safe_string_k_opt(priorExecution.clone(), "symbol", &[]);
side = self.safe_string_k_opt(priorExecution.clone(), "side", &[]);
rawType = self.safe_string_k(priorExecution, "type", &[]);
} else if (priorEdit != Value::Null) {
order = self.safe_string_k_opt(priorEdit.clone(), "orderId", &[]);
marketId = self.safe_string_k_opt(priorEdit.clone(), "symbol", &[]);
side = self.safe_string_k_opt(priorEdit.clone(), "type", &[]);
rawType = self.safe_string_k(priorEdit, "type", &[]);
}
let mut type_var: Value = self.parse_order_type(rawType).map(Value::from).unwrap_or(Value::Null); let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut cost: Value = Value::Null;
let mut linear: bool = self.safe_bool_k_opt(marketResolved.clone(), "linear", &[Value::Bool(false)]).unwrap_or(false);
if (amount != Value::Null) && (price.is_some()) && (marketResolved != Value::Null) {
if linear {
cost = crate::precise::Precise::stringMul(&amount, &price.clone().map(Value::from).unwrap_or(Value::Null)); } else {
cost = crate::precise::Precise::stringDiv(&amount, &price.clone().map(Value::from).unwrap_or(Value::Null)); }
let mut contractSize: Option<String> = self.safe_string_k_opt(marketResolved.clone(), "contractSize", &[]);
cost = crate::precise::Precise::stringMul(&cost, &contractSize.clone().map(Value::from).unwrap_or(Value::Null));
}
let mut takerOrMaker: Value = Value::Null;
let mut fillType: Option<String> = self.safe_string_k_opt(trade.clone(), "fillType", &[]);
if (fillType.is_some()) {
if fillType.as_deref().unwrap_or("").contains("taker") {
takerOrMaker = Value::Str("taker".into());
} else if fillType.as_deref().unwrap_or("").contains("maker") {
takerOrMaker = Value::Str("maker".into());
}
}
let mut isHistoricalExecution: bool = matches!(&trade, Value::Dict(__d) if __d.contains_key("takerOrder"));
if isHistoricalExecution {
timestamp = self.safe_integer_k(trade.clone(), "timestamp", &[]);
let mut taker: Value = self.safe_dict_k(trade.clone(), "takerOrder", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (taker != Value::Null) {
side = self.safe_string_lower_k_opt(taker, "direction", &[]);
takerOrMaker = Value::Str("taker".into());
}
}
let mut fee: Value = Value::Null;
if (takerOrMaker != Value::Null) && (cost != Value::Null) {
let mut feeRate: Option<String> = self.safe_string_opt(marketResolved.clone(), takerOrMaker.clone(), &[]);
let mut feeCurrency: Option<String> = self.safe_string_k_opt(marketResolved.clone(), "settle", &[]);
if (feeCurrency.is_none()) {
feeCurrency = self.safe_string_k_opt(marketResolved.clone(), "quote", &[]);
}
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), crate::precise::Precise::stringMul(&cost, &feeRate.clone().map(Value::from).unwrap_or(Value::Null)));
m.insert("currency".to_string(), feeCurrency.map(Value::from).unwrap_or(Value::Null));
m.insert("rate".to_string(), feeRate.map(Value::from).unwrap_or(Value::Null));
m
});
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade);
m.insert("id".to_string(), id);
m.insert("symbol".to_string(), self.safe_string_k(marketResolved, "symbol", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("order".to_string(), order.map(Value::from).unwrap_or(Value::Null));
m.insert("type".to_string(), type_var);
m.insert("side".to_string(), side.map(Value::from).unwrap_or(Value::Null));
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), price.map(Value::from).unwrap_or(Value::Null));
m.insert("amount".to_string(), (if linear { amount } else { Value::Null }));
m.insert("cost".to_string(), cost);
m.insert("fee".to_string(), fee);
m
}), &[]);
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);
let mut symbolValue: Option<String> = self.safe_string_k_opt(market.clone(), "symbol", &[]);
let mut typeValue: Value = self.safe_string_k(params.clone(), "orderType", &[type_var]);
let mut timeInForce: Option<String> = self.safe_string_k(params.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
let postOnlyparamsPostOnlyVariable: Vec<Value> = self.handle_post_only(Value::Bool(typeValue.as_str() == Some("market")), Value::Bool(typeValue.as_str() == Some("post")), &[params]).as_array().cloned().unwrap_or_default();
let mut postOnly: Value = postOnlyparamsPostOnlyVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPostOnly: Value = postOnlyparamsPostOnlyVariable.get(1).cloned().unwrap_or(Value::Null);
if postOnly.as_bool() == Some(true) {
typeValue = Value::Str("post".into());
} else if (timeInForce.as_deref() == Some("ioc")) {
typeValue = Value::Str("ioc".into());
} else if (typeValue.as_str() == Some("limit")) {
typeValue = Value::Str("lmt".into());
} else if (typeValue.as_str() == Some("market")) {
typeValue = Value::Str("mkt".into());
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("side".to_string(), side);
m.insert("size".to_string(), self.amount_to_precision(symbolValue.clone().map(Value::from).unwrap_or(Value::Null), amount));
m
});
let mut clientOrderId: Option<String> = self.safe_string2_opt(paramsPostOnly.clone(), Value::Str("clientOrderId".into()), Value::Str("cliOrdId".into()), &[]);
if (clientOrderId.is_some()) {
request.insert("cliOrdId".into(), clientOrderId.map(Value::from).unwrap_or(Value::Null));
}
let mut triggerPrice: Option<String> = self.safe_string2_opt(paramsPostOnly.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut isTriggerOrder: bool = triggerPrice.is_some();
let mut stopLossTriggerPrice: Option<String> = self.safe_string_k_opt(paramsPostOnly.clone(), "stopLossPrice", &[]);
let mut takeProfitTriggerPrice: Option<String> = self.safe_string_k_opt(paramsPostOnly.clone(), "takeProfitPrice", &[]);
let mut isStopLossTriggerOrder: bool = stopLossTriggerPrice.is_some();
let mut isTakeProfitTriggerOrder: bool = takeProfitTriggerPrice.is_some();
let mut isStopLossOrTakeProfitTrigger: bool = isStopLossTriggerOrder || isTakeProfitTriggerOrder;
let mut triggerSignal: Value = self.safe_string_k(paramsPostOnly.clone(), "triggerSignal", &[Value::Str("last".into())]);
let mut reduceOnlyParam: bool = self.safe_bool_k_opt(paramsPostOnly.clone(), "reduceOnly", &[Value::Bool(false)]).unwrap_or(false);
let mut reduceOnly: bool = reduceOnlyParam;
if isStopLossOrTakeProfitTrigger || isTriggerOrder {
request.insert("triggerSignal".into(), triggerSignal);
}
if isTriggerOrder {
typeValue = Value::Str("stp".into());
request.insert("stopPrice".into(), self.price_to_precision(symbolValue.clone().map(Value::from).unwrap_or(Value::Null), triggerPrice.map(Value::from).unwrap_or(Value::Null)));
} else if isStopLossOrTakeProfitTrigger {
reduceOnly = true;
if isStopLossTriggerOrder {
typeValue = Value::Str("stp".into());
request.insert("stopPrice".into(), self.price_to_precision(symbolValue.clone().map(Value::from).unwrap_or(Value::Null), stopLossTriggerPrice.map(Value::from).unwrap_or(Value::Null)));
} else if isTakeProfitTriggerOrder {
typeValue = Value::Str("take_profit".into());
request.insert("stopPrice".into(), self.price_to_precision(symbolValue.clone().map(Value::from).unwrap_or(Value::Null), takeProfitTriggerPrice.map(Value::from).unwrap_or(Value::Null)));
}
}
if reduceOnly {
request.insert("reduceOnly".into(), Value::Bool(true));
}
request.insert("orderType".into(), typeValue.clone());
let mut priceValue: Value = self.parse_number(price, &[]); let mut isLimitOrder: bool = (typeValue.as_str() == Some("lmt")) || (typeValue.as_str() == Some("post")) || (typeValue.as_str() == Some("ioc"));
let mut limitPriceParam: Option<String> = self.safe_string_k(paramsPostOnly.clone(), "limitPrice", &[]).as_str().map(str::to_owned); if isLimitOrder && (priceValue == Value::Null) && (limitPriceParam.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder () requires a price argument for ".into())).into()), typeValue).into()), Value::Str(" orders".into()))));
}
let mut isMarketOrder: bool = typeValue.as_str() == Some("mkt");
if (priceValue != Value::Null) && !isMarketOrder {
request.insert("limitPrice".into(), self.price_to_precision(symbolValue.map(Value::from).unwrap_or(Value::Null), priceValue));
}
let mut paramsOmitted: Value = self.omit(paramsPostOnly, Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("timeInForce".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]);
return self.extend(Value::Map(request), &[paramsOmitted]);
Value::Null
}
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 orderRequest: Value = self.create_order_request(symbol, type_var, side, amount, &[price, params]);
let mut response: Value = self.private_post_sendorder(&[orderRequest]).await;
let mut sendStatus: Value = self.safe_value_k(response, "sendStatus", &[]);
let mut status: Option<String> = self.safe_string_k_opt(sendStatus.clone(), "status", &[]);
self.verify_order_action_success(status.map(Value::from).unwrap_or(Value::Null), Value::Str("createOrder".into()), &[Value::from(vec![Value::Str("filled".into())])]);
return self.parse_order(sendStatus, &[market]);
Value::Null
}
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: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_873: bool = true;
while { if !__for_first_873 { i += 1; } __for_first_873 = false; i < (orders.len() as i64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), Value::Int(i), &[]);
let mut marketId: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "symbol", &[]);
let mut type_var: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "type", &[]);
let mut side: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "side", &[]);
let mut amount: Value = self.safe_value_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_value_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()]); if !(matches!(&extendedParams, Value::Dict(__d) if __d.contains_key("order_tag"))) {
if let Value::Dict(__d) = &mut extendedParams { std::sync::Arc::make_mut(__d).insert("order_tag".into(), self.number_to_string(self.sum(&[Value::Int(i), Value::Int(1)]))); }; }
if let Value::Dict(__d) = &mut extendedParams { std::sync::Arc::make_mut(__d).insert("order".into(), Value::Str("send".into())); }
let mut orderRequest: Value = self.create_order_request(marketId.map(Value::from).unwrap_or(Value::Null), type_var.map(Value::from).unwrap_or(Value::Null), side.map(Value::from).unwrap_or(Value::Null), amount, &[price, extendedParams]);
ordersRequests.push(orderRequest);
}
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("batchOrder".to_string(), Value::from(ordersRequests));
m
});
let __ws_arg_5 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_post_batchorder(&[__ws_arg_5]).await;
let mut data: Value = self.safe_list_k(response, "batchStatus", &[Value::from(vec![])]);
return self.parse_orders(data, &[]);
Value::Null
}
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 request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id);
m
});
if (amount != Value::Null) {
request.insert("size".into(), amount);
}
if (price != Value::Null) {
request.insert("limitPrice".into(), price);
}
let __ws_arg_6 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_post_editorder(&[__ws_arg_6]).await;
let mut editStatus: Value = self.safe_dict_k(response.clone(), "editStatus", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Option<String> = self.safe_string_k_opt(editStatus.clone(), "status", &[]);
self.verify_order_action_success(status.map(Value::from).unwrap_or(Value::Null), Value::Str("editOrder".into()), &[Value::from(vec![Value::Str("filled".into())])]);
let mut order: indexmap::IndexMap<String, Value> = self.parse_order(editStatus, &[]).as_map().cloned().unwrap_or_default();
order.insert("info".into(), response);
return Value::Map(order);
Value::Null
}
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let __ws_arg_7 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order_id".to_string(), id);
m
}), &[params]);
let mut response: Value = self.private_post_cancelorder(&[__ws_arg_7]).await;
let mut status: Option<String> = self.safe_string_opt(self.safe_dict_k(response.clone(), "cancelStatus", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("status".into()), &[]);
self.verify_order_action_success(status.map(Value::from).unwrap_or(Value::Null), Value::Str("cancelOrder".into()), &[]);
let mut order: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (matches!(&response, Value::Dict(__d) if __d.contains_key("cancelStatus"))) {
order = self.parse_order(response.as_map().and_then(|__m| __m.get("cancelStatus")).cloned().unwrap_or(Value::Null), &[]).as_map().cloned().unwrap_or_default();
}
return self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[Value::Map(order)]);
Value::Null
}
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Vec<Value> = Vec::new();
let mut clientOrderIds: Vec<Value> = self.safe_list_k(params.clone(), "clientOrderIds", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut clientOrderIdsLength: f64 = ((clientOrderIds.len() as i64) as f64);
if clientOrderIdsLength > ((0i64) as f64) {
{
let mut i: i64 = 0;
let mut __for_first_874: bool = true;
while { if !__for_first_874 { i += 1; } __for_first_874 = false; i < (clientOrderIds.len() as i64) } {
orders.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), Value::Str("cancel".into()));
m.insert("cliOrdId".to_string(), clientOrderIds.get(i as usize).cloned().unwrap_or(Value::Null));
m
}));
}
}
} else {
{
let mut i: i64 = 0;
let mut __for_first_875: bool = true;
while { if !__for_first_875 { i += 1; } __for_first_875 = false; i < (ids.len() as i64) } {
orders.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), Value::Str("cancel".into()));
m.insert("order_id".to_string(), self.safe_string(ids.clone(), Value::Int(i), &[]));
m
}));
}
}
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("batchOrder".to_string(), Value::from(orders));
m
});
let __ws_arg_8 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_post_batchorder(&[__ws_arg_8]).await;
let mut batchStatus: Value = self.safe_list_k(response, "batchStatus", &[Value::from(vec![])]);
return self.parse_orders(batchStatus, &[]);
Value::Null
}
pub async fn cancel_all_orders(&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 mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (symbol != Value::Null) {
request.insert("symbol".into(), self.market_id(symbol));
}
let __ws_arg_9 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_post_cancelallorders(&[__ws_arg_9]).await;
let mut cancelStatus: Value = self.safe_dict_k(response, "cancelStatus", &[]);
let mut orderEvents: Value = self.safe_list_k(cancelStatus, "orderEvents", &[Value::from(vec![])]);
let mut orders: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_876: bool = true;
while { if !__for_first_876 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_876 = false; i.as_f64().unwrap_or(f64::NAN) < ((orderEvents.len() as i64) as f64) } {
let mut orderEvent: Value = self.safe_dict(orderEvents.clone(), Value::Int(0), &[]);
let mut order: Value = self.safe_dict_k(orderEvent, "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
orders.push(order);
}
}
return self.parse_orders(Value::from(orders), &[]);
Value::Null
}
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 request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("timeout".to_string(), (if (timeout.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) { (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 }))) } else { Value::Int(0) }));
m
});
let __ws_arg_10 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_post_cancelallordersafter(&[__ws_arg_10]).await;
return response;
Value::Null
}
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 market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut response: Value = self.private_get_openorders(&[params]).await;
let mut orders: Value = self.safe_list_k(response, "openOrders", &[Value::from(vec![])]);
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
pub async fn fetch_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 market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut response: Value = self.private_get_orders_status(&[params]).await;
let mut orders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("orderIds".to_string(), Value::from(vec![id.clone()]));
m
});
let __ws_arg_11 = self.extend(Value::Map(request), &[params]);
let mut orders: Value = self.fetch_orders(&[Value::Null, Value::Null, Value::Null, __ws_arg_11]).await;
let mut order: Value = self.safe_dict(orders, Value::Int(0), &[]);
if (order == Value::Null) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOrder could not find order id ".into())).into()), id)));
}
return order;
Value::Null
}
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 market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
request.insert("count".into(), limit.clone());
}
if (since != Value::Null) {
request.insert("since".into(), since.clone());
}
let mut isTrigger: bool = self.safe_bool2_opt(params.clone(), Value::Str("trigger".into()), Value::Str("stop".into()), &[Value::Bool(false)]).unwrap_or(false);
let mut response: Value = Value::Null;
let mut paramsOmitted: Value = self.omit(params.clone(), Value::from(vec![Value::Str("trigger".into()), Value::Str("stop".into())]), &[]);
if isTrigger {
let __ws_arg_12 = self.extend(Value::Map(request.clone()), &[paramsOmitted]);
response = self.history_get_triggers(&[__ws_arg_12]).await;
} else {
let __ws_arg_13 = self.extend(Value::Map(request), &[params]);
response = self.history_get_orders(&[__ws_arg_13]).await;
}
let mut allOrders: Value = self.safe_list_k(response, "elements", &[Value::from(vec![])]);
let mut closedOrders: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_877: bool = true;
while { if !__for_first_877 { i += 1; } __for_first_877 = false; i < (allOrders.len() as i64) } {
let mut order: Value = self.safe_dict(allOrders.clone(), Value::Int(i), &[]);
let mut event: Value = self.safe_dict_k(order, "event", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderPlaced: Value = self.safe_dict2(event.clone(), Value::Str("OrderPlaced".into()), Value::Str("OrderTriggerActivated".into()), &[]);
let mut orderUpdated: Value = self.safe_dict_k(event, "OrderUpdated", &[]);
if (orderPlaced != Value::Null) {
let mut innerOrder: Value = self.safe_dict_k(orderPlaced, "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut filled: Option<String> = self.safe_string_k(innerOrder.clone(), "filled", &[]).as_str().map(str::to_owned);
if (filled.as_deref() != Some("0")) {
if let Value::Dict(__d) = &mut innerOrder { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("closed".into())); }; closedOrders.push(innerOrder);
}
} else if (orderUpdated != Value::Null) {
let mut reason: Option<String> = self.safe_string_k(orderUpdated.clone(), "reason", &[]).as_str().map(str::to_owned);
if (reason.as_deref() == Some("full_fill")) {
let mut newOrder: Value = self.safe_dict_k(orderUpdated, "newOrder", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut newOrder { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("closed".into())); }
closedOrders.push(newOrder);
}
}
}
}
return self.parse_orders(Value::from(closedOrders), &[market, since, limit]);
Value::Null
}
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 market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
request.insert("count".into(), limit.clone());
}
if (since != Value::Null) {
request.insert("since".into(), since.clone());
}
let mut response: Value = Value::Null;
let mut isTrigger: bool = self.safe_bool2_opt(params.clone(), Value::Str("trigger".into()), Value::Str("stop".into()), &[Value::Bool(false)]).unwrap_or(false);
let mut paramsOmitted: Value = self.omit(params.clone(), Value::from(vec![Value::Str("trigger".into()), Value::Str("stop".into())]), &[]);
if isTrigger {
let __ws_arg_14 = self.extend(Value::Map(request.clone()), &[paramsOmitted]);
response = self.history_get_triggers(&[__ws_arg_14]).await;
} else {
let __ws_arg_15 = self.extend(Value::Map(request), &[params]);
response = self.history_get_orders(&[__ws_arg_15]).await;
}
let mut allOrders: Value = self.safe_list_k(response, "elements", &[Value::from(vec![])]);
let mut canceledAndRejected: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_878: bool = true;
while { if !__for_first_878 { i += 1; } __for_first_878 = false; i < (allOrders.len() as i64) } {
let mut order: Value = self.safe_dict(allOrders.clone(), Value::Int(i), &[]);
let mut event: Value = self.safe_dict_k(order, "event", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut isCancelledTriggerOrder: bool = matches!(&event, Value::Dict(__d) if __d.contains_key("OrderTriggerCancelled"));
let mut orderPlaced: Value = self.safe_dict2(event.clone(), Value::Str("OrderPlaced".into()), Value::Str("OrderTriggerCancelled".into()), &[]);
if (orderPlaced != Value::Null) {
let mut innerOrder: Value = self.safe_dict_k(orderPlaced, "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut filled: Option<String> = self.safe_string_k(innerOrder.clone(), "filled", &[]).as_str().map(str::to_owned);
if (filled.as_deref() == Some("0")) || isCancelledTriggerOrder {
if let Value::Dict(__d) = &mut innerOrder { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("canceled".into())); }; canceledAndRejected.push(innerOrder.clone());
}
}
let mut orderCanceled: Value = self.safe_dict_k(event.clone(), "OrderCancelled", &[]);
if (orderCanceled != Value::Null) {
let mut innerOrder: Value = self.safe_dict_k(orderCanceled, "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut innerOrder { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("canceled".into())); }; canceledAndRejected.push(innerOrder.clone());
}
let mut orderRejected: Value = self.safe_dict_k(event, "OrderRejected", &[]);
if (orderRejected != Value::Null) {
let mut innerOrder: Value = self.safe_dict_k(orderRejected, "order", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut innerOrder { std::sync::Arc::make_mut(__d).insert("status".into(), Value::Str("rejected".into())); }; canceledAndRejected.push(innerOrder);
}
}
}
return self.parse_orders(Value::from(canceledAndRejected), &[market, since, limit]);
Value::Null
}
pub fn parse_order_type(&self, mut orderType: Value) -> Option<String> {
let mut typesMap: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("lmt".to_string(), Value::Str("limit".into()));
m.insert("mkt".to_string(), Value::Str("market".into()));
m.insert("post".to_string(), Value::Str("limit".into()));
m.insert("ioc".to_string(), Value::Str("market".into()));
m
});
return self.safe_string(Value::Map(typesMap), orderType.clone(), &[orderType.clone()]).as_str().map(str::to_owned);
}
pub fn verify_order_action_success(&self, mut status: Value, mut method: Value, optional_args: &[Value]) {
let mut omit = get_arg(optional_args, 0, Value::from(vec![]));
let mut errors: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("invalidOrderType".to_string(), Value::Str("InvalidOrder".into()));
m.insert("invalidSide".to_string(), Value::Str("InvalidOrder".into()));
m.insert("invalidSize".to_string(), Value::Str("InvalidOrder".into()));
m.insert("invalidPrice".to_string(), Value::Str("InvalidOrder".into()));
m.insert("insufficientAvailableFunds".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("selfFill".to_string(), Value::Str("ExchangeError".into()));
m.insert("tooManySmallOrders".to_string(), Value::Str("ExchangeError".into()));
m.insert("maxPositionViolation".to_string(), Value::Str("BadRequest".into()));
m.insert("marketSuspended".to_string(), Value::Str("ExchangeNotAvailable".into()));
m.insert("marketInactive".to_string(), Value::Str("ExchangeNotAvailable".into()));
m.insert("clientOrderIdAlreadyExist".to_string(), Value::Str("DuplicateOrderId".into()));
m.insert("clientOrderIdTooLong".to_string(), Value::Str("BadRequest".into()));
m.insert("outsidePriceCollar".to_string(), Value::Str("InvalidOrder".into()));
m.insert("postWouldExecute".to_string(), Value::Str("OrderImmediatelyFillable".into()));
m.insert("iocWouldNotExecute".to_string(), Value::Str("OrderNotFillable".into()));
m.insert("wouldNotReducePosition".to_string(), Value::Str("ExchangeError".into()));
m.insert("orderForEditNotFound".to_string(), Value::Str("OrderNotFound".into()));
m.insert("orderForEditNotAStop".to_string(), Value::Str("InvalidOrder".into()));
m.insert("filled".to_string(), Value::Str("OrderNotFound".into()));
m.insert("notFound".to_string(), Value::Str("OrderNotFound".into()));
m
});
if (matches!((&errors, &status), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) && !(self.in_array(status.clone(), omit).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::create_error(&crate::runtime::stringify_param(&((if let (Some(__m), Some(__k)) = (errors.as_map(), status.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null }))), &crate::runtime::stringify_param(&(Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}",
Value::Str(format!("{}{}", self.id.clone(), Value::Str(": ".into())).into()), method).into()), Value::Str(" failed due to ".into())).into()), status).into())))));
}
}
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("placed".to_string(), Value::Str("open".into()));
m.insert("cancelled".to_string(), Value::Str("canceled".into()));
m.insert("invalidOrderType".to_string(), Value::Str("rejected".into()));
m.insert("invalidSide".to_string(), Value::Str("rejected".into()));
m.insert("invalidSize".to_string(), Value::Str("rejected".into()));
m.insert("invalidPrice".to_string(), Value::Str("rejected".into()));
m.insert("insufficientAvailableFunds".to_string(), Value::Str("rejected".into()));
m.insert("selfFill".to_string(), Value::Str("rejected".into()));
m.insert("tooManySmallOrders".to_string(), Value::Str("rejected".into()));
m.insert("maxPositionViolation".to_string(), Value::Str("rejected".into()));
m.insert("marketSuspended".to_string(), Value::Str("rejected".into()));
m.insert("marketInactive".to_string(), Value::Str("rejected".into()));
m.insert("clientOrderIdAlreadyExist".to_string(), Value::Str("rejected".into()));
m.insert("clientOrderIdTooLong".to_string(), Value::Str("rejected".into()));
m.insert("outsidePriceCollar".to_string(), Value::Str("rejected".into()));
m.insert("postWouldExecute".to_string(), Value::Str("rejected".into()));
m.insert("iocWouldNotExecute".to_string(), Value::Str("rejected".into()));
m.insert("wouldNotReducePosition".to_string(), Value::Str("rejected".into()));
m.insert("edited".to_string(), Value::Str("open".into()));
m.insert("orderForEditNotFound".to_string(), Value::Str("rejected".into()));
m.insert("orderForEditNotAStop".to_string(), Value::Str("rejected".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("notFound".to_string(), Value::Str("rejected".into()));
m.insert("untouched".to_string(), Value::Str("open".into()));
m.insert("partiallyFilled".to_string(), Value::Str("open".into()));
m.insert("ENTERED_BOOK".to_string(), Value::Str("open".into()));
m.insert("FULLY_EXECUTED".to_string(), Value::Str("closed".into()));
m.insert("CANCELLED".to_string(), Value::Str("canceled".into()));
m.insert("TRIGGER_PLACED".to_string(), Value::Str("open".into()));
m.insert("PARTIALLY_FILLED".to_string(), Value::Str("open".into()));
m.insert("UNTOUCHED".to_string(), Value::Str("open".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut orderDictFromFetchOrder: Value = self.safe_dict_k(order.clone(), "order", &[]);
if (orderDictFromFetchOrder != Value::Null) {
let mut datetime: Option<String> = self.safe_string_k_opt(orderDictFromFetchOrder.clone(), "timestamp", &[]);
let mut innerStatus: Option<String> = self.safe_string_k_opt(order.clone(), "status", &[]);
let mut fetchOrderPriceTriggerOptions: Value = self.safe_dict_k(orderDictFromFetchOrder.clone(), "priceTriggerOptions", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fetchOrderTriggerPrice: Option<String> = self.safe_string_k_opt(fetchOrderPriceTriggerOptions, "triggerPrice", &[]);
let mut unifiedSymbol: Value = self.safe_symbol(self.safe_string_k(orderDictFromFetchOrder.clone(), "symbol", &[]), &[market.clone()]);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string_k(orderDictFromFetchOrder.clone(), "orderId", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(orderDictFromFetchOrder.clone(), "cliOrdId", &[]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone().map(Value::from).unwrap_or(Value::Null)));
m.insert("datetime".to_string(), datetime.map(Value::from).unwrap_or(Value::Null));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.parse8601(self.safe_string_k(orderDictFromFetchOrder.clone(), "lastUpdateTimestamp", &[])));
m.insert("symbol".to_string(), unifiedSymbol);
m.insert("type".to_string(), Value::Null);
m.insert("timeInForce".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), self.safe_bool_k(orderDictFromFetchOrder.clone(), "reduceOnly", &[]));
m.insert("side".to_string(), self.safe_string_k(orderDictFromFetchOrder.clone(), "side", &[]));
m.insert("price".to_string(), Value::Null);
m.insert("triggerPrice".to_string(), fetchOrderTriggerPrice.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("stopPrice".to_string(), fetchOrderTriggerPrice.map(Value::from).unwrap_or(Value::Null));
m.insert("amount".to_string(), self.safe_string_k(orderDictFromFetchOrder.clone(), "quantity", &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("filled".to_string(), self.safe_string_k(orderDictFromFetchOrder, "filled", &[]));
m.insert("remaining".to_string(), Value::Null);
m.insert("status".to_string(), self.parse_order_status(innerStatus.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null));
m.insert("fee".to_string(), Value::Null);
m.insert("fees".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[]);
}
let mut orderEvents: Vec<Value> = self.safe_list_k(order.clone(), "orderEvents", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut errorStatus: Option<String> = self.safe_string_k(order.clone(), "status", &[]).as_str().map(str::to_owned);
let mut orderEventsLength: f64 = ((orderEvents.len() as i64) as f64);
if (matches!(&order, Value::Dict(__d) if __d.contains_key("orderEvents"))) && (errorStatus.is_some()) && (orderEventsLength == 0.0) {
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("status".to_string(), Value::Str("rejected".into()));
m
}), &[]);
}
let mut details: Value = Value::Null;
let mut isPrior: bool = false;
let mut fixed: bool = false;
let mut statusId: Value = Value::Null;
let mut price: Value = Value::Null;
let mut trades: Value = Value::from(vec![]);
if orderEventsLength > ((0i64) as f64) {
let mut executions: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_879: bool = true;
while { if !__for_first_879 { i += 1; } __for_first_879 = false; i < (orderEvents.len() as i64) } {
let mut item: Value = orderEvents.get(i as usize).cloned().unwrap_or(Value::Null);
if (self.safe_string_k(item.clone(), "type", &[]).as_str() == Some("EXECUTION")) {
executions.push(item.clone());
}
let mut orderTrigger: Value = self.safe_value_k(item.clone(), "orderTrigger", &[]);
if (details == Value::Null) {
details = self.safe_value2(item.clone(), Value::Str("new".into()), Value::Str("order".into()), &[orderTrigger]);
if (details != Value::Null) {
isPrior = false;
fixed = true;
} else if !(fixed) {
let mut executedPrice: Option<String> = self.safe_string_k_opt(item.clone(), "price", &[]);
let mut orderPriorExecution: Value = self.safe_dict_k(item.clone(), "orderPriorExecution", &[]);
details = self.safe_value2(item, Value::Str("orderPriorExecution".into()), Value::Str("orderPriorEdit".into()), &[]);
if (executedPrice.is_none()) {
price = self.safe_string_k(orderPriorExecution, "limitPrice", &[]);
} else {
price = executedPrice.map(Value::from).unwrap_or(Value::Null);
}
if (details != Value::Null) {
isPrior = true;
}
}
}
}
}
trades = self.parse_trades(Value::from(executions), &[]);
statusId = self.safe_string_k(order.clone(), "status", &[]);
}
if (details == Value::Null) {
details = order.clone();
}
if (statusId == Value::Null) {
statusId = self.safe_string_k(details.clone(), "status", &[]);
}
let mut status: Value = self.parse_order_status(statusId).map(Value::from).unwrap_or(Value::Null);
let mut isClosed: Value = self.in_array(status.clone(), Value::from(vec![Value::Str("canceled".into()), Value::Str("rejected".into()), Value::Str("closed".into())]));
let mut marketId: Option<String> = self.safe_string2_opt(details.clone(), Value::Str("symbol".into()), Value::Str("tradeable".into()), &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.clone().map(Value::from).unwrap_or(Value::Null), market]);
let mut symbol: Option<String> = self.safe_string_k_opt(marketResolved.clone(), "symbol", &[]);
let mut timestamp: Value = self.parse8601(self.safe_string2(details.clone(), Value::Str("timestamp".into()), Value::Str("receivedTime".into()), &[]));
let mut lastUpdateTimestamp: Value = self.parse8601(self.safe_string_k(details.clone(), "lastUpdateTime", &[]));
let mut amount: Value = self.safe_string_k(details.clone(), "quantity", &[]);
let mut filled: Value = self.safe_string2(details.clone(), Value::Str("filledSize".into()), Value::Str("filled".into()), &[Value::Str("0.0".into())]);
let mut remaining: Value = self.safe_string_k(details.clone(), "unfilledSize", &[]);
let mut average: Value = Value::Null;
let mut filled2: Value = Value::Str("0.0".into());
let mut tradesLength: f64 = ((trades.len() as i64) as f64);
if tradesLength > ((0i64) as f64) {
let mut vwapSum: Value = Value::Str("0.0".into());
{
let mut i: i64 = 0;
let mut __for_first_880: bool = true;
while { if !__for_first_880 { i += 1; } __for_first_880 = false; i < (trades.len() as i64) } {
let mut trade: Value = self.safe_dict(trades.clone(), Value::Int(i), &[]);
let mut tradeAmount: Option<String> = self.safe_string_k_opt(trade.clone(), "amount", &[]);
let mut tradePrice: Option<String> = self.safe_string_k_opt(trade, "price", &[]);
filled2 = crate::precise::Precise::stringAdd(&filled2, &tradeAmount.clone().map(Value::from).unwrap_or(Value::Null));
vwapSum = crate::precise::Precise::stringAdd(&vwapSum, &crate::precise::Precise::stringMul(&tradeAmount.clone().map(Value::from).unwrap_or(Value::Null), &tradePrice.clone().map(Value::from).unwrap_or(Value::Null)));
}
}
average = crate::precise::Precise::stringDiv(&vwapSum, &filled2);
if (amount != Value::Null) && (!(isClosed.as_bool() == Some(true))) && isPrior && crate::precise::Precise::stringGe(&filled2, &amount).as_bool() == Some(true) {
status = Value::Str("closed".into());
isClosed = Value::Bool(true);
}
if isPrior {
filled = crate::precise::Precise::stringAdd(&filled, &filled2);
} else {
filled = crate::precise::Precise::stringMax(&filled, &filled2);
}
}
if (remaining == Value::Null) {
if isPrior {
if (amount != Value::Null) {
remaining = crate::precise::Precise::stringSub(&amount, &filled2);
}
} else {
remaining = amount.clone();
}
}
if (amount == Value::Null) && (!(isPrior)) && (remaining != Value::Null) {
amount = crate::precise::Precise::stringAdd(&filled, &remaining);
}
let mut cost: Value = Value::Null;
if (filled != Value::Null) && (marketResolved != Value::Null) {
let mut whichPrice: Value = price.clone();
if (average != Value::Null) {
whichPrice = average.clone();
}
if (whichPrice != Value::Null) {
if matches!(self.safe_bool_k(marketResolved, "linear", &[Value::Bool(false)]), Value::Bool(true)) {
cost = crate::precise::Precise::stringMul(&filled, &whichPrice); } else {
cost = crate::precise::Precise::stringDiv(&filled, &whichPrice); }
}
}
let mut id: Value = self.safe_string2(order.clone(), Value::Str("order_id".into()), Value::Str("orderId".into()), &[]);
if (id == Value::Null) {
id = self.safe_string2(details.clone(), Value::Str("orderId".into()), Value::Str("uid".into()), &[]);
}
let mut type_var: Value = self.safe_string_lower2(details.clone(), Value::Str("type".into()), Value::Str("orderType".into()), &[]);
let mut parsedType: Value = self.parse_order_type(type_var.clone()).map(Value::from).unwrap_or(Value::Null);
let mut timeInForce: String = "gtc".to_string();
if (type_var.as_str() == Some("ioc")) || (parsedType.as_str() == Some("market")) {
timeInForce = "ioc".to_string();
}
let mut ts: Value = self.safe_integer_k(details.clone(), "timestamp", &[timestamp]);
let mut priceTriggerOptions: Value = self.safe_dict_k(details.clone(), "priceTriggerOptions", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut triggerPrice: Value = self.safe_string2(details.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
if (triggerPrice == Value::Null) {
triggerPrice = self.safe_string_k(priceTriggerOptions, "triggerPrice", &[]);
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order);
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), self.safe_string_n(details.clone(), Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("clientId".into()), Value::Str("cliOrdId".into())]), &[]));
m.insert("timestamp".to_string(), ts.clone());
m.insert("datetime".to_string(), self.iso8601(ts));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(details.clone(), "lastUpdateTimestamp", &[lastUpdateTimestamp]));
m.insert("symbol".to_string(), symbol.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("type".to_string(), parsedType);
m.insert("timeInForce".to_string(), Value::from(timeInForce));
m.insert("postOnly".to_string(), Value::Bool(type_var.as_str() == Some("post")));
m.insert("reduceOnly".to_string(), self.safe_bool2(details.clone(), Value::Str("reduceOnly".into()), Value::Str("reduce_only".into()), &[]));
m.insert("side".to_string(), self.safe_string_lower2(details, Value::Str("side".into()), Value::Str("direction".into()), &[]));
m.insert("price".to_string(), price);
m.insert("triggerPrice".to_string(), triggerPrice.clone());
m.insert("stopPrice".to_string(), triggerPrice);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), cost);
m.insert("average".to_string(), average);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), remaining);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), Value::Null);
m.insert("fees".to_string(), Value::Null);
m.insert("trades".to_string(), trades);
m
}), &[]);
Value::Null
}
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 symbolResolved: Value = Value::Null;
if (symbol != Value::Null) {
symbolResolved = self.symbol(symbol.clone());
}
let mut response: Value = self.private_get_fills(&[params]).await;
let mut fills: Value = self.safe_list_k(response, "fills", &[Value::from(vec![])]);
let mut trades: Value = self.parse_trades(fills, &[]);
return self.filter_by_symbol_since_limit(trades, &[symbolResolved, since, limit]);
Value::Null
}
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
}));
self.load_markets(&[]).await;
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (since != Value::Null) {
request.insert("since".into(), since.clone());
request.insert("sort".into(), Value::Str("asc".into()));
}
if (limit != Value::Null) {
request.insert("count".into(), (match (&(limit), &(Value::Int(2))) { (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: Option<i64> = self.safe_integer_k(params.clone(), "until", &[]).as_i64();
if (until.is_some()) {
request.insert("before".into(), Value::from(until));
}
let mut paramsOmitted: Value = (if (until.is_some()) { self.omit(params.clone(), Value::Str("until".into()), &[]) } else { params });
let __ws_arg_16 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.history_get_account_log(&[__ws_arg_16]).await;
let mut logs: Vec<Value> = self.safe_list_k(response, "logs", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rows: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_881: bool = true;
while { if !__for_first_881 { i += 1; } __for_first_881 = false; i < (logs.len() as i64) } {
let mut row: Value = logs.get(i as usize).cloned().unwrap_or(Value::Null);
let mut asset: Value = self.safe_string_k(row.clone(), "asset", &[]);
let mut contract: Value = self.safe_string_k(row.clone(), "contract", &[]);
if (asset != Value::Null) && (asset != contract) {
rows.push(row);
}
}
}
return self.parse_ledger(Value::from(rows), &[currency, since, limit]);
Value::Null
}
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
}));
self.load_markets(&[]).await;
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), Value::Str("funding rate change".into()));
m
});
if (since != Value::Null) {
request.insert("since".into(), since.clone());
request.insert("sort".into(), Value::Str("asc".into()));
}
if (limit != Value::Null) && (symbol == Value::Null) {
request.insert("count".into(), limit.clone());
}
let mut until: Option<i64> = self.safe_integer_k(params.clone(), "until", &[]).as_i64();
if (until.is_some()) {
request.insert("before".into(), Value::from(until));
}
let mut paramsOmitted: Value = (if (until.is_some()) { self.omit(params.clone(), Value::Str("until".into()), &[]) } else { params });
let __ws_arg_17 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.history_get_account_log(&[__ws_arg_17]).await;
let mut logs: Value = self.safe_list_k(response, "logs", &[Value::from(vec![])]);
return self.parse_incomes(logs, &[market, since, limit]);
Value::Null
}
pub fn parse_income(&self, mut income: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string_upper_k_opt(income.clone(), "contract", &[]);
let mut currencyId: Option<String> = self.safe_string_k_opt(income.clone(), "asset", &[]);
let mut timestamp: Value = self.parse8601(self.safe_string_k(income.clone(), "date", &[]));
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), income.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("code".to_string(), self.safe_currency_code(currencyId.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("id".to_string(), self.safe_string_k(income.clone(), "id", &[]));
m.insert("amount".to_string(), self.safe_number_k(income, "realized_funding", &[]));
m
});
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Option<String> {
let mut types: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("futures trade".to_string(), Value::Str("trade".into()));
m.insert("futures liquidation".to_string(), Value::Str("trade".into()));
m.insert("futures assignee".to_string(), Value::Str("trade".into()));
m.insert("futures assignor".to_string(), Value::Str("trade".into()));
m.insert("futures unwind counterparty".to_string(), Value::Str("trade".into()));
m.insert("futures unwind bankrupt".to_string(), Value::Str("trade".into()));
m.insert("covered liquidation".to_string(), Value::Str("trade".into()));
m.insert("settlement".to_string(), Value::Str("trade".into()));
m.insert("conversion".to_string(), Value::Str("trade".into()));
m.insert("funding rate change".to_string(), Value::Str("fee".into()));
m.insert("interest payment".to_string(), Value::Str("fee".into()));
m.insert("kfee applied".to_string(), Value::Str("fee".into()));
m.insert("tax withheld".to_string(), Value::Str("fee".into()));
m.insert("tax refund".to_string(), Value::Str("rebate".into()));
m.insert("transfer".to_string(), Value::Str("transfer".into()));
m.insert("subaccount transfer".to_string(), Value::Str("transfer".into()));
m.insert("cross-exchange transfer".to_string(), Value::Str("transfer".into()));
m.insert("admin transfer".to_string(), Value::Str("transfer".into()));
m
});
return self.safe_string(Value::Map(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);
let mut timestamp: Value = self.parse8601(self.safe_string_k(item.clone(), "date", &[]));
let mut currencyId: Option<String> = self.safe_string_k_opt(item.clone(), "asset", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone().map(Value::from).unwrap_or(Value::Null), &[currency.clone()]);
let mut currencyResolved: Value = self.safe_currency(currencyId.map(Value::from).unwrap_or(Value::Null), &[currency]);
let mut before: Option<String> = self.safe_string_k_opt(item.clone(), "old_balance", &[]);
let mut after: Option<String> = self.safe_string_k_opt(item.clone(), "new_balance", &[]);
let mut feeCost: Option<String> = self.safe_string_k_opt(item.clone(), "fee", &[]);
let mut amount: Value = Value::Null;
let mut direction: Value = Value::Null;
if (before.is_some()) && (after.is_some()) {
amount = crate::precise::Precise::stringSub(&after.clone().map(Value::from).unwrap_or(Value::Null), &before.clone().map(Value::from).unwrap_or(Value::Null));
if (feeCost.is_some()) {
amount = crate::precise::Precise::stringAdd(&amount, &feeCost.clone().map(Value::from).unwrap_or(Value::Null));
}
if crate::precise::Precise::stringLt(&amount, &Value::Str("0".into())).as_bool() == Some(true) {
direction = Value::Str("out".into());
amount = crate::precise::Precise::stringAbs(&amount);
} else {
direction = Value::Str("in".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(), "id", &[]));
m.insert("direction".to_string(), direction);
m.insert("account".to_string(), self.safe_string_k(item.clone(), "margin_account", &[]));
m.insert("referenceId".to_string(), self.safe_string2(item.clone(), Value::Str("execution".into()), Value::Str("booking_uid".into()), &[]));
m.insert("referenceAccount".to_string(), Value::Null);
m.insert("type".to_string(), self.parse_ledger_entry_type(self.safe_string_k(item, "info", &[])).map(Value::from).unwrap_or(Value::Null));
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("before".to_string(), self.parse_number(before.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("after".to_string(), self.parse_number(after.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("status".to_string(), Value::Str("ok".into()));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(feeCost.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("currency".to_string(), code);
m
}));
m
}), &[currencyResolved]);
Value::Null
}
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 type_var: Value = self.safe_string2(params.clone(), Value::Str("type".into()), Value::Str("account".into()), &[]);
let mut symbol: Value = self.safe_string_k(params.clone(), "symbol", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("type".into()), Value::Str("account".into()), Value::Str("symbol".into())]), &[]);
let mut response: Value = self.private_get_accounts(&[paramsOmitted]).await;
let mut datetime: Option<String> = self.safe_string_k_opt(response.clone(), "serverTime", &[]);
if (type_var.as_str() == Some("marginAccount")) || (type_var.as_str() == Some("margin")) {
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchBalance requires symbol argument for margin accounts".into()))));
}
type_var = symbol.clone();
}
if (type_var == Value::Null) {
if (symbol == Value::Null) {
type_var = Value::Str("flex".into());
} else {
type_var = symbol.clone();
}
}
let mut accountName: Value = self.parse_kraken_account_name(type_var.clone());
let mut accounts: Value = self.safe_dict_k(response.clone(), "accounts", &[]);
let mut account: Value = self.safe_dict(accounts, accountName, &[]);
if (account == Value::Null) {
if (type_var == Value::Null) {
type_var = Value::Str("".into());
}
if (symbol == Value::Null) {
symbol = Value::Str("".into());
}
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchBalance has no account for ".into())).into()), type_var)));
}
let mut balance: Value = self.parse_balance(account);
if let Value::Dict(__rda) = &mut balance { std::sync::Arc::make_mut(__rda).insert("info".to_string(), response); }
if let Value::Dict(__rda) = &mut balance { std::sync::Arc::make_mut(__rda).insert("timestamp".to_string(), self.parse8601(datetime.clone().map(Value::from).unwrap_or(Value::Null))); }
if let Value::Dict(__rda) = &mut balance { std::sync::Arc::make_mut(__rda).insert("datetime".to_string(), datetime.map(Value::from).unwrap_or(Value::Null)); }
return balance;
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut accountType: Option<String> = self.safe_string2(response.clone(), Value::Str("accountType".into()), Value::Str("type".into()), &[]).as_str().map(str::to_owned);
let mut isFlex: bool = accountType.as_deref() == Some("multiCollateralMarginAccount");
let mut isCash: bool = accountType.as_deref() == Some("cashAccount");
let mut balances: Value = self.safe_dict2(response.clone(), Value::Str("balances".into()), Value::Str("currencies".into()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut currencyIds: Vec<Value> = Value::Array(balances.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).as_array().cloned().unwrap_or_default();
{
let mut i: i64 = 0;
let mut __for_first_882: bool = true;
while { if !__for_first_882 { i += 1; } __for_first_882 = false; i < (currencyIds.len() as i64) } {
let mut currencyId: Value = currencyIds.get(i as usize).cloned().unwrap_or(Value::Null);
let mut balance: Value = (if let (Some(__m), Some(__k)) = (balances.as_map(), currencyId.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
let mut code: Value = self.safe_currency_code(currencyId, &[]);
if (code == Value::Null) {
continue;
}
let mut splitCode: Vec<Value> = Value::Array(if let Some(__s) = code.as_str() { __s.split("_").map(Value::from).collect() } else { Vec::new() }).as_array().cloned().unwrap_or_default();
let mut codeLength: f64 = ((splitCode.len() as i64) as f64);
if codeLength > ((1i64) as f64) {
continue;
}
let mut account: indexmap::IndexMap<String, Value> = self.account().as_map().cloned().unwrap_or_default();
if isFlex {
account.insert("total".into(), self.safe_string_k(balance.clone(), "quantity", &[]));
account.insert("free".into(), self.safe_string_k(balance.clone(), "available", &[]));
} else if isCash {
account.insert("used".into(), Value::Str("0.0".into()));
account.insert("total".into(), balance);
} else {
let mut auxiliary: Value = self.safe_dict_k(response.clone(), "auxiliary", &[]);
account.insert("free".into(), self.safe_string_k(auxiliary.clone(), "af", &[]));
account.insert("total".into(), self.safe_string_k(auxiliary, "pv", &[]));
}
if (code != Value::Null) {
result.insert(crate::runtime::stringify_param(&code), Value::Map(account));
}
}
}
return self.safe_balance(Value::Map(result));
Value::Null
}
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 marketIds: Value = self.market_ids(&[symbols]);
let mut response: Value = self.public_get_tickers(&[params]).await;
let mut tickers: Value = self.safe_list_k(response, "tickers", &[Value::from(vec![])]);
let mut fundingRates: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_883: bool = true;
while { if !__for_first_883 { i += 1; } __for_first_883 = false; i < (tickers.len() as i64) } {
let mut entry: Value = self.safe_dict(tickers.clone(), Value::Int(i), &[]);
let mut entry_symbol: Option<String> = self.safe_string_k_opt(entry.clone(), "symbol", &[]);
if (marketIds != Value::Null) {
if !(self.in_array(entry_symbol.clone().map(Value::from).unwrap_or(Value::Null), marketIds.clone()).as_bool() == Some(true)) {
continue;
}
}
let mut market: Value = self.safe_market(&[entry_symbol.map(Value::from).unwrap_or(Value::Null)]);
let mut parsed: Value = self.parse_funding_rate(entry, &[market]);
fundingRates.push(parsed);
}
}
return self.index_by(Value::from(fundingRates), Value::Str("symbol".into()));
Value::Null
}
pub fn parse_funding_rate(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string_k_opt(ticker.clone(), "symbol", &[]);
let mut symbol: Value = self.symbol(marketId.map(Value::from).unwrap_or(Value::Null));
let mut timestamp: Value = self.parse8601(self.safe_string_k(ticker.clone(), "lastTime", &[]));
let mut markPriceString: Option<String> = self.safe_string_k_opt(ticker.clone(), "markPrice", &[]);
let mut fundingRateString: Option<String> = self.safe_string_k_opt(ticker.clone(), "fundingRate", &[]);
let mut fundingRateResult: Value = crate::precise::Precise::stringDiv(&fundingRateString.clone().map(Value::from).unwrap_or(Value::Null), &markPriceString.clone().map(Value::from).unwrap_or(Value::Null));
let mut nextFundingRateString: Option<String> = self.safe_string_k_opt(ticker.clone(), "fundingRatePrediction", &[]);
let mut nextFundingRateResult: Value = crate::precise::Precise::stringDiv(&nextFundingRateString.clone().map(Value::from).unwrap_or(Value::Null), &markPriceString.clone().map(Value::from).unwrap_or(Value::Null));
if crate::precise::Precise::stringGt(&fundingRateResult, &Value::Str("0.25".into())).as_bool() == Some(true) {
fundingRateResult = Value::Str("0.25".into());
} else if crate::precise::Precise::stringLt(&fundingRateResult, &Value::Str("-0.25".into())).as_bool() == Some(true) {
fundingRateResult = Value::Str("-0.25".into());
}
if crate::precise::Precise::stringGt(&nextFundingRateResult, &Value::Str("0.25".into())).as_bool() == Some(true) {
nextFundingRateResult = Value::Str("0.25".into());
} else if crate::precise::Precise::stringLt(&nextFundingRateResult, &Value::Str("-0.25".into())).as_bool() == Some(true) {
nextFundingRateResult = Value::Str("-0.25".into());
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), ticker.clone());
m.insert("symbol".to_string(), symbol);
m.insert("markPrice".to_string(), self.parse_number(markPriceString.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("indexPrice".to_string(), self.safe_number_k(ticker, "indexPrice", &[]));
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("fundingRate".to_string(), self.parse_number(fundingRateResult, &[]));
m.insert("fundingTimestamp".to_string(), Value::Null);
m.insert("fundingDatetime".to_string(), Value::Null);
m.insert("nextFundingRate".to_string(), self.parse_number(nextFundingRateResult, &[]));
m.insert("nextFundingTimestamp".to_string(), Value::Null);
m.insert("nextFundingDatetime".to_string(), Value::Null);
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(), Value::Str("1h".into()));
m
});
Value::Null
}
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 market: Value = self.market(symbol.clone());
if !matches!(self.safe_bool_k(market.clone(), "swap", &[Value::Bool(false)]), Value::Bool(true)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() supports swap contracts only".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_string_upper_k(market, "id", &[]));
m
});
let __ws_arg_18 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_get_historicalfundingrates(&[__ws_arg_18]).await;
let mut rates: Value = self.safe_list_k(response, "rates", &[Value::from(vec![])]);
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_884: bool = true;
while { if !__for_first_884 { i += 1; } __for_first_884 = false; i < (rates.len() as i64) } {
let mut item: Value = self.safe_dict(rates.clone(), Value::Int(i), &[]);
let mut datetime: Option<String> = self.safe_string_k_opt(item.clone(), "timestamp", &[]);
result.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("fundingRate".to_string(), self.safe_number_k(item, "relativeFundingRate", &[]));
m.insert("timestamp".to_string(), self.parse8601(datetime.clone().map(Value::from).unwrap_or(Value::Null)));
m.insert("datetime".to_string(), datetime.map(Value::from).unwrap_or(Value::Null));
m
}));
}
}
let mut sorted: Value = self.sort_by(Value::from(result), Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[symbol, since, limit]);
Value::Null
}
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: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = self.private_get_openpositions(&[Value::Map(request)]).await;
let mut positions: Value = self.safe_list_k(response, "openPositions", &[]);
if (positions == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_not_available(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() returned a response without an \"openPositions\" list".into()))));
}
return self.parse_positions(positions, &[symbols]);
Value::Null
}
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
}));
self.load_markets(&[]).await;
let mut market: Value = Value::Null;
if (symbols != Value::Null) {
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
if (symbolsLength == 1.0) {
market = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
}
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("closed".to_string(), Value::Bool(true));
m
});
if (market != Value::Null) {
request.insert("tradeable".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
if (since != Value::Null) {
request.insert("since".into(), since.clone());
request.insert("sort".into(), Value::Str("asc".into()));
}
if (limit != Value::Null) {
request.insert("count".into(), limit.clone());
}
let mut until: Option<i64> = self.safe_integer_k(params.clone(), "until", &[]).as_i64();
if (until.is_some()) {
request.insert("before".into(), Value::from(until));
}
let mut paramsOmitted: Value = (if (until.is_some()) { self.omit(params.clone(), Value::Str("until".into()), &[]) } else { params });
let __ws_arg_19 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.history_get_positions(&[__ws_arg_19]).await;
let mut elements: Vec<Value> = self.safe_list_k(response, "elements", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut updates: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_885: bool = true;
while { if !__for_first_885 { i += 1; } __for_first_885 = false; i < (elements.len() as i64) } {
let mut event: Value = self.safe_dict_k(elements.get(i as usize).cloned().unwrap_or(Value::Null), "event", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut update: Value = self.safe_dict_k(event, "PositionUpdate", &[]);
if (update != Value::Null) {
updates.push(update);
}
}
}
let mut positions: Value = self.parse_positions(Value::from(updates), &[symbols]);
return self.filter_by_since_limit(positions, &[since, limit]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut positionChange: Option<String> = self.safe_string_k(position.clone(), "positionChange", &[]).as_str().map(str::to_owned);
let mut isHistory: bool = positionChange.is_some();
let mut leverage: Value = self.safe_number_k(position.clone(), "maxFixedLeverage", &[]);
let mut marginType: String = "cross".to_string();
if (leverage != Value::Null) {
marginType = "isolated".to_string();
}
let mut timestamp: Value = Value::Null;
let mut datetime: Value = Value::Null;
if isHistory {
timestamp = self.safe_integer_k(position.clone(), "timestamp", &[]);
datetime = self.iso8601(timestamp.clone());
} else {
datetime = self.safe_string_k(position.clone(), "fillTime", &[]);
timestamp = self.parse8601(datetime.clone());
}
let mut side: Value = self.safe_string_k(position.clone(), "side", &[]);
let mut entryPrice: Option<String> = self.safe_string_k_opt(position.clone(), "price", &[]);
let mut contracts: Value = self.safe_string_k(position.clone(), "size", &[]);
if isHistory {
let mut describesNewPosition: bool = (positionChange.as_deref() == Some("open")) || (positionChange.as_deref() == Some("increase"));
let mut signedSize: Option<String> = self.safe_string_k_opt(position.clone(), "oldPosition", &[]);
entryPrice = self.safe_string_k_opt(position.clone(), "oldAverageEntryPrice", &[]);
contracts = self.safe_string_k(position.clone(), "executionSize", &[]);
if describesNewPosition {
signedSize = self.safe_string_k_opt(position.clone(), "newPosition", &[]);
entryPrice = self.safe_string_k_opt(position.clone(), "newAverageEntryPrice", &[]);
contracts = crate::precise::Precise::stringAbs(&signedSize.clone().map(Value::from).unwrap_or(Value::Null));
} else if (positionChange.as_deref() == Some("reverse")) {
contracts = crate::precise::Precise::stringAbs(&signedSize.clone().map(Value::from).unwrap_or(Value::Null)); }
if crate::precise::Precise::stringGt(&signedSize.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("0".into())).as_bool() == Some(true) {
side = Value::Str("long".into());
} else if crate::precise::Precise::stringLt(&signedSize.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("0".into())).as_bool() == Some(true) {
side = Value::Str("short".into());
}
}
let mut marketId: Option<String> = self.safe_string2_opt(position.clone(), Value::Str("symbol".into()), Value::Str("tradeable".into()), &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
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(), "executionUid", &[]));
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);
m.insert("datetime".to_string(), datetime);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("entryPrice".to_string(), self.parse_number(entryPrice.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("notional".to_string(), Value::Null);
m.insert("leverage".to_string(), leverage);
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "unrealizedPnl", &[]));
m.insert("realizedPnl".to_string(), self.safe_number_k(position.clone(), "realizedPnL", &[]));
m.insert("contracts".to_string(), self.parse_number(contracts, &[]));
m.insert("contractSize".to_string(), self.safe_number_k(marketResolved, "contractSize", &[]));
m.insert("marginRatio".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("markPrice".to_string(), Value::Null);
m.insert("lastPrice".to_string(), self.safe_number_k(position, "executionPrice", &[]));
m.insert("collateral".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::from(marginType));
m.insert("side".to_string(), side);
m.insert("percentage".to_string(), Value::Null);
m
}));
Value::Null
}
pub async fn fetch_leverage_tiers(&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 response: Value = self.public_get_instruments(&[params]).await;
let mut data: Value = self.safe_list_k(response, "instruments", &[]);
return self.parse_leverage_tiers(data, &[symbols, Value::Str("symbol".into())]);
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);
let mut marginLevels: Value = self.safe_list_k(info.clone(), "marginLevels", &[]);
let mut marketId: Option<String> = self.safe_string_k_opt(info, "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.clone().map(Value::from).unwrap_or(Value::Null), market]);
let mut tiers: Value = Value::from(vec![]);
if (marginLevels == Value::Null) {
return tiers;
}
{
let mut i: i64 = 0;
let mut __for_first_886: bool = true;
while { if !__for_first_886 { i += 1; } __for_first_886 = false; i < (marginLevels.len() as i64) } {
let mut tier: Value = marginLevels.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut initialMargin: Option<String> = self.safe_string_k_opt(tier.clone(), "initialMargin", &[]);
let mut minNotional: Option<f64> = self.safe_number2_opt(tier.clone(), Value::Str("numNonContractUnits".into()), Value::Str("contracts".into()), &[]);
if let Value::Arr(__a) = &mut tiers { std::sync::Arc::make_mut(__a).push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tier".to_string(), self.sum(&[Value::Int(i), Value::Int(1)]));
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone().map(Value::from).unwrap_or(Value::Null), &[marketResolved.clone()]));
m.insert("currency".to_string(), marketResolved.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null));
m.insert("minNotional".to_string(), Value::from(minNotional));
m.insert("maxNotional".to_string(), self.safe_number2(self.safe_value(marginLevels.clone(), self.sum(&[Value::Int(i), Value::Int(1)]), &[]), Value::Str("numNonContractUnits".into()), Value::Str("contracts".into()), &[]));
m.insert("maintenanceMarginRate".to_string(), self.safe_number_k(tier.clone(), "maintenanceMargin", &[]));
m.insert("maxLeverage".to_string(), self.parse_number(crate::precise::Precise::stringDiv(&Value::Str("1".into()), &initialMargin.clone().map(Value::from).unwrap_or(Value::Null)), &[]));
m.insert("info".to_string(), tier);
m
})); }
}
}
return tiers;
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let __currency_empty = indexmap::IndexMap::new();
let currency = currency.as_map().unwrap_or(&__currency_empty);
let mut datetime: Option<String> = self.safe_string_k_opt(transfer.clone(), "serverTime", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), Value::Null);
m.insert("timestamp".to_string(), self.parse8601(datetime.clone().map(Value::from).unwrap_or(Value::Null)));
m.insert("datetime".to_string(), datetime.map(Value::from).unwrap_or(Value::Null));
m.insert("currency".to_string(), (match currency.get("code") { 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 }));
m.insert("amount".to_string(), Value::Null);
m.insert("fromAccount".to_string(), Value::Null);
m.insert("toAccount".to_string(), Value::Null);
m.insert("status".to_string(), self.safe_string_k(transfer, "result", &[]));
m
});
Value::Null
}
pub fn parse_kraken_account_name(&self, mut account: Value) -> Value {
let mut accountByType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("main".to_string(), Value::Str("cash".into()));
m.insert("funding".to_string(), Value::Str("cash".into()));
m.insert("future".to_string(), Value::Str("cash".into()));
m.insert("futures".to_string(), Value::Str("cash".into()));
m.insert("cashAccount".to_string(), Value::Str("cash".into()));
m.insert("multiCollateralMarginAccount".to_string(), Value::Str("flex".into()));
m.insert("multiCollateral".to_string(), Value::Str("flex".into()));
m.insert("multiCollateralMargin".to_string(), Value::Str("flex".into()));
m
});
if (matches!((&accountByType, &account), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
return (if let (Some(__m), Some(__k)) = (accountByType.as_map(), account.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
} else if (self.markets.clone() != Value::Null) && (matches!((&self.markets, &account), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
let mut market: Value = self.market(account.clone());
let mut marketId: Value = self.safe_string_k(market.clone(), "id", &[Value::Str("".into())]);
let mut splitId: Value = Value::Array(if let Some(__s) = marketId.as_str() { __s.split("_").map(Value::from).collect() } else { Vec::new() });
let splitMarketId: String = self.safe_string_opt(splitId, Value::Int(1), &[Value::Str("".into())]).unwrap_or_default();
if matches!(self.safe_bool_k(market, "inverse", &[Value::Bool(false)]), Value::Bool(true)) {
return Value::Str(format!("{}{}", Value::Str("fi_".into()), splitMarketId).into());
} else {
return Value::Str(format!("{}{}", Value::Str("fv_".into()), splitMarketId).into());
}
} else {
return account;
}
Value::Null
}
pub async fn transfer_out(&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
}));
return self.transfer(code, amount, Value::Str("future".into()), Value::Str("spot".into()), &[params]).await;
Value::Null
}
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);
if (fromAccount.as_str() == Some("spot")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" transfer does not yet support transfers from spot".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), amount.clone());
m
});
let mut response: Value = Value::Null;
if (toAccount.as_str() == Some("spot")) {
if (self.parse_kraken_account_name(fromAccount.clone()).as_str() != Some("cash")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" transfer cannot transfer from ".into())).into()), fromAccount).into()), Value::Str(" to ".into())).into()), toAccount)));
}
request.insert("currency".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
let __ws_arg_20 = self.extend(Value::Map(request.clone()), &[params.clone()]);
response = self.private_post_withdrawal(&[__ws_arg_20]).await;
} else {
request.insert("fromAccount".into(), self.parse_kraken_account_name(fromAccount.clone()));
request.insert("toAccount".into(), self.parse_kraken_account_name(toAccount.clone()));
request.insert("unit".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
let __ws_arg_21 = self.extend(Value::Map(request), &[params]);
response = self.private_post_transfer(&[__ws_arg_21]).await;
}
let mut transfer: Value = self.parse_transfer(response, &[currency]);
return self.extend(transfer, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), amount);
m.insert("fromAccount".to_string(), fromAccount);
m.insert("toAccount".to_string(), toAccount);
m
})]);
Value::Null
}
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()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut marketIdUpper: Option<String> = self.safe_string_opt(self.market(symbol), Value::Str("id".into()), &[]);
if (marketIdUpper.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" marketId is required".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("maxLeverage".to_string(), leverage);
m.insert("symbol".to_string(), (if let Some(__s) = marketIdUpper.as_deref() { Value::Str(__s.to_uppercase().into()) } else { Value::Null }));
m
});
let __ws_arg_22 = self.extend(Value::Map(request), &[params]);
return self.private_put_leveragepreferences(&[__ws_arg_22]).await;
Value::Null
}
pub async fn fetch_leverages(&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 response: Value = self.private_get_leveragepreferences(&[params]).await;
let mut leveragePreferences: Value = self.safe_list_k(response, "leveragePreferences", &[Value::from(vec![])]);
return self.parse_leverages(leveragePreferences, &[symbols, Value::Str("symbol".into())]);
Value::Null
}
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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchLeverage() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marketIdUpper: Option<String> = self.safe_string_k_opt(market.clone(), "id", &[]);
if (marketIdUpper.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" marketId is required".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), (if let Some(__s) = marketIdUpper.as_deref() { Value::Str(__s.to_uppercase().into()) } else { Value::Null }));
m
});
let __ws_arg_23 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_get_leveragepreferences(&[__ws_arg_23]).await;
let mut leveragePreferences: Value = self.safe_list_k(response, "leveragePreferences", &[Value::from(vec![])]);
let mut data: Value = self.safe_dict(leveragePreferences, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
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: Option<String> = self.safe_string_k_opt(leverage.clone(), "symbol", &[]);
let mut leverageValue: Option<i64> = self.safe_integer_k(leverage.clone(), "maxLeverage", &[]).as_i64();
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), leverage);
m.insert("symbol".to_string(), self.safe_symbol(marketId.map(Value::from).unwrap_or(Value::Null), &[market]));
m.insert("marginMode".to_string(), Value::Null);
m.insert("longLeverage".to_string(), Value::from(leverageValue));
m.insert("shortLeverage".to_string(), Value::from(leverageValue));
m
});
Value::Null
}
pub fn handle_errors(&self, mut code: 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;
}
if (code.as_f64() == Some(429.0)) {
panic!("{}", crate::exchange_errors::d_do_s_protection(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body)));
}
let mut errors: Value = self.safe_list_k(response.clone(), "errors", &[]);
let mut firstError: Value = self.safe_dict(errors, Value::Int(0), &[]);
let mut firtErrorMessage: Option<String> = self.safe_string_k_opt(firstError, "message", &[]);
let mut message: Value = self.safe_string_k(response, "error", &[firtErrorMessage.map(Value::from).unwrap_or(Value::Null)]);
if (message == Value::Null) {
return Value::Null;
}
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), message.clone(), 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());
if (code.as_f64() == Some(400.0)) {
panic!("{}", crate::exchange_errors::bad_request(feedback));
}
panic!("{}", crate::exchange_errors::exchange_error(feedback));
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![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 __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiName: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut apiVersions: Value = self.safe_dict(self.options.as_map().and_then(|__m| __m.get("versions")).cloned().unwrap_or(Value::Null), apiName.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut methodVersions: Value = self.safe_dict(apiVersions, method.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultVersion: Value = self.safe_string(methodVersions, path.clone(), &[self.version.clone()]);
let mut version: Value = self.safe_string_k(params.clone(), "version", &[defaultVersion]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("version".into()), &[]);
let mut apiAccess: Value = self.safe_dict(self.options.as_map().and_then(|__m| __m.get("access")).cloned().unwrap_or(Value::Null), apiName.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut methodAccess: Value = self.safe_dict(apiAccess, method.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut access: Option<String> = self.safe_string(methodAccess, path.clone(), &[Value::Str("public".into())]).as_str().map(str::to_owned);
let mut endpoint: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", version, Value::Str("/".into())).into()), self.implode_params(path.clone(), paramsOmitted.clone())).into());
let mut paramsOmitted2: Value = self.omit(paramsOmitted, self.extract_params(path.clone()), &[]);
let mut query: Value = endpoint.clone();
let mut postData: Value = Value::Str("".into());
if (path.as_str() == Some("batchorder")) {
postData = Value::Str(format!("{}{}", Value::Str("json=".into()), json_stringify(¶msOmitted2)).into());
} else if ((Value::Array(paramsOmitted2.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).len() as i64) as f64) > ((0i64) as f64) {
if (matches!(¶msOmitted2, Value::Dict(__d) if __d.contains_key("orderIds"))) {
postData = self.urlencode_with_array_repeat(paramsOmitted2.clone());
} else {
postData = self.urlencode(paramsOmitted2, &[]);
}
query = Value::Str(format!("{}{}", query, Value::Str(format!("{}{}", Value::Str("?".into()), postData).into())).into());
}
let mut apiUrl: Option<String> = self.safe_string_opt(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), apiName.clone(), &[]);
if (apiUrl.is_none()) {
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!("{}{}", apiUrl.map(Value::from).unwrap_or(Value::Null), query).into());
let mut requestBody: Value = (if (path.as_str() == Some("batchorder")) { postData.clone() } else { Value::Null });
let mut privateHeaders: Value = Value::Null;
if (apiName.as_str() == Some("private")) || (access.as_deref() == Some("private")) {
self.check_required_credentials(&[]);
let mut auth: Value = Value::Str(format!("{}{}", postData, Value::Str("/api/".into())).into());
if (apiName.as_str() != Some("private")) {
auth = Value::Str(format!("{}{}", auth, Value::Str(format!("{}{}", apiName, Value::Str("/".into())).into())).into());
}
auth = Value::Str(format!("{}{}", auth, endpoint).into()); let mut hash: Value = self.hash(self.encode(auth), Value::Str("sha256".into()), &[Value::Str("binary".into())]); let mut secret: Value = self.base64_to_binary(self.secret.clone(), &[]); let mut signature: Value = self.hmac(hash, secret, Value::Str("sha512".into()), &[Value::Str("base64".into())]); privateHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("application/x-www-form-urlencoded".into()));
m.insert("Accept".to_string(), Value::Str("application/json".into()));
m.insert("APIKey".to_string(), self.apiKey.clone());
m.insert("Authent".to_string(), signature);
m
});
}
let mut requestHeaders: Value = privateHeaders;
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
}
}