// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
pub struct KrakenCore {
pub exchange: crate::exchange::Exchange,
}
impl KrakenCore {
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 = KrakenCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for KrakenCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_order(self, order, &[market])
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_position(self, position, &[market])
}
fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_deposit_address(self, depositAddress, &[currency])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_transfer(self, transfer, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_currency(self, currency)
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::parse_transaction(self, transaction, &[currency])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
#[allow(invalid_reference_casting)]
let me = unsafe { &mut *(self as *const KrakenCore as *mut KrakenCore) };
KrakenCore::sign(me, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on KrakenCore.
KrakenCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for KrakenCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"add_pagination_cursor_to_result" => self.add_pagination_cursor_to_result(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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_deposit_address" => self.create_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"create_market_order_with_cost" => self.create_market_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"create_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_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,
"fee_to_precision" => self.fee_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposit_address" => self.fetch_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposit_methods" => self.fetch_deposit_methods(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_ledger" => self.fetch_ledger(&args[..]).await,
"fetch_ledger_entries_by_ids" => self.fetch_ledger_entries_by_ids(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_ledger_entry" => self.fetch_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_order_trades" => self.fetch_order_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders_by_ids" => self.fetch_orders_by_ids(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_status" => self.fetch_status(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"find_market_by_altname_or_id" => self.find_market_by_altname_or_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"get_delisted_market_by_id" => self.get_delisted_market_by_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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)),
"nonce" => self.nonce(),
"order_request" => self.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.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]),
"parse_account_type" => self.parse_account_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_deposit_address" => self.parse_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ledger_entry" => self.parse_ledger_entry(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_order_book_bid_ask" => self.parse_order_book_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_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.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_transactions_by_type" => self.parse_transactions_by_type(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"resolve_market_by_altname_or_id" => self.resolve_market_by_altname_or_id(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"safe_currency_code" => self.safe_currency_code(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"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,
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for KrakenCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for KrakenCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl KrakenCore {
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("kraken".into()));
m.insert("name".to_string(), Value::Str("Kraken".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
m.insert("version".to_string(), Value::Str("0".into()));
m.insert("rateLimit".to_string(), Value::Int(1000));
m.insert("certified".to_string(), Value::Bool(false));
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(true));
m.insert("margin".to_string(), Value::Bool(true));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".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("createDepositAddress".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(true));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".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("createTrailingAmountOrder".to_string(), Value::Bool(true));
m.insert("createTrailingPercentOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
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(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(true));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(false));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRates".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLedgerEntry".to_string(), Value::Bool(true));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
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("fetchOrderTrades".to_string(), Value::Str("emulated".into()));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(true));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(false));
m.insert("setMarginMode".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Int(1));
m.insert("5m".to_string(), Value::Int(5));
m.insert("15m".to_string(), Value::Int(15));
m.insert("30m".to_string(), Value::Int(30));
m.insert("1h".to_string(), Value::Int(60));
m.insert("4h".to_string(), Value::Int(240));
m.insert("1d".to_string(), Value::Int(1440));
m.insert("1w".to_string(), Value::Int(10080));
m.insert("2w".to_string(), Value::Int(21600));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://user-images.githubusercontent.com/51840849/76173629-fc67fb00-61b1-11ea-84fe-f2de582f58a3.jpg".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api.kraken.com".into()));
m.insert("private".to_string(), Value::Str("https://api.kraken.com".into()));
m.insert("zendesk".to_string(), Value::Str("https://kraken.zendesk.com/api/v2/help_center/en-us/articles".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.kraken.com".into()));
m.insert("doc".to_string(), Value::Str("https://docs.kraken.com/api-reference/".into()));
m.insert("fees".to_string(), Value::Str("https://www.kraken.com/en-us/features/fee-schedule".into()));
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.0026".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0016".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.0026".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000".into()), &[]), self.parse_number(Value::Str("0.0024".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000".into()), &[]), self.parse_number(Value::Str("0.0022".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("250000".into()), &[]), self.parse_number(Value::Str("0.0020".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000".into()), &[]), self.parse_number(Value::Str("0.0018".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.0016".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("2500000".into()), &[]), self.parse_number(Value::Str("0.0014".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.0012".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".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.0016".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("50000".into()), &[]), self.parse_number(Value::Str("0.0014".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("100000".into()), &[]), self.parse_number(Value::Str("0.0012".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("250000".into()), &[]), self.parse_number(Value::Str("0.0010".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("500000".into()), &[]), self.parse_number(Value::Str("0.0008".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("1000000".into()), &[]), self.parse_number(Value::Str("0.0006".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("2500000".into()), &[]), self.parse_number(Value::Str("0.0004".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("5000000".into()), &[]), self.parse_number(Value::Str("0.0002".into()), &[])]), Value::from(vec![self.parse_number(Value::Str("10000000".into()), &[]), self.parse_number(Value::Str("0.0".into()), &[])])]));
m
}));
m
}));
m
}));
m.insert("handleContentTypeApplicationZip".to_string(), Value::Bool(true));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("zendesk".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("360000292886".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("201893608".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
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("Time".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("SystemStatus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("MaintenanceSchedule".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("Assets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("AssetPairs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("Ticker".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("OHLC".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.2));
m
}));
m.insert("Depth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.2));
m
}));
m.insert("GroupedBook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.2));
m
}));
m.insert("Trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.2));
m
}));
m.insert("Spread".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("PreTrade".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("PostTrade".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("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Level3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.2));
m
}));
m.insert("Balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("BalanceEx".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("CreditLines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("TradeBalance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("OpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("ClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("QueryOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("OrderAmends".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("TradesHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(6));
m
}));
m.insert("QueryTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("OpenPositions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("Ledgers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(6));
m
}));
m.insert("QueryLedgers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("TradeVolume".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("AddExport".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("ExportStatus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("RetrieveExport".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("RemoveExport".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("GetApiKeyInfo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("ListWalletAccounts".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("AddOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(0));
m
}));
m.insert("AmendOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(0));
m
}));
m.insert("CancelOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(0));
m
}));
m.insert("CancelAll".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("CancelAllOrdersAfter".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("GetWebSocketsToken".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("AddOrderBatch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(0));
m
}));
m.insert("CancelOrderBatch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(0));
m
}));
m.insert("EditOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(0));
m
}));
m.insert("DepositMethods".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("DepositAddresses".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("DepositStatus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("WithdrawMethods".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("WithdrawAddresses".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("WithdrawInfo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("Withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("WithdrawStatus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("WithdrawCancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("WalletTransfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("CreateSubaccount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("AccountTransfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("Earn/Allocate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("Earn/Deallocate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("Earn/AllocateStatus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("Earn/DeallocateStatus".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("Earn/Strategies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m.insert("Earn/Allocations".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(3));
m
}));
m
}));
m
}));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("LUNA".to_string(), Value::Str("LUNC".into()));
m.insert("LUNA2".to_string(), Value::Str("LUNA".into()));
m.insert("REPV2".to_string(), Value::Str("REP".into()));
m.insert("REP".to_string(), Value::Str("REPV1".into()));
m.insert("UST".to_string(), Value::Str("USTC".into()));
m.insert("XBT".to_string(), Value::Str("BTC".into()));
m.insert("XDG".to_string(), Value::Str("DOGE".into()));
m.insert("FEE".to_string(), Value::Str("KFEE".into()));
m.insert("XETC".to_string(), Value::Str("ETC".into()));
m.insert("XETH".to_string(), Value::Str("ETH".into()));
m.insert("XLTC".to_string(), Value::Str("LTC".into()));
m.insert("XMLN".to_string(), Value::Str("MLN".into()));
m.insert("XREP".to_string(), Value::Str("REP".into()));
m.insert("XXBT".to_string(), Value::Str("BTC".into()));
m.insert("XXDG".to_string(), Value::Str("DOGE".into()));
m.insert("XXLM".to_string(), Value::Str("XLM".into()));
m.insert("XXMR".to_string(), Value::Str("XMR".into()));
m.insert("XXRP".to_string(), Value::Str("XRP".into()));
m.insert("XZEC".to_string(), Value::Str("ZEC".into()));
m.insert("ZAUD".to_string(), Value::Str("AUD".into()));
m.insert("ZCAD".to_string(), Value::Str("CAD".into()));
m.insert("ZEUR".to_string(), Value::Str("EUR".into()));
m.insert("ZGBP".to_string(), Value::Str("GBP".into()));
m.insert("ZJPY".to_string(), Value::Str("JPY".into()));
m.insert("ZUSD".to_string(), Value::Str("USD".into()));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("mica".to_string(), Value::Bool(true));
m.insert("timeDifference".to_string(), Value::Int(0));
m.insert("adjustForTimeDifference".to_string(), Value::Bool(false));
m.insert("marketsByAltname".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("delistedMarketsById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("inactiveCurrencies".to_string(), Value::from(vec![Value::Str("CAD".into()), Value::Str("USD".into()), Value::Str("JPY".into()), Value::Str("GBP".into())]));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ETH".to_string(), Value::Str("ERC20".into()));
m.insert("TRX".to_string(), Value::Str("TRC20".into()));
m
}));
m.insert("depositMethods".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1INCH".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("1inch".into()), Value::Str(" ".into())).into()), Value::Str("(1INCH)".into())).into()));
m.insert("AAVE".to_string(), Value::Str("Aave".into()));
m.insert("ADA".to_string(), Value::Str("ADA".into()));
m.insert("ALGO".to_string(), Value::Str("Algorand".into()));
m.insert("ANKR".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("ANKR".into()), Value::Str(" ".into())).into()), Value::Str("(ANKR)".into())).into()));
m.insert("ANT".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Aragon".into()), Value::Str(" ".into())).into()), Value::Str("(ANT)".into())).into()));
m.insert("ATOM".to_string(), Value::Str("Cosmos".into()));
m.insert("AXS".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Axie Infinity Shards".into()), Value::Str(" ".into())).into()), Value::Str("(AXS)".into())).into()));
m.insert("BADGER".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Bager DAO".into()), Value::Str(" ".into())).into()), Value::Str("(BADGER)".into())).into()));
m.insert("BAL".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Balancer".into()), Value::Str(" ".into())).into()), Value::Str("(BAL)".into())).into()));
m.insert("BAND".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Band Protocol".into()), Value::Str(" ".into())).into()), Value::Str("(BAND)".into())).into()));
m.insert("BAT".to_string(), Value::Str("BAT".into()));
m.insert("BCH".to_string(), Value::Str("Bitcoin Cash".into()));
m.insert("BNC".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Bifrost".into()), Value::Str(" ".into())).into()), Value::Str("(BNC)".into())).into()));
m.insert("BNT".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Bancor".into()), Value::Str(" ".into())).into()), Value::Str("(BNT)".into())).into()));
m.insert("BTC".to_string(), Value::Str("Bitcoin".into()));
m.insert("CHZ".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Chiliz".into()), Value::Str(" ".into())).into()), Value::Str("(CHZ)".into())).into()));
m.insert("COMP".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Compound".into()), Value::Str(" ".into())).into()), Value::Str("(COMP)".into())).into()));
m.insert("CQT".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("\tCovalent Query Token".into()), Value::Str(" ".into())).into()), Value::Str("(CQT)".into())).into()));
m.insert("CRV".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Curve DAO Token".into()), Value::Str(" ".into())).into()), Value::Str("(CRV)".into())).into()));
m.insert("CTSI".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Cartesi".into()), Value::Str(" ".into())).into()), Value::Str("(CTSI)".into())).into()));
m.insert("DAI".to_string(), Value::Str("Dai".into()));
m.insert("DASH".to_string(), Value::Str("Dash".into()));
m.insert("DOGE".to_string(), Value::Str("Dogecoin".into()));
m.insert("DOT".to_string(), Value::Str("Polkadot".into()));
m.insert("DYDX".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("dYdX".into()), Value::Str(" ".into())).into()), Value::Str("(DYDX)".into())).into()));
m.insert("ENJ".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Enjin Coin".into()), Value::Str(" ".into())).into()), Value::Str("(ENJ)".into())).into()));
m.insert("EOS".to_string(), Value::Str("EOS".into()));
m.insert("ETC".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Ether Classic".into()), Value::Str(" ".into())).into()), Value::Str("(Hex)".into())).into()));
m.insert("ETH".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Ether".into()), Value::Str(" ".into())).into()), Value::Str("(Hex)".into())).into()));
m.insert("EWT".to_string(), Value::Str("Energy Web Token".into()));
m.insert("FEE".to_string(), Value::Str("Kraken Fee Credit".into()));
m.insert("FIL".to_string(), Value::Str("Filecoin".into()));
m.insert("FLOW".to_string(), Value::Str("Flow".into()));
m.insert("GHST".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Aavegotchi".into()), Value::Str(" ".into())).into()), Value::Str("(GHST)".into())).into()));
m.insert("GNO".to_string(), Value::Str("GNO".into()));
m.insert("GRT".to_string(), Value::Str("GRT".into()));
m.insert("ICX".to_string(), Value::Str("Icon".into()));
m.insert("INJ".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Injective Protocol".into()), Value::Str(" ".into())).into()), Value::Str("(INJ)".into())).into()));
m.insert("KAR".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Karura".into()), Value::Str(" ".into())).into()), Value::Str("(KAR)".into())).into()));
m.insert("KAVA".to_string(), Value::Str("Kava".into()));
m.insert("KEEP".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Keep Token".into()), Value::Str(" ".into())).into()), Value::Str("(KEEP)".into())).into()));
m.insert("KNC".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Kyber Network".into()), Value::Str(" ".into())).into()), Value::Str("(KNC)".into())).into()));
m.insert("KSM".to_string(), Value::Str("Kusama".into()));
m.insert("LINK".to_string(), Value::Str("Link".into()));
m.insert("LPT".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Livepeer Token".into()), Value::Str(" ".into())).into()), Value::Str("(LPT)".into())).into()));
m.insert("LRC".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Loopring".into()), Value::Str(" ".into())).into()), Value::Str("(LRC)".into())).into()));
m.insert("LSK".to_string(), Value::Str("Lisk".into()));
m.insert("LTC".to_string(), Value::Str("Litecoin".into()));
m.insert("MANA".to_string(), Value::Str("MANA".into()));
m.insert("MATIC".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Polygon".into()), Value::Str(" ".into())).into()), Value::Str("(MATIC)".into())).into()));
m.insert("MINA".to_string(), Value::Str("Mina".into()));
m.insert("MIR".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Mirror Protocol".into()), Value::Str(" ".into())).into()), Value::Str("(MIR)".into())).into()));
m.insert("MKR".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Maker".into()), Value::Str(" ".into())).into()), Value::Str("(MKR)".into())).into()));
m.insert("MLN".to_string(), Value::Str("MLN".into()));
m.insert("MOVR".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Moonriver".into()), Value::Str(" ".into())).into()), Value::Str("(MOVR)".into())).into()));
m.insert("NANO".to_string(), Value::Str("NANO".into()));
m.insert("OCEAN".to_string(), Value::Str("OCEAN".into()));
m.insert("OGN".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Origin Protocol".into()), Value::Str(" ".into())).into()), Value::Str("(OGN)".into())).into()));
m.insert("OMG".to_string(), Value::Str("OMG".into()));
m.insert("OXT".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Orchid".into()), Value::Str(" ".into())).into()), Value::Str("(OXT)".into())).into()));
m.insert("OXY".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Oxygen".into()), Value::Str(" ".into())).into()), Value::Str("(OXY)".into())).into()));
m.insert("PAXG".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("PAX".into()), Value::Str(" ".into())).into()), Value::Str("(Gold)".into())).into()));
m.insert("PERP".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Perpetual Protocol".into()), Value::Str(" ".into())).into()), Value::Str("(PERP)".into())).into()));
m.insert("PHA".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Phala".into()), Value::Str(" ".into())).into()), Value::Str("(PHA)".into())).into()));
m.insert("QTUM".to_string(), Value::Str("QTUM".into()));
m.insert("RARI".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Rarible".into()), Value::Str(" ".into())).into()), Value::Str("(RARI)".into())).into()));
m.insert("RAY".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Raydium".into()), Value::Str(" ".into())).into()), Value::Str("(RAY)".into())).into()));
m.insert("REN".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Ren Protocol".into()), Value::Str(" ".into())).into()), Value::Str("(REN)".into())).into()));
m.insert("REP".to_string(), Value::Str("REPv2".into()));
m.insert("REPV1".to_string(), Value::Str("REP".into()));
m.insert("SAND".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("The Sandbox".into()), Value::Str(" ".into())).into()), Value::Str("(SAND)".into())).into()));
m.insert("SC".to_string(), Value::Str("Siacoin".into()));
m.insert("SDN".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Shiden".into()), Value::Str(" ".into())).into()), Value::Str("(SDN)".into())).into()));
m.insert("SOL".to_string(), Value::Str("Solana".into()));
m.insert("SNX".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Synthetix Network".into()), Value::Str(" ".into())).into()), Value::Str("(SNX)".into())).into()));
m.insert("SRM".to_string(), Value::Str("Serum".into()));
m.insert("STORJ".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Storj".into()), Value::Str(" ".into())).into()), Value::Str("(STORJ)".into())).into()));
m.insert("SUSHI".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Sushiswap".into()), Value::Str(" ".into())).into()), Value::Str("(SUSHI)".into())).into()));
m.insert("TBTC".to_string(), Value::Str("tBTC".into()));
m.insert("TRX".to_string(), Value::Str("Tron".into()));
m.insert("UNI".to_string(), Value::Str("UNI".into()));
m.insert("USDC".to_string(), Value::Str("USDC".into()));
m.insert("USDT".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Tether USD".into()), Value::Str(" ".into())).into()), Value::Str("(ERC20)".into())).into()));
m.insert("USDT-TRC20".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Tether USD".into()), Value::Str(" ".into())).into()), Value::Str("(TRC20)".into())).into()));
m.insert("WAVES".to_string(), Value::Str("Waves".into()));
m.insert("WBTC".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Wrapped Bitcoin".into()), Value::Str(" ".into())).into()), Value::Str("(WBTC)".into())).into()));
m.insert("XLM".to_string(), Value::Str("Stellar XLM".into()));
m.insert("XMR".to_string(), Value::Str("Monero".into()));
m.insert("XRP".to_string(), Value::Str("Ripple XRP".into()));
m.insert("XTZ".to_string(), Value::Str("XTZ".into()));
m.insert("YFI".to_string(), Value::Str("YFI".into()));
m.insert("ZEC".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("Zcash".into()), Value::Str(" ".into())).into()), Value::Str("(Transparent)".into())).into()));
m.insert("ZRX".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), Value::Str(" ".into())).into()), Value::Str("(ZRX)".into())).into()));
m
}));
m.insert("withdrawMethods".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Lightning".to_string(), Value::Str("Lightning".into()));
m.insert("Bitcoin".to_string(), Value::Str("BTC".into()));
m.insert("Ripple".to_string(), Value::Str("XRP".into()));
m.insert("Litecoin".to_string(), Value::Str("LTC".into()));
m.insert("Dogecoin".to_string(), Value::Str("DOGE".into()));
m.insert("Stellar".to_string(), Value::Str("XLM".into()));
m.insert("Ethereum".to_string(), Value::Str("ERC20".into()));
m.insert("Arbitrum One".to_string(), Value::Str("Arbitrum".into()));
m.insert("Polygon".to_string(), Value::Str("MATIC".into()));
m.insert("Arbitrum Nova".to_string(), Value::Str("Arbitrum".into()));
m.insert("Optimism".to_string(), Value::Str("Optimism".into()));
m.insert("zkSync Era".to_string(), Value::Str("zkSync".into()));
m.insert("Ethereum Classic".to_string(), Value::Str("ETC".into()));
m.insert("Zcash".to_string(), Value::Str("ZEC".into()));
m.insert("Monero".to_string(), Value::Str("XMR".into()));
m.insert("Tron".to_string(), Value::Str("TRC20".into()));
m.insert("Solana".to_string(), Value::Str("SOL".into()));
m.insert("EOS".to_string(), Value::Str("EOS".into()));
m.insert("Bitcoin Cash".to_string(), Value::Str("BCH".into()));
m.insert("Cardano".to_string(), Value::Str("ADA".into()));
m.insert("Qtum".to_string(), Value::Str("QTUM".into()));
m.insert("Tezos".to_string(), Value::Str("XTZ".into()));
m.insert("Cosmos".to_string(), Value::Str("ATOM".into()));
m.insert("Nano".to_string(), Value::Str("NANO".into()));
m.insert("Siacoin".to_string(), Value::Str("SC".into()));
m.insert("Lisk".to_string(), Value::Str("LSK".into()));
m.insert("Waves".to_string(), Value::Str("WAVES".into()));
m.insert("ICON".to_string(), Value::Str("ICX".into()));
m.insert("Algorand".to_string(), Value::Str("ALGO".into()));
m.insert("Polygon - USDC.e".to_string(), Value::Str("MATIC".into()));
m.insert("Arbitrum One - USDC.e".to_string(), Value::Str("Arbitrum".into()));
m.insert("Polkadot".to_string(), Value::Str("DOT".into()));
m.insert("Kava".to_string(), Value::Str("KAVA".into()));
m.insert("Filecoin".to_string(), Value::Str("FIL".into()));
m.insert("Kusama".to_string(), Value::Str("KSM".into()));
m.insert("Flow".to_string(), Value::Str("FLOW".into()));
m.insert("Energy Web".to_string(), Value::Str("EW".into()));
m.insert("Mina".to_string(), Value::Str("MINA".into()));
m.insert("Centrifuge".to_string(), Value::Str("CFG".into()));
m.insert("Karura".to_string(), Value::Str("KAR".into()));
m.insert("Moonriver".to_string(), Value::Str("MOVR".into()));
m.insert("Shiden".to_string(), Value::Str("SDN".into()));
m.insert("Khala".to_string(), Value::Str("PHA".into()));
m.insert("Bifrost Kusama".to_string(), Value::Str("BNC".into()));
m.insert("Songbird".to_string(), Value::Str("SGB".into()));
m.insert("Terra classic".to_string(), Value::Str("LUNC".into()));
m.insert("KILT".to_string(), Value::Str("KILT".into()));
m.insert("Basilisk".to_string(), Value::Str("BSX".into()));
m.insert("Flare".to_string(), Value::Str("FLR".into()));
m.insert("Avalanche C-Chain".to_string(), Value::Str("AVAX".into()));
m.insert("Kintsugi".to_string(), Value::Str("KINT".into()));
m.insert("Altair".to_string(), Value::Str("AIR".into()));
m.insert("Moonbeam".to_string(), Value::Str("GLMR".into()));
m.insert("Acala".to_string(), Value::Str("ACA".into()));
m.insert("Astar".to_string(), Value::Str("ASTR".into()));
m.insert("Akash".to_string(), Value::Str("AKT".into()));
m.insert("Robonomics".to_string(), Value::Str("XRT".into()));
m.insert("Fantom".to_string(), Value::Str("FTM".into()));
m.insert("Elrond".to_string(), Value::Str("EGLD".into()));
m.insert("THORchain".to_string(), Value::Str("RUNE".into()));
m.insert("Secret".to_string(), Value::Str("SCRT".into()));
m.insert("Near".to_string(), Value::Str("NEAR".into()));
m.insert("Internet Computer Protocol".to_string(), Value::Str("ICP".into()));
m.insert("Picasso".to_string(), Value::Str("PICA".into()));
m.insert("Crust Shadow".to_string(), Value::Str("CSM".into()));
m.insert("Integritee".to_string(), Value::Str("TEER".into()));
m.insert("Parallel Finance".to_string(), Value::Str("PARA".into()));
m.insert("HydraDX".to_string(), Value::Str("HDX".into()));
m.insert("Interlay".to_string(), Value::Str("INTR".into()));
m.insert("Fetch.ai".to_string(), Value::Str("FET".into()));
m.insert("NYM".to_string(), Value::Str("NYM".into()));
m.insert("Terra 2.0".to_string(), Value::Str("LUNA2".into()));
m.insert("Juno".to_string(), Value::Str("JUNO".into()));
m.insert("Nodle".to_string(), Value::Str("NODL".into()));
m.insert("Stacks".to_string(), Value::Str("STX".into()));
m.insert("Ethereum PoW".to_string(), Value::Str("ETHW".into()));
m.insert("Aptos".to_string(), Value::Str("APT".into()));
m.insert("Sui".to_string(), Value::Str("SUI".into()));
m.insert("Genshiro".to_string(), Value::Str("GENS".into()));
m.insert("Aventus".to_string(), Value::Str("AVT".into()));
m.insert("Sei".to_string(), Value::Str("SEI".into()));
m.insert("OriginTrail".to_string(), Value::Str("OTP".into()));
m.insert("Celestia".to_string(), Value::Str("TIA".into()));
m
}));
m.insert("marketHelperProps".to_string(), Value::from(vec![Value::Str("marketsByAltname".into()), Value::Str("delistedMarketsById".into())]));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(false));
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(false));
m.insert("triggerPriceType".to_string(), Value::Null);
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(true));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(true));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(true));
m.insert("iceberg".to_string(), Value::Bool(true));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(2));
m.insert("max".to_string(), Value::Int(15));
m.insert("sameSymbolOnly".to_string(), Value::Bool(true));
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::Null);
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::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::Int(100000));
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(720));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("rollingWindowSize".to_string(), Value::Int(10000));
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("EQuery:Invalid asset pair".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("EAPI:Invalid key".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("EFunding:Unknown withdraw key".to_string(), Value::Str("InvalidAddress".into()).clone());
m.insert("EFunding:Invalid amount".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("EService:Unavailable".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("EDatabase:Internal error".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("EService:Busy".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("EQuery:Unknown asset".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("EAPI:Rate limit exceeded".to_string(), Value::Str("DDoSProtection".into()).clone());
m.insert("EOrder:Rate limit exceeded".to_string(), Value::Str("DDoSProtection".into()).clone());
m.insert("EGeneral:Internal error".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("EGeneral:Temporary lockout".to_string(), Value::Str("DDoSProtection".into()).clone());
m.insert("EGeneral:Permission denied".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("EGeneral:Invalid arguments:price".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("EOrder:Unknown order".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("EOrder:Invalid price:Invalid price argument".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("EOrder:Order minimum not met".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("EOrder:Insufficient funds".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("EGeneral:Invalid arguments".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("ESession:Invalid session".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("EAPI:Invalid nonce".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("EFunding:No funding method".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("EFunding:Unknown asset".to_string(), Value::Str("BadSymbol".into()).clone());
m.insert("EService:Market in post_only mode".to_string(), Value::Str("OnMaintenance".into()).clone());
m.insert("EService:Market in cancel_only mode".to_string(), Value::Str("OnMaintenance".into()).clone());
m.insert("EGeneral:Too many requests".to_string(), Value::Str("DDoSProtection".into()).clone());
m.insert("ETrade:User Locked".to_string(), Value::Str("AccountSuspended".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert(":Invalid order".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert(":Invalid arguments:volume".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert(":Invalid arguments:viqc".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert(":Invalid nonce".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert(":IInsufficient funds".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert(":Cancel pending".to_string(), Value::Str("CancelPending".into()).clone());
m.insert(":Rate limit exceeded".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m
}));
m
}));
m
})]);
Value::Null
}
pub fn fee_to_precision(&self, mut symbol: Value, mut fee: Value) -> Value {
return self.decimal_to_precision(fee, Value::Int(crate::runtime::TRUNCATE), self.market(symbol).as_map().and_then(|__m| __m.get("precision")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("amount")).cloned().unwrap_or(Value::Null), &[self.precisionMode.clone()]);
Value::Null
}
/*
* @method
* @name kraken#fetchMarkets
* @description retrieves data on all markets for kraken
* @see https://docs.kraken.com/api-reference/market-data/get-tradable-asset-pairs
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut promises: Value = Value::from(vec![]);
append_to_array(&mut promises, self.public_get_asset_pairs(&[params]).await);
if matches!(self.safe_bool_k(self.options.clone(), "adjustForTimeDifference", &[Value::Bool(false)]), Value::Bool(true)) {
append_to_array(&mut promises, self.load_time_difference(&[]).await);
}
let mut responses: Value = promise_all(&promises).await;
let mut assetsResponse: Value = self.safe_dict(responses, Value::Int(0), &[]);
//
// {
// "error": [],
// "result": {
// "ADAETH": {
// "altname": "ADAETH",
// "wsname": "ADA\/ETH",
// "aclass_base": "currency",
// "base": "ADA",
// "aclass_quote": "currency",
// "quote": "XETH",
// "lot": "unit",
// "pair_decimals": 7,
// "lot_decimals": 8,
// "lot_multiplier": 1,
// "leverage_buy": [],
// "leverage_sell": [],
// "fees": [
// [0, 0.26],
// [50000, 0.24],
// [100000, 0.22],
// [250000, 0.2],
// [500000, 0.18],
// [1000000, 0.16],
// [2500000, 0.14],
// [5000000, 0.12],
// [10000000, 0.1]
// ],
// "fees_maker": [
// [0, 0.16],
// [50000, 0.14],
// [100000, 0.12],
// [250000, 0.1],
// [500000, 0.08],
// [1000000, 0.06],
// [2500000, 0.04],
// [5000000, 0.02],
// [10000000, 0]
// ],
// "fee_volume_currency": "ZUSD",
// "margin_call": 80,
// "margin_stop": 40,
// "ordermin": "1"
// },
// }
// }
//
let mut markets: Value = self.safe_dict_k(assetsResponse, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut cachedCurrencies: Value = self.safe_dict_k(self.options.clone(), "cachedCurrencies", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut keys: Value = object_keys(&markets);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_827: bool = true;
while { if !__for_first_827 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_827 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut id: Value = keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut isSynthetic: bool = false;
if Value::Int(id.as_str().and_then(|__s| __s.find(":BTNL")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
isSynthetic = true;
}
let mut market: Value = markets.as_map().and_then(|__m| id.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
let mut baseIdRaw: Value = self.safe_string_k(market.clone(), "base", &[]);
let mut quoteIdRaw: Value = self.safe_string_k(market.clone(), "quote", &[]);
let mut baseId: Value = self.safe_currency_code(baseIdRaw, &[]);
let mut quoteId: Value = self.safe_currency_code(quoteIdRaw, &[]);
let mut base: Value = baseId.clone();
let mut quote: Value = quoteId.clone();
if (base == Value::Null) || (quote == Value::Null) {
continue;
}
let mut makerFees: Value = self.safe_list_k(market.clone(), "fees_maker", &[Value::from(vec![])]);
let mut firstMakerFee: Value = self.safe_list(makerFees, Value::Int(0), &[Value::from(vec![])]);
let mut firstMakerFeeRate: Value = self.safe_string(firstMakerFee, Value::Int(1), &[]);
let mut maker: Value = Value::Null;
if (firstMakerFeeRate != Value::Null) {
maker = self.parse_number(crate::precise::Precise::stringDiv(&firstMakerFeeRate, &Value::Str("100".into())), &[]);
}
let mut takerFees: Value = self.safe_list_k(market.clone(), "fees", &[Value::from(vec![])]);
let mut firstTakerFee: Value = self.safe_list(takerFees, Value::Int(0), &[Value::from(vec![])]);
let mut firstTakerFeeRate: Value = self.safe_string(firstTakerFee, Value::Int(1), &[]);
let mut taker: Value = Value::Null;
if (firstTakerFeeRate != Value::Null) {
taker = self.parse_number(crate::precise::Precise::stringDiv(&firstTakerFeeRate, &Value::Str("100".into())), &[]);
}
let mut leverageBuy: Value = self.safe_list_k(market.clone(), "leverage_buy", &[Value::from(vec![])]);
let mut leverageBuyLength: Value = Value::Int(leverageBuy.len() as i64);
let mut precisionPrice: Value = self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "pair_decimals", &[])]), &[]);
let mut precisionAmount: Value = self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "lot_decimals", &[])]), &[]);
let mut spot: Value = Value::Bool(true);
// fix https://github.com/freqtrade/freqtrade/issues/11765#issuecomment-2894224103
if matches!(&spot, Value::Bool(true)) && (in_op(&cachedCurrencies, &base)) {
let mut currency: Value = self.safe_dict(cachedCurrencies.clone(), base.clone(), &[]);
let mut currencyPrecision: Value = self.safe_number_k(currency, "precision", &[]);
// if currency precision is greater (e.g. 0.01) than market precision (e.g. 0.001)
if (currencyPrecision == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" method() missing currencyPrecision".into()))));
}
if currencyPrecision.as_f64().unwrap_or(f64::NAN) > precisionAmount.as_f64().unwrap_or(f64::NAN) {
precisionAmount = currencyPrecision;
}
}
let mut status: Option<String> = self.safe_string_k(market.clone(), "status", &[]).as_str().map(str::to_owned);
let mut isActive: Value = Value::Bool(status.as_deref() == Some("online"));
let mut symbol: Value = id.clone();
if !isSynthetic {
symbol = (Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into()));
}
append_to_array(&mut result, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("wsId".to_string(), self.safe_string_k(market.clone(), "wsname", &[]));
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), Value::Null);
m.insert("altname".to_string(), crate::value::get_value_k(&market, "altname"));
m.insert("type".to_string(), Value::Str("spot".into()));
m.insert("spot".to_string(), spot);
m.insert("margin".to_string(), (Value::Bool(leverageBuyLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64))));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), isActive);
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("taker".to_string(), taker);
m.insert("maker".to_string(), maker);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
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(), precisionAmount);
m.insert("price".to_string(), precisionPrice);
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(), self.parse_number(Value::Str("1".into()), &[]));
m.insert("max".to_string(), self.safe_number(leverageBuy, (match (&(leverageBuyLength), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &[Value::Int(1)]));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(market.clone(), "ordermin", &[]));
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(), self.safe_number_k(market.clone(), "costmin", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market);
m
}));
}
}
{ let __be_tmp = self.index_by(result.clone(), Value::Str("altname".into())); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("marketsByAltname".into(), __be_tmp); } }
return result;
Value::Null
}
/*
* @method
* @name kraken#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://docs.kraken.com/api-reference/market-data/get-system-status
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/?id=exchange-status-structure}
*/
pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_system_status(&[params]).await;
//
// {
// error: [],
// result: { status: 'online', timestamp: '2024-07-22T16:34:44Z' }
// }
//
let mut result: Value = self.safe_dict_k(response.clone(), "result", &[]);
let mut statusRaw: Option<String> = self.safe_string_k(result, "status", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if (statusRaw.as_deref() == Some("online")) { Value::Str("ok".into()) } else { Value::Str("maintenance".into()) }));
m.insert("updated".to_string(), Value::Null);
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
/*
* @method
* @name kraken#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://docs.kraken.com/api-reference/market-data/get-asset-info
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_assets(&[params]).await;
//
// {
// "error": [],
// "result": {
// "ATOM": {
// "aclass": "currency",
// "altname": "ATOM",
// "collateral_value": "0.7",
// "decimals": 8,
// "display_decimals": 6,
// "margin_rate": 0.02,
// "status": "enabled",
// },
// "ATOM.S": {
// "aclass": "currency",
// "altname": "ATOM.S",
// "decimals": 8,
// "display_decimals": 6,
// "status": "enabled",
// },
// "XXBT": {
// "aclass": "currency",
// "altname": "XBT",
// "decimals": 10,
// "display_decimals": 5,
// "margin_rate": 0.01,
// "status": "enabled",
// },
// "XETH": {
// "aclass": "currency",
// "altname": "ETH",
// "decimals": 10,
// "display_decimals": 5
// "margin_rate": 0.02,
// "status": "enabled",
// },
// "XBT.M": {
// "aclass": "currency",
// "altname": "XBT.M",
// "decimals": 10,
// "display_decimals": 5
// "status": "enabled",
// },
// "ETH.M": {
// "aclass": "currency",
// "altname": "ETH.M",
// "decimals": 10,
// "display_decimals": 5
// "status": "enabled",
// },
// ...
// },
// }
//
let mut currencies: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut enhancedArray: Value = self.add_key_in_array_items(currencies, Value::Str("_coin_id".into()));
return self.parse_currencies(enhancedArray);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
// todo: will need to rethink the fees
// see: https://support.kraken.com/hc/en-us/articles/201893608-What-are-the-withdrawal-fees-
// to add support for multiple withdrawal/deposit methods and
// differentiated fees for each particular method
//
// Notes about abbreviations:
// Z and X prefixes: https://support.kraken.com/hc/en-us/articles/360001206766-Bitcoin-currency-code-XBT-vs-BTC
// S and M suffixes: https://support.kraken.com/hc/en-us/articles/360039879471-What-is-Asset-S-and-Asset-M-
//
let mut id: Value = self.safe_string_k(rawCurrency.clone(), "_coin_id", &[]);
let mut code: Value = self.safe_currency_code(id.clone(), &[]);
// the below cannot be reliably done in `safeCurrencyCode`, so we have to do it here
if (id == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" parseCurrency() missing id".into()))));
}
if Value::Int(id.as_str().and_then(|__s| __s.find(".")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
let mut altName: Value = self.safe_string_k(rawCurrency.clone(), "altname", &[]);
// handle cases like below:
//
// id | altname
// ---------------
// XXBT | XBT
// ZUSD | USD
if (id == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" parseCurrency() missing id".into()))));
}
if (id.as_str() != altName.as_str()) && ((starts_with(&id, &Value::Str("X".into()))) || (starts_with(&id, &Value::Str("Z".into())))) {
code = self.safe_currency_code(altName, &[]);
// also, add map in commonCurrencies:
if (id != Value::Null) && (code != Value::Null) {
if let Value::Dict(__d) = &mut self.commonCurrencies.clone() { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&id), code.clone()); }
}
} else {
code = self.safe_currency_code(id.clone(), &[]);
}
}
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" parseCurrency() missing code".into()))));
}
let mut isFiat: bool = Value::Int(code.as_str().and_then(|__s| __s.find(".HOLD")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64);
let mut rawCurrencyOmitted: Value = self.omit(rawCurrency, Value::Str("_coin_id".into()), &[]);
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("code".to_string(), code);
m.insert("info".to_string(), rawCurrencyOmitted.clone());
m.insert("name".to_string(), self.safe_string_k(rawCurrencyOmitted.clone(), "altname", &[]));
m.insert("active".to_string(), Value::Bool(self.safe_string_k(rawCurrencyOmitted.clone(), "status", &[]).as_str() == Some("enabled")));
m.insert("type".to_string(), (if isFiat { Value::Str("fiat".into()) } else { Value::Str("crypto".into()) }));
m.insert("deposit".to_string(), Value::Null);
m.insert("withdraw".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("precision".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(rawCurrencyOmitted, "decimals", &[])]), &[]));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
Value::Null
}
pub fn safe_currency_code(&self, mut currencyId: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
if (currencyId == Value::Null) {
return currencyId;
}
if Value::Int(currencyId.as_str().and_then(|__s| __s.find(".")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
// if ID contains .M, .S or .F, then it can't contain X or Z prefix. in such case, ID equals to ALTNAME
let mut parts: Value = split(¤cyId, &Value::Str(".".into()));
let mut firstPart: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
let mut secondPart: Value = self.safe_string(parts, Value::Int(1), &[]);
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.super_safe_currency_code(firstPart, currency.clone()), Value::Str(".".into())).into()), secondPart).into());
}
return self.super_safe_currency_code(currencyId, currency);
Value::Null
}
/*
* @method
* @name kraken#fetchTradingFee
* @description fetch the trading fees for a market
* @see https://docs.kraken.com/api-reference/account-data/get-trade-volume
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [fee structure]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_trading_fee(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("fee-info".to_string(), Value::Bool(true));
m
});
let __ws_arg_0 = self.extend(request, &[params]);
let mut response: Value = self.private_post_trade_volume(&[__ws_arg_0]).await;
//
// {
// "error": [],
// "result": {
// "currency": 'ZUSD',
// "volume": '0.0000',
// "fees": {
// "XXBTZUSD": {
// "fee": '0.2600',
// "minfee": '0.1000',
// "maxfee": '0.2600',
// "nextfee": '0.2400',
// "tiervolume": '0.0000',
// "nextvolume": '50000.0000'
// }
// },
// "fees_maker": {
// "XXBTZUSD": {
// "fee": '0.1600',
// "minfee": '0.0000',
// "maxfee": '0.1600',
// "nextfee": '0.1400',
// "tiervolume": '0.0000',
// "nextvolume": '50000.0000'
// }
// }
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_trading_fee(result, market);
Value::Null
}
pub fn parse_trading_fee(&self, mut fee: Value, mut market: Value) -> Value {
let mut makerFees: Value = self.safe_dict_k(fee.clone(), "fees_maker", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut takerFees: Value = self.safe_dict_k(fee.clone(), "fees", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut symbolMakerFee: Value = self.safe_dict(makerFees, market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut symbolTakerFee: Value = self.safe_dict(takerFees, market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee);
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("maker".to_string(), self.parse_number(crate::precise::Precise::stringDiv(&self.safe_string_k(symbolMakerFee, "fee", &[]), &Value::Str("100".into())), &[]));
m.insert("taker".to_string(), self.parse_number(crate::precise::Precise::stringDiv(&self.safe_string_k(symbolTakerFee, "fee", &[]), &Value::Str("100".into())), &[]));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(true));
m
});
Value::Null
}
pub fn parse_order_book_bid_ask(&self, mut bidask: Value, optional_args: &[Value]) -> Value {
let mut priceKey = get_arg(optional_args, 0, Value::Int(0));
let mut amountKey = get_arg(optional_args, 1, Value::Int(1));
let mut countOrIdKey = get_arg(optional_args, 2, Value::Int(2));
let mut price: Value = self.safe_number(bidask.clone(), priceKey, &[]);
let mut amount: Value = self.safe_number(bidask.clone(), amountKey, &[]);
let mut timestamp: Value = self.safe_integer(bidask, Value::Int(2), &[]);
return Value::from(vec![price, amount, timestamp]);
Value::Null
}
/*
* @method
* @name kraken#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.kraken.com/api-reference/market-data/get-order-book
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
*/
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("count".into(), limit); }; // 100
}
let __ws_arg_1 = self.extend(request, &[params]);
let mut response: Value = self.public_get_depth(&[__ws_arg_1]).await;
//
// {
// "error":[],
// "result":{
// "XETHXXBT":{
// "asks":[
// ["0.023480","4.000",1586321307],
// ["0.023490","50.095",1586321306],
// ["0.023500","28.535",1586321302],
// ],
// "bids":[
// ["0.023470","59.580",1586321307],
// ["0.023460","20.000",1586321301],
// ["0.023440","67.832",1586321306],
// ]
// }
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderbook: Value = self.safe_dict(result.clone(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null), &[]);
// sometimes kraken returns wsname instead of market id
// https://github.com/ccxt/ccxt/issues/8662
let mut marketInfo: Value = self.safe_dict_k(market, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut wsName: Value = self.safe_string_k(marketInfo, "wsname", &[]);
if (wsName != Value::Null) {
orderbook = self.safe_dict(result, wsName, &[orderbook.clone()]);
}
return self.parse_order_book(orderbook, symbol, &[]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "a":["2432.77000","1","1.000"],
// "b":["2431.37000","2","2.000"],
// "c":["2430.58000","0.04408910"],
// "v":["4147.94474901","8896.96086304"],
// "p":["2456.22239","2568.63032"],
// "t":[3907,10056],
// "l":["2302.18000","2302.18000"],
// "h":["2621.14000","2860.01000"],
// "o":"2571.56000"
// }
//
let mut symbol: Value = self.safe_symbol(Value::Null, &[market.clone()]);
let mut v: Value = self.safe_list_k(ticker.clone(), "v", &[Value::from(vec![])]);
let mut baseVolume: Value = self.safe_string(v, Value::Int(1), &[]);
let mut p: Value = self.safe_list_k(ticker.clone(), "p", &[Value::from(vec![])]);
let mut vwap: Value = self.safe_string(p, Value::Int(1), &[]);
let mut quoteVolume: Value = crate::precise::Precise::stringMul(&baseVolume, &vwap);
let mut c: Value = self.safe_list_k(ticker.clone(), "c", &[Value::from(vec![])]);
let mut last: Value = self.safe_string(c, Value::Int(0), &[]);
let mut high: Value = self.safe_list_k(ticker.clone(), "h", &[Value::from(vec![])]);
let mut low: Value = self.safe_list_k(ticker.clone(), "l", &[Value::from(vec![])]);
let mut bid: Value = self.safe_list_k(ticker.clone(), "b", &[Value::from(vec![])]);
let mut ask: Value = self.safe_list_k(ticker.clone(), "a", &[Value::from(vec![])]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("high".to_string(), self.safe_string(high, Value::Int(1), &[]));
m.insert("low".to_string(), self.safe_string(low, Value::Int(1), &[]));
m.insert("bid".to_string(), self.safe_string(bid.clone(), Value::Int(0), &[]));
m.insert("bidVolume".to_string(), self.safe_string(bid, Value::Int(2), &[]));
m.insert("ask".to_string(), self.safe_string(ask.clone(), Value::Int(0), &[]));
m.insert("askVolume".to_string(), self.safe_string(ask, Value::Int(2), &[]));
m.insert("vwap".to_string(), vwap);
m.insert("open".to_string(), self.safe_string_k(ticker.clone(), "o", &[]));
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), baseVolume);
m.insert("quoteVolume".to_string(), quoteVolume);
m.insert("info".to_string(), ticker);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name kraken#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://docs.kraken.com/api-reference/market-data/get-ticker-information
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
if (symbolsNormalized != Value::Null) {
let mut marketIds: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_828: bool = true;
while { if !__for_first_828 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_828 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsNormalized.len() as i64) as f64) } {
let mut symbol: Value = symbolsNormalized.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("active")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
append_to_array(&mut marketIds, market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
}
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("pair".into(), join(&marketIds, &Value::Str(",".into()))); }
}
let __ws_arg_2 = self.extend(request, &[params]);
let mut response: Value = self.public_get_ticker(&[__ws_arg_2]).await;
let mut tickers: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ids: Value = object_keys(&tickers);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: Value = Value::Int(0);
let mut __for_first_829: bool = true;
while { if !__for_first_829 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_829 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
let mut id: Value = ids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut market: Value = self.safe_market(&[id.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut ticker: Value = tickers.as_map().and_then(|__m| id.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), self.parse_ticker(ticker, &[market])); }
}
}
return self.filter_by_array_tickers(result, Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
/*
* @method
* @name kraken#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://docs.kraken.com/api-reference/market-data/get-ticker-information
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_3 = self.extend(request, &[params]);
let mut response: Value = self.public_get_ticker(&[__ws_arg_3]).await;
let mut tickerResult: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ticker: Value = self.safe_value(tickerResult, market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null), &[]);
return self.parse_ticker(ticker, &[market]);
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_timestamp(ohlcv.clone(), Value::Int(0), &[]), self.safe_number(ohlcv.clone(), Value::Int(1), &[]), self.safe_number(ohlcv.clone(), Value::Int(2), &[]), self.safe_number(ohlcv.clone(), Value::Int(3), &[]), self.safe_number(ohlcv.clone(), Value::Int(4), &[]), self.safe_number(ohlcv, Value::Int(6), &[])]);
Value::Null
}
/*
* @method
* @name kraken#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.kraken.com/api-reference/market-data/get-ohlc-data
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchOHLCV".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".into()), &[symbol.clone(), since.clone(), limit.clone(), timeframe.clone(), paramsPaginate.clone(), Value::Int(720)]).await;
}
let mut market: Value = self.market(symbol);
let mut parsedTimeframe: Value = self.safe_integer(self.timeframes.clone(), timeframe.clone(), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (parsedTimeframe != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("interval".into(), parsedTimeframe.clone()); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("interval".into(), timeframe.clone()); }
}
if (since != Value::Null) {
let mut scaledSince: 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 }));
if (parsedTimeframe == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() missing parsedTimeframe".into()))));
}
let mut timeFrameInSeconds: Value = (match (&(parsedTimeframe), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("since".into(), self.number_to_string((match (&(scaledSince), &(timeFrameInSeconds)) { (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 }))); }; // expected to be in seconds
}
let __ws_arg_4 = self.extend(request, &[paramsPaginate]);
let mut response: Value = self.public_get_ohlc(&[__ws_arg_4]).await;
//
// {
// "error":[],
// "result":{
// "XETHXXBT":[
// [1591475580,"0.02499","0.02499","0.02499","0.02499","0.00000","0.00000000",0],
// [1591475640,"0.02500","0.02500","0.02500","0.02500","0.02500","9.12201000",5],
// [1591475700,"0.02499","0.02499","0.02499","0.02499","0.02499","1.28681415",2],
// [1591475760,"0.02499","0.02499","0.02499","0.02499","0.02499","0.08800000",1],
// ],
// "last":1591517580
// }
// }
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ohlcvs: Value = self.safe_list(result, market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null), &[Value::from(vec![])]);
return self.parse_ohlc_vs(ohlcvs, &[market, timeframe, since, limit]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade".to_string(), Value::Str("trade".into()));
m.insert("withdrawal".to_string(), Value::Str("transaction".into()));
m.insert("deposit".to_string(), Value::Str("transaction".into()));
m.insert("transfer".to_string(), Value::Str("transfer".into()));
m.insert("margin".to_string(), Value::Str("margin".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// 'LTFK7F-N2CUX-PNY4SX': {
// "refid": "TSJTGT-DT7WN-GPPQMJ",
// "time": 1520102320.555,
// "type": "trade",
// "aclass": "currency",
// "asset": "XETH",
// "amount": "0.1087194600",
// "fee": "0.0000000000",
// "balance": "0.2855851000"
// },
// ...
// }
//
let mut id: Value = self.safe_string_k(item.clone(), "id", &[]);
let mut direction: Value = Value::Null;
let mut account: Value = Value::Null;
let mut referenceId: Value = self.safe_string_k(item.clone(), "refid", &[]);
let mut referenceAccount: Value = Value::Null;
let mut type_var: Value = self.parse_ledger_entry_type(self.safe_string_k(item.clone(), "type", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
let mut currencyId: Value = self.safe_string_k(item.clone(), "asset", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
let mut currencyResolved: Value = self.safe_currency(currencyId, &[currency]);
let mut amount: Value = self.safe_string_k(item.clone(), "amount", &[]);
if is_true(&crate::precise::Precise::stringLt(&amount, &Value::Str("0".into()))) {
direction = Value::Str("out".into());
amount = crate::precise::Precise::stringAbs(&amount);
} else {
direction = Value::Str("in".into());
}
let mut timestamp: Value = self.safe_integer_product_k(item.clone(), "time", Value::Int(1000), &[]);
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(), id);
m.insert("direction".to_string(), direction);
m.insert("account".to_string(), account);
m.insert("referenceId".to_string(), referenceId);
m.insert("referenceAccount".to_string(), referenceAccount);
m.insert("type".to_string(), type_var);
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), self.safe_number_k(item.clone(), "balance", &[]));
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.safe_number_k(item, "fee", &[]));
m.insert("currency".to_string(), code);
m
}));
m
}), &[currencyResolved]);
Value::Null
}
/*
* @method
* @name kraken#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
* @see https://docs.kraken.com/api-reference/account-data/get-ledgers-info
* @param {string} [code] unified currency code, default is undefined
* @param {int} [since] timestamp in ms of the earliest ledger entry, default is undefined
* @param {int} [limit] max number of ledger entries to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest ledger entry
* @param {int} [params.end] timestamp in seconds of the latest ledger entry
* @returns {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
*/
pub async fn fetch_ledger(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// https://www.kraken.com/features/api#get-ledgers-info
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("asset".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), 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 }))); }
}
let mut until: Value = self.safe_string2(params.clone(), Value::Str("until".into()), Value::Str("till".into()), &[]);
let mut paramsOmitted: Value = (if (until != Value::Null) { self.omit(params.clone(), Value::from(vec![Value::Str("until".into()), Value::Str("till".into())]), &[]) } else { params });
if (until != Value::Null) {
let mut untilDivided: Value = crate::precise::Precise::stringDiv(&until, &Value::Str("1000".into()));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), self.parse_to_int(crate::precise::Precise::stringAdd(&untilDivided, &Value::Str("1".into())))); }
}
let __ws_arg_5 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_ledgers(&[__ws_arg_5]).await;
// { error: [],
// "result": { ledger: { 'LPUAIB-TS774-UKHP7X': { refid: "A2B4HBV-L4MDIE-JU4N3N",
// "time": 1520103488.314,
// "type": "withdrawal",
// "aclass": "currency",
// "asset": "XETH",
// "amount": "-0.2805800000",
// "fee": "0.0050000000",
// "balance": "0.0000051000" },
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ledger: Value = self.safe_dict_k(result, "ledger", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut keys: Value = object_keys(&ledger);
let mut items: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_830: bool = true;
while { if !__for_first_830 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_830 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut key: Value = keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut value: Value = get_value(&ledger, &key);
add_element_to_object(&mut value, &Value::Str("id".into()), key.clone());
crate::set_value(&mut ledger, &key, value.clone());
append_to_array(&mut items, value);
}
}
return self.parse_ledger(items, &[currency, since, limit]);
Value::Null
}
pub async fn fetch_ledger_entries_by_ids(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// https://www.kraken.com/features/api#query-ledgers
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut idsValue: Value = join(&ids, &Value::Str(",".into()));
let mut request: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), idsValue);
m
}), &[params]);
let mut response: Value = self.private_post_query_ledgers(&[request]).await;
// { error: [],
// "result": { 'LPUAIB-TS774-UKHP7X': { refid: "A2B4HBV-L4MDIE-JU4N3N",
// "time": 1520103488.314,
// "type": "withdrawal",
// "aclass": "currency",
// "asset": "XETH",
// "amount": "-0.2805800000",
// "fee": "0.0050000000",
// "balance": "0.0000051000" } } }
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut keys: Value = object_keys(&result);
let mut items: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_831: bool = true;
while { if !__for_first_831 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_831 = false; i.as_f64().unwrap_or(f64::NAN) < ((keys.len() as i64) as f64) } {
let mut key: Value = keys.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut value: Value = get_value(&result, &key);
add_element_to_object(&mut value, &Value::Str("id".into()), key.clone());
crate::set_value(&mut result, &key, value.clone());
append_to_array(&mut items, value);
}
}
return self.parse_ledger(items, &[]);
Value::Null
}
pub async fn fetch_ledger_entry(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut items: Value = self.fetch_ledger_entries_by_ids(Value::from(vec![id]), &[code, params]).await;
let mut entry: Value = self.safe_dict(items, Value::Int(0), &[]);
return entry;
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchTrades (public)
//
// [
// "0.032310", // price
// "4.28169434", // amount
// 1541390792.763, // timestamp
// "s", // sell or buy
// "l", // limit or market
// ""
// ]
//
// fetchOrderTrades (private)
//
// {
// "id": 'TIMIRG-WUNNE-RRJ6GT', // injected from outside
// "ordertxid": 'OQRPN2-LRHFY-HIFA7D',
// "postxid": 'TKH2SE-M7IF5-CFI7LT',
// "pair": 'USDCUSDT',
// "time": 1586340086.457,
// "type": 'sell',
// "ordertype": 'market',
// "price": '0.99860000',
// "cost": '22.16892001',
// "fee": '0.04433784',
// "vol": '22.20000000',
// "margin": '0.00000000',
// "misc": ''
// }
//
// fetchMyTrades
//
// {
// "ordertxid": "OSJVN7-A2AE-63WZV",
// "postxid": "TBP7O6-PNXI-CONU",
// "pair": "XXBTZUSD",
// "time": 1710429248.3052235,
// "type": "sell",
// "ordertype": "liquidation market",
// "price": "72026.50000",
// "cost": "7.20265",
// "fee": "0.01873",
// "vol": "0.00010000",
// "margin": "1.44053",
// "leverage": "5",
// "misc": "closing",
// "trade_id": 68230622,
// "maker": false
// }
//
// watchTrades
//
// {
// "symbol": "BTC/USD",
// "side": "buy",
// "price": 109601.2,
// "qty": 0.04561994,
// "ord_type": "market",
// "trade_id": 83449369,
// "timestamp": "2025-05-27T11:24:03.847761Z"
// }
//
let mut timestamp: Value = Value::Null;
let mut datetime: Value = Value::Null;
let mut side: Value = Value::Null;
let mut type_var: Value = Value::Null;
let mut price: Value = Value::Null;
let mut amount: Value = Value::Null;
let mut id: Value = Value::Null;
let mut orderId: Value = Value::Null;
let mut fee: Value = Value::Null;
let mut symbol: Value = Value::Null;
let mut isOrderTrade: bool = (!(matches!(&trade, Value::Arr(_)))) && (!matches!(&trade, Value::Str(_))) && (matches!(&trade, Value::Dict(__d) if __d.contains_key("ordertxid")));
let mut marketResolved: Value = market.clone();
if isOrderTrade {
marketResolved = self.resolve_market_by_altname_or_id(self.safe_string_k(trade.clone(), "pair", &[]), &[market]);
}
if (matches!(&trade, Value::Arr(_))) {
timestamp = self.safe_timestamp(trade.clone(), Value::Int(2), &[]);
side = (if (self.safe_string(trade.clone(), Value::Int(3), &[]).as_str() == Some("s")) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
type_var = (if (self.safe_string(trade.clone(), Value::Int(4), &[]).as_str() == Some("l")) { Value::Str("limit".into()) } else { Value::Str("market".into()) });
price = self.safe_string(trade.clone(), Value::Int(0), &[]);
amount = self.safe_string(trade.clone(), Value::Int(1), &[]);
let mut tradeLength: f64 = ((trade.len() as i64) as f64);
if tradeLength > ((6i64) as f64) {
id = self.safe_string(trade.clone(), Value::Int(6), &[]); // artificially added as per #1794
}
} else if matches!(&trade, Value::Str(_)) {
id = trade.clone();
} else if (matches!(&trade, Value::Dict(__d) if __d.contains_key("ordertxid"))) {
orderId = self.safe_string_k(trade.clone(), "ordertxid", &[]);
id = self.safe_string2(trade.clone(), Value::Str("id".into()), Value::Str("postxid".into()), &[]);
timestamp = self.safe_timestamp_k(trade.clone(), "time", &[]);
side = self.safe_string_k(trade.clone(), "type", &[]);
type_var = self.safe_string_k(trade.clone(), "ordertype", &[]);
price = self.safe_string_k(trade.clone(), "price", &[]);
amount = self.safe_string_k(trade.clone(), "vol", &[]);
if (matches!(&trade, Value::Dict(__d) if __d.contains_key("fee"))) {
let mut currency: Value = Value::Null;
if (marketResolved != Value::Null) {
currency = self.safe_string_k(marketResolved.clone(), "quote", &[]);
}
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_string_k(trade.clone(), "fee", &[]));
m.insert("currency".to_string(), currency);
m
});
}
} else {
symbol = self.safe_string_k(trade.clone(), "symbol", &[]);
datetime = self.safe_string_k(trade.clone(), "timestamp", &[]);
id = self.safe_string_k(trade.clone(), "trade_id", &[]);
side = self.safe_string_k(trade.clone(), "side", &[]);
type_var = self.safe_string_k(trade.clone(), "ord_type", &[]);
price = self.safe_string_k(trade.clone(), "price", &[]);
amount = self.safe_string_k(trade.clone(), "qty", &[]);
}
if (marketResolved != Value::Null) {
symbol = self.safe_string_k(marketResolved.clone(), "symbol", &[]);
}
let mut cost: Value = self.safe_string_k(trade.clone(), "cost", &[]);
let mut maker: Value = self.safe_bool_k(trade.clone(), "maker", &[]);
let mut takerOrMaker: Value = Value::Null;
if (maker != Value::Null) {
takerOrMaker = (if maker.as_bool() == Some(true) { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
}
if (datetime == Value::Null) {
datetime = self.iso8601(timestamp.clone());
} else {
timestamp = self.parse8601(datetime.clone());
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("order".to_string(), orderId);
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp);
m.insert("datetime".to_string(), datetime);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), cost);
m.insert("fee".to_string(), fee);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name kraken#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://docs.kraken.com/api-reference/market-data/get-recent-trades
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut id: Value = market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), id.clone());
m
});
// https://support.kraken.com/hc/en-us/articles/218198197-How-to-pull-all-trade-data-using-the-Kraken-REST-API
// https://github.com/ccxt/ccxt/issues/5677
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("since".into(), self.number_to_string(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 })))); }; // expected to be in seconds
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("count".into(), limit.clone()); }
}
let __ws_arg_6 = self.extend(request, &[params]);
let mut response: Value = self.public_get_trades(&[__ws_arg_6]).await;
//
// {
// "error": [],
// "result": {
// "XETHXXBT": [
// ["0.032310","4.28169434",1541390792.763,"s","l",""]
// ],
// "last": "1541439421200678657"
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut trades: Value = self.safe_value(result.clone(), id, &[]);
// trades is a sorted array: last (most recent trade) goes last
let mut length: Value = get_array_length(&trades);
if length.as_f64().unwrap_or(f64::NAN) <= ((0i64) as f64) {
return Value::from(vec![]);
}
let mut lastTrade: Value = get_value(&trades, &subtract(&length, &Value::Int(1)));
let mut lastTradeId: Value = self.safe_string_k(result, "last", &[]);
append_to_array(&mut lastTrade, lastTradeId);
add_element_to_object(&mut trades, &subtract(&length, &Value::Int(1)), lastTrade);
return self.parse_trades(trades, &[market, since, limit]);
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut balances: Value = self.safe_dict_k(response.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
let mut currencyIds: Value = object_keys(&balances);
{
let mut i: Value = Value::Int(0);
let mut __for_first_832: bool = true;
while { if !__for_first_832 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_832 = false; i.as_f64().unwrap_or(f64::NAN) < ((currencyIds.len() as i64) as f64) } {
let mut currencyId: Value = currencyIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut balance: Value = self.safe_dict(balances.clone(), currencyId, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(balance.clone(), "hold_trade", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(balance, "balance", &[])); }
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
}
return self.safe_balance(result);
Value::Null
}
/*
* @method
* @name kraken#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://docs.kraken.com/api-reference/account-data/get-extended-balance
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.private_post_balance_ex(&[params]).await;
return self.parse_balance(response);
Value::Null
}
/*
* @method
* @name kraken#createMarketOrderWithCost
* @description create a market order by providing the symbol, side and cost
* @see https://docs.kraken.com/api-reference/trading/add-order
* @param {string} symbol unified symbol of the market to create an order in (only USD markets are supported)
* @param {string} side 'buy' or 'sell'
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_market_order_with_cost(&mut self, mut symbol: Value, mut side: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
// only buy orders are supported by the endpoint
let mut req: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), cost.clone());
m
});
let __ws_arg_7 = self.extend(req, &[params]);
return self.create_order(symbol, Value::Str("market".into()), side, cost, &[Value::Null, __ws_arg_7]).await;
Value::Null
}
/*
* @method
* @name kraken#createMarketBuyOrderWithCost
* @description create a market buy order by providing the symbol, side and cost
* @see https://docs.kraken.com/api-reference/trading/add-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_market_buy_order_with_cost(&mut self, mut symbol: Value, mut cost: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
return self.create_market_order_with_cost(symbol, Value::Str("buy".into()), cost, &[params]).await;
Value::Null
}
/*
* @method
* @name kraken#createOrder
* @description create a trade order
* @see https://docs.kraken.com/api-reference/trading/add-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.postOnly] if true, the order will only be posted to the order book and not executed immediately
* @param {bool} [params.reduceOnly] *margin only* indicates if this order is to reduce the size of a position
* @param {float} [params.stopLossPrice] *margin only* the price that a stop loss order is triggered at
* @param {float} [params.takeProfitPrice] *margin only* the price that a take profit order is triggered at
* @param {string} [params.trailingAmount] *margin only* the quote amount to trail away from the current market price
* @param {string} [params.trailingPercent] *margin only* the percent to trail away from the current market price
* @param {string} [params.trailingLimitAmount] *margin only* the quote amount away from the trailingAmount
* @param {string} [params.trailingLimitPercent] *margin only* the percent away from the trailingAmount
* @param {string} [params.offset] *margin only* '+' or '-' whether you want the trailingLimitAmount value to be positive or negative, default is negative '-'
* @param {string} [params.trigger] *margin only* the activation price type, 'last' or 'index', default is 'last'
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pair".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), side);
m.insert("ordertype".to_string(), type_var.clone());
m.insert("volume".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m
});
let mut orderRequest: Value = self.order_request(Value::Str("createOrder".into()), symbol, type_var, request, amount, &[price, params]);
let mut flags: Value = self.safe_string(orderRequest.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), Value::Str("oflags".into()), &[Value::Str("".into())]);
let mut isUsingCost: Value = Value::Bool(Value::Int(flags.as_str().and_then(|__s| __s.find("viqc")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64));
let __ws_arg_8 = self.extend(orderRequest.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null), &[orderRequest.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null)]);
let mut response: Value = self.private_post_add_order(&[__ws_arg_8]).await;
//
// {
// "error": [],
// "result": {
// "descr": { order: 'buy 0.02100000 ETHUSDT @ limit 330.00' }, // see more examples in "parseOrder"
// "txid": [ 'OEKVV2-IH52O-TPL6GZ' ]
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("usingCost".into(), isUsingCost); }
return self.parse_order(result, &[]);
Value::Null
}
/*
* @method
* @name kraken#createOrders
* @description create a list of trade orders
* @see https://docs.kraken.com/api-reference/trading/add-order-batch
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut ordersRequests: Value = Value::from(vec![]);
let mut orderSymbols: Value = Value::from(vec![]);
let mut symbol: Value = Value::Null;
let mut market: Value = Value::Null;
{
let mut i: Value = Value::Int(0);
let mut __for_first_833: bool = true;
while { if !__for_first_833 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_833 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut marketId: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
if (symbol == Value::Null) {
symbol = marketId.clone();
} else {
if (symbol.as_str() != marketId.as_str()) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createOrders() requires all orders to have the same symbol".into()))));
}
}
market = self.market(marketId.clone());
append_to_array(&mut orderSymbols, marketId.clone());
let mut type_var: Value = self.safe_string_k(rawOrder.clone(), "type", &[]);
let mut side: Value = self.safe_string_k(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 parsedAmount: Value = self.amount_to_precision(market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), amount.clone());
let mut req: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), side);
m.insert("ordertype".to_string(), type_var.clone());
m.insert("volume".to_string(), parsedAmount);
m
});
let mut orderRequest: Value = self.order_request(Value::Str("createOrders".into()), marketId, type_var, req, amount, &[price, orderParams]);
append_to_array(&mut ordersRequests, orderRequest.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
}
}
orderSymbols = self.market_symbols(&[orderSymbols.clone(), Value::Null, Value::Bool(false), Value::Bool(true), Value::Bool(true)]);
let mut response: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), ordersRequests);
m.insert("pair".to_string(), self.safe_string_k(market, "id", &[]));
m
});
request = self.extend(request.clone(), &[params]);
response = self.private_post_add_order_batch(&[request]).await;
//
// {
// "error":[
// ],
// "result":{
// "orders":[
// {
// "txid":"OEPPJX-34RMM-OROGZE",
// "descr":{
// "order":"sell 6.000000 ADAUSDC @ limit 0.400000"
// }
// },
// {
// "txid":"OLQY7O-OYBXW-W23PGL",
// "descr":{
// "order":"sell 6.000000 ADAUSDC @ limit 0.400000"
// }
// }
// ]
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_orders(self.safe_list_k(result, "orders", &[]), &[]);
Value::Null
}
pub fn find_market_by_altname_or_id(&self, mut id: Value) -> Value {
let mut marketsByAltname: Value = self.safe_dict_k(self.options.clone(), "marketsByAltname", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (in_op(&marketsByAltname, &id)) {
return get_value(&marketsByAltname, &id);
} else {
return self.safe_market(&[id]);
}
Value::Null
}
pub fn resolve_market_by_altname_or_id(&self, mut marketId: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut foundMarket: Value = self.find_market_by_altname_or_id(marketId.clone());
if (foundMarket != Value::Null) {
return foundMarket;
}
if (marketId != Value::Null) {
return self.get_delisted_market_by_id(marketId);
}
return market;
Value::Null
}
pub fn get_delisted_market_by_id(&self, mut id: Value) -> Value {
if (id == Value::Null) {
return id;
}
let mut market: Value = self.safe_dict(self.options.as_map().and_then(|__m| __m.get("delistedMarketsById")).cloned().unwrap_or(Value::Null), id.clone(), &[]);
if (market != Value::Null) {
return market;
}
let mut baseIdStart: Value = Value::Int(0);
let mut baseIdEnd: Value = Value::Int(3);
let mut quoteIdStart: Value = Value::Int(3);
let mut quoteIdEnd: Value = Value::Int(6);
if is_equal(&get_array_length(&id), &Value::Int(8)) {
baseIdEnd = Value::Int(4);
quoteIdStart = Value::Int(4);
quoteIdEnd = Value::Int(8);
} else if is_equal(&get_array_length(&id), &Value::Int(7)) {
baseIdEnd = Value::Int(4);
quoteIdStart = Value::Int(4);
quoteIdEnd = Value::Int(7);
}
let mut baseId: Value = slice(&id, &baseIdStart, &baseIdEnd);
let mut quoteId: Value = slice(&id, "eIdStart, "eIdEnd);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
return Value::Null;
}
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
market = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m
});
add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.options) }, &Value::Str("delistedMarketsById".into())), &id, market.clone());
return market;
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pending".to_string(), Value::Str("open".into()));
m.insert("open".to_string(), Value::Str("open".into()));
m.insert("pending_new".to_string(), Value::Str("open".into()));
m.insert("new".to_string(), Value::Str("open".into()));
m.insert("partially_filled".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("closed".to_string(), Value::Str("closed".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("expired".to_string(), Value::Str("expired".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order_type(&self, mut status: Value) -> Option<String> {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("take-profit".to_string(), Value::Str("market".into()));
m.insert("stop-loss".to_string(), Value::Str("market".into()));
m.insert("stop-loss-limit".to_string(), Value::Str("limit".into()));
m.insert("take-profit-limit".to_string(), Value::Str("limit".into()));
m.insert("trailing-stop-limit".to_string(), Value::Str("limit".into()));
m
});
return self.safe_string(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);
//
// createOrder
//
// {
// "descr": {
// "order": "buy 0.02100000 ETHUSDT @ limit 330.00" // limit orders
// "buy 0.12345678 ETHUSDT @ market" // market order
// "sell 0.28002676 ETHUSDT @ stop loss 0.0123 -> limit 0.0.1222" // stop order
// "sell 0.00100000 ETHUSDT @ stop loss 2677.00 -> limit 2577.00 with 5:1 leverage"
// "buy 0.10000000 LTCUSDT @ take profit 75.00000 -> limit 74.00000"
// "sell 10.00000000 XRPEUR @ trailing stop +50.0000%" // trailing stop
// },
// "txid": [ 'OEKVV2-IH52O-TPL6GZ' ]
// }
//
// editOrder
//
// {
// "amend_id": "TJSMEH-AA67V-YUSQ6O"
// }
//
// ws - createOrder
// {
// "order_id": "OXM2QD-EALR2-YBAVEU"
// }
//
// ws - editOrder
// {
// "amend_id": "TJSMEH-AA67V-YUSQ6O",
// "order_id": "OXM2QD-EALR2-YBAVEU"
// }
//
// {
// "error": [],
// "result": {
// "open": {
// "OXVPSU-Q726F-L3SDEP": {
// "refid": null,
// "userref": 0,
// "status": "open",
// "opentm": 1706893367.4656649,
// "starttm": 0,
// "expiretm": 0,
// "descr": {
// "pair": "XRPEUR",
// "type": "sell",
// "ordertype": "trailing-stop",
// "price": "+50.0000%",
// "price2": "0",
// "leverage": "none",
// "order": "sell 10.00000000 XRPEUR @ trailing stop +50.0000%",
// "close": ""
// },
// "vol": "10.00000000",
// "vol_exec": "0.00000000",
// "cost": "0.00000000",
// "fee": "0.00000000",
// "price": "0.00000000",
// "stopprice": "0.23424000",
// "limitprice": "0.46847000",
// "misc": "",
// "oflags": "fciq",
// "trigger": "index"
// }
// }
// }
//
// fetchOpenOrders
//
// {
// "refid": null,
// "userref": null,
// "cl_ord_id": "1234",
// "status": "open",
// "opentm": 1733815269.370054,
// "starttm": 0,
// "expiretm": 0,
// "descr": {
// "pair": "XBTUSD",
// "type": "buy",
// "ordertype": "limit",
// "price": "70000.0",
// "price2": "0",
// "leverage": "none",
// "order": "buy 0.00010000 XBTUSD @ limit 70000.0",
// "close": ""
// },
// "vol": "0.00010000",
// "vol_exec": "0.00000000",
// "cost": "0.00000",
// "fee": "0.00000",
// "price": "0.00000",
// "stopprice": "0.00000",
// "limitprice": "0.00000",
// "misc": "",
// "oflags": "fciq"
// }
//
let mut isUsingCost: Value = self.safe_bool_k(order.clone(), "usingCost", &[Value::Bool(false)]);
let mut orderOmitted: Value = self.omit(order, Value::Str("usingCost".into()), &[]);
let mut description: Value = self.safe_dict_k(orderOmitted.clone(), "descr", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderDescriptionObj: Value = self.safe_dict_k(orderOmitted.clone(), "descr", &[]); // can be null
let mut orderDescription: Value = Value::Null;
if (orderDescriptionObj != Value::Null) {
orderDescription = self.safe_string_k(orderDescriptionObj, "order", &[]);
} else {
orderDescription = self.safe_string_k(orderOmitted.clone(), "descr", &[]);
}
let mut side: Value = Value::Null;
let mut rawType: Value = Value::Null;
let mut marketId: Value = Value::Null;
let mut price: Value = Value::Null;
let mut amount: Value = Value::Null;
let mut cost: Value = Value::Null;
let mut triggerPrice: Value = Value::Null;
if (orderDescription != Value::Null) {
let mut parts: Value = split(&orderDescription, &Value::Str(" ".into()));
side = self.safe_string(parts.clone(), Value::Int(0), &[]);
if (isUsingCost.as_bool() != Some(true)) {
amount = self.safe_string(parts.clone(), Value::Int(1), &[]);
} else {
cost = self.safe_string(parts.clone(), Value::Int(1), &[]);
}
marketId = self.safe_string(parts.clone(), Value::Int(2), &[]);
let mut part4: Value = self.safe_string(parts.clone(), Value::Int(4), &[]);
let mut part5: Value = self.safe_string(parts.clone(), Value::Int(5), &[]);
if (part4.as_str() == Some("limit")) || (part4.as_str() == Some("market")) {
rawType = part4.clone(); // eg, limit, market
} else {
rawType = Value::Str(format!("{}{}", Value::Str(format!("{}{}", part4, Value::Str(" ".into())).into()), part5).into()); // eg. stop loss, take profit, trailing stop
}
if (rawType.as_str() == Some("stop loss")) || (rawType.as_str() == Some("take profit")) {
triggerPrice = self.safe_string(parts.clone(), Value::Int(6), &[]);
price = self.safe_string(parts.clone(), Value::Int(9), &[]);
} else if (rawType.as_str() == Some("limit")) {
price = self.safe_string(parts, Value::Int(5), &[]);
}
}
side = self.safe_string_k(description.clone(), "type", &[side.clone()]);
rawType = self.safe_string_k(description.clone(), "ordertype", &[rawType.clone()]); // orderType has dash, e.g. trailing-stop
marketId = self.safe_string_k(description.clone(), "pair", &[marketId.clone()]);
let mut marketResolved: Value = self.resolve_market_by_altname_or_id(marketId, &[market]);
let mut symbol: Value = Value::Null;
let mut timestamp: Value = self.safe_timestamp_k(orderOmitted.clone(), "opentm", &[]);
amount = self.safe_string_k(orderOmitted.clone(), "vol", &[amount.clone()]);
let mut filled: Value = self.safe_string_k(orderOmitted.clone(), "vol_exec", &[]);
let mut fee: Value = Value::Null;
// kraken truncates the cost in the api response so we will ignore it and calculate it from average & filled
// const cost = this.safeString (order, 'cost');
price = self.safe_string_k(description.clone(), "price", &[price.clone()]);
// when type = trailing stop returns price = '+50.0000%'
if (price != Value::Null) && ((ends_with(&price, &Value::Str("%".into()))) || is_true(&crate::precise::Precise::stringEquals(&price, &Value::Str("0.00000".into()))) || is_true(&crate::precise::Precise::stringEquals(&price, &Value::Str("0".into())))) {
price = Value::Null; // this is not the price we want
}
if (price == Value::Null) {
price = self.safe_string_k(description.clone(), "price2", &[]);
price = self.safe_string2(orderOmitted.clone(), Value::Str("limitprice".into()), Value::Str("price".into()), &[price.clone()]);
}
let mut flags: Value = self.safe_string_k(orderOmitted.clone(), "oflags", &[Value::Str("".into())]);
let mut isPostOnly: Value = Value::Bool(Value::Int(flags.as_str().and_then(|__s| __s.find("post")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64));
let mut average: Value = self.safe_number_k(orderOmitted.clone(), "price", &[]);
if (marketResolved != Value::Null) {
symbol = self.safe_string_k(marketResolved.clone(), "symbol", &[]);
if (matches!(&orderOmitted, Value::Dict(__d) if __d.contains_key("fee"))) {
let mut feeCost: Value = self.safe_string_k(orderOmitted.clone(), "fee", &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost);
m.insert("rate".to_string(), Value::Null);
m
});
if Value::Int(flags.as_str().and_then(|__s| __s.find("fciq")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
if let Value::Dict(__d) = &mut fee { std::sync::Arc::make_mut(__d).insert("currency".into(), marketResolved.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null)); }
} else if Value::Int(flags.as_str().and_then(|__s| __s.find("fcib")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
if let Value::Dict(__d) = &mut fee { std::sync::Arc::make_mut(__d).insert("currency".into(), marketResolved.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null)); }
}
}
}
let mut status: Value = self.parse_order_status(self.safe_string_k(orderOmitted.clone(), "status", &[]));
let mut id: Value = self.safe_string_n(orderOmitted.clone(), Value::from(vec![Value::Str("id".into()), Value::Str("txid".into()), Value::Str("order_id".into()), Value::Str("amend_id".into())]), &[]);
if (id == Value::Null) || (starts_with(&id, &Value::Str("[".into()))) {
let mut txid: Value = self.safe_list_k(orderOmitted.clone(), "txid", &[]);
id = self.safe_string(txid, Value::Int(0), &[]);
}
let mut userref: Value = self.safe_string_k(orderOmitted.clone(), "userref", &[]);
let mut clientOrderId: Value = self.safe_string_k(orderOmitted.clone(), "cl_ord_id", &[userref]);
let mut rawTrades: Value = self.safe_list_k(orderOmitted.clone(), "trades", &[Value::from(vec![])]);
let mut trades: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_834: bool = true;
while { if !__for_first_834 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_834 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawTrades.len() as i64) as f64) } {
let mut rawTrade: Value = rawTrades.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if matches!(&rawTrade, Value::Str(_)) {
append_to_array(&mut trades, self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), rawTrade.clone());
m.insert("order".to_string(), id.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}), &[]));
} else {
append_to_array(&mut trades, rawTrade);
}
}
}
// as mentioned in #24192 PR, this field is not something consistent/actual
// triggerPrice = this.omitZero (this.safeString (order, 'stopprice', triggerPrice));
let mut stopLossPrice: Value = Value::Null;
let mut takeProfitPrice: Value = Value::Null;
// the dashed strings are not provided from fields (eg. fetch order)
// while spaced strings from "order" sentence (when other fields not available)
if (rawType != Value::Null) {
if (starts_with(&rawType, &Value::Str("take-profit".into()))) {
takeProfitPrice = self.safe_string_k(description.clone(), "price", &[]);
price = self.omit_zero(self.safe_string_k(description.clone(), "price2", &[]));
} else if (starts_with(&rawType, &Value::Str("stop-loss".into()))) {
stopLossPrice = self.safe_string_k(description.clone(), "price", &[]);
price = self.omit_zero(self.safe_string_k(description, "price2", &[]));
} else if (rawType.as_str() == Some("take profit")) {
takeProfitPrice = triggerPrice.clone();
} else if (rawType.as_str() == Some("stop loss")) {
stopLossPrice = triggerPrice.clone();
}
}
let mut typeParsed: Value = self.parse_order_type(rawType).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
// unlike from endpoints which provide eg: "take-profit-limit"
// for "space-delimited" orders we dont have market/limit suffixes, their format is
// eg: `stop loss > limit 123`, so we need to parse them manually
if self.in_array(typeParsed.clone(), Value::from(vec![Value::Str("stop loss".into()), Value::Str("take profit".into())])).as_bool() == Some(true) {
typeParsed = (if (price == Value::Null) { Value::Str("market".into()) } else { Value::Str("limit".into()) });
}
let mut amendId: Option<String> = self.safe_string_k(orderOmitted.clone(), "amend_id", &[]).as_str().map(str::to_owned);
if (amendId.is_some()) {
isPostOnly = Value::Null;
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), clientOrderId);
m.insert("info".to_string(), orderOmitted.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_timestamp_k(orderOmitted.clone(), "closetm", &[]));
m.insert("status".to_string(), status);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), typeParsed);
m.insert("timeInForce".to_string(), Value::Null);
m.insert("postOnly".to_string(), isPostOnly);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("triggerPrice".to_string(), triggerPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("cost".to_string(), cost);
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), filled);
m.insert("average".to_string(), average);
m.insert("remaining".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), self.safe_bool2(orderOmitted, Value::Str("reduceOnly".into()), Value::Str("reduce_only".into()), &[]));
m.insert("fee".to_string(), fee);
m.insert("trades".to_string(), trades);
m
}), &[marketResolved]);
Value::Null
}
pub fn order_request(&self, mut method: Value, mut symbol: Value, mut type_var: Value, mut request: 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
}));
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("clientOrderId".into())]), &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("cl_ord_id".into(), clientOrderId); }
}
let mut stopLossTriggerPrice: Value = self.safe_string_k(paramsOmitted.clone(), "stopLossPrice", &[]);
let mut takeProfitTriggerPrice: Value = self.safe_string_k(paramsOmitted.clone(), "takeProfitPrice", &[]);
let mut isStopLossTriggerOrder: bool = stopLossTriggerPrice != Value::Null;
let mut isTakeProfitTriggerOrder: bool = takeProfitTriggerPrice != Value::Null;
let mut isStopLossOrTakeProfitTrigger: bool = isStopLossTriggerOrder || isTakeProfitTriggerOrder;
let mut trailingAmount: Value = self.safe_string_k(paramsOmitted.clone(), "trailingAmount", &[]);
let mut trailingPercent: Value = self.safe_string_k(paramsOmitted.clone(), "trailingPercent", &[]);
let mut trailingLimitAmount: Value = self.safe_string_k(paramsOmitted.clone(), "trailingLimitAmount", &[]);
let mut trailingLimitPercent: Value = self.safe_string_k(paramsOmitted.clone(), "trailingLimitPercent", &[]);
let mut isTrailingAmountOrder: bool = trailingAmount != Value::Null;
let mut isTrailingPercentOrder: bool = trailingPercent != Value::Null;
let mut isLimitOrder: bool = (type_var != Value::Null) && (ends_with(&type_var, &Value::Str("limit".into()))); // supporting limit, stop-loss-limit, take-profit-limit, etc
let mut isMarketOrder: bool = type_var.as_str() == Some("market");
let mut cost: Value = self.safe_string_k(paramsOmitted.clone(), "cost", &[]);
let mut flags: Value = self.safe_string_k(paramsOmitted.clone(), "oflags", &[]);
let mut paramsOmitted2: Value = self.omit(paramsOmitted, Value::from(vec![Value::Str("cost".into()), Value::Str("oflags".into())]), &[]);
let mut isViqcOrder: bool = (flags != Value::Null) && (Value::Int(flags.as_str().and_then(|__s| __s.find("viqc")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64)); // volume in quote currency
if isMarketOrder && ((cost != Value::Null) || isViqcOrder) {
if (cost == Value::Null) && (amount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("volume".into(), self.cost_to_precision(symbol.clone(), self.number_to_string(amount))); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("volume".into(), self.cost_to_precision(symbol.clone(), cost)); }
}
let mut extendedOflags: Value = Value::Str("viqc".into());
if (flags != Value::Null) {
extendedOflags = Value::Str(format!("{}{}", flags, Value::Str(",viqc".into())).into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("oflags".into(), extendedOflags); }
} else if isLimitOrder && !isTrailingAmountOrder && !isTrailingPercentOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol.clone(), price.clone())); }
}
let mut reduceOnly: Value = self.safe_bool2(paramsOmitted2.clone(), Value::Str("reduceOnly".into()), Value::Str("reduce_only".into()), &[]);
if isStopLossOrTakeProfitTrigger {
if isStopLossTriggerOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol.clone(), stopLossTriggerPrice)); }
if isLimitOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordertype".into(), Value::Str("stop-loss-limit".into())); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordertype".into(), Value::Str("stop-loss".into())); }
}
} else if isTakeProfitTriggerOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), self.price_to_precision(symbol.clone(), takeProfitTriggerPrice)); }
if isLimitOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordertype".into(), Value::Str("take-profit-limit".into())); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordertype".into(), Value::Str("take-profit".into())); }
}
}
if isLimitOrder {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price2".into(), self.price_to_precision(symbol.clone(), price)); }
}
} else if isTrailingAmountOrder || isTrailingPercentOrder {
let mut trailingPercentString: Value = Value::Null;
if (trailingPercent != Value::Null) {
trailingPercentString = (if (ends_with(&trailingPercent, &Value::Str("%".into()))) { (Value::Str(format!("{}{}", Value::Str("+".into()), trailingPercent).into())) } else { (Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("+".into()), trailingPercent).into()), Value::Str("%".into())).into())) });
}
let mut trailingAmountString: Value = (if (trailingAmount != Value::Null) { Value::Str(format!("{}{}", Value::Str("+".into()), trailingAmount).into()) } else { Value::Null }); // must use + for this
let mut offset: Value = self.safe_string_k(paramsOmitted2.clone(), "offset", &[Value::Str("-".into())]); // can use + or - for this
let mut trailingLimitAmountString: Value = (if (trailingLimitAmount != Value::Null) { Value::Str(format!("{}{}", offset, self.number_to_string(trailingLimitAmount.clone())).into()) } else { Value::Null });
let mut trailingActivationPriceType: Value = self.safe_string_k(paramsOmitted2.clone(), "trigger", &[Value::Str("last".into())]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("trigger".into(), trailingActivationPriceType); }
if isLimitOrder || (trailingLimitAmount != Value::Null) || (trailingLimitPercent != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordertype".into(), Value::Str("trailing-stop-limit".into())); }
if (trailingLimitPercent != Value::Null) {
let mut trailingLimitPercentString: Value = (if (ends_with(&trailingLimitPercent, &Value::Str("%".into()))) { (Value::Str(format!("{}{}", offset, trailingLimitPercent).into())) } else { (Value::Str(format!("{}{}", Value::Str(format!("{}{}", offset, trailingLimitPercent).into()), Value::Str("%".into())).into())) });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), trailingPercentString.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price2".into(), trailingLimitPercentString); }
} else if (trailingLimitAmount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), trailingAmountString.clone()); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price2".into(), trailingLimitAmountString); }
}
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("ordertype".into(), Value::Str("trailing-stop".into())); }
if (trailingPercent != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), trailingPercentString); }
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("price".into(), trailingAmountString); }
}
}
}
if (reduceOnly.as_bool() == Some(true)) {
if (method.as_str() == Some("createOrderWs")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("reduce_only".into(), Value::Bool(true)); }; // ws request can't have stringified bool
} else {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("reduce_only".into(), Value::Str("true".into())); }; // not using boolean in this case, because the urlencodedNested transforms it into 'True' string
}
}
let mut close: Value = self.safe_dict_k(paramsOmitted2.clone(), "close", &[]);
if (close != Value::Null) {
close = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[close.clone()]);
close = (if (close == Value::Null) { Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) } else { close.clone() });
let mut closePrice: Value = self.safe_value_k(close.clone(), "price", &[]);
if (closePrice != Value::Null) {
add_element_to_object(&mut close, &Value::Str("price".into()), self.price_to_precision(symbol.clone(), closePrice));
}
let mut closePrice2: Value = self.safe_value_k(close.clone(), "price2", &[]); // stopPrice
if (closePrice2 != Value::Null) {
add_element_to_object(&mut close, &Value::Str("price2".into()), self.price_to_precision(symbol, closePrice2));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("close".into(), close); }
}
let mut timeInForce: Value = self.safe_string2(paramsOmitted2.clone(), Value::Str("timeInForce".into()), Value::Str("timeinforce".into()), &[]);
if (timeInForce != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("timeinforce".into(), timeInForce); }
}
let mut isMarket: Value = (Value::Bool(type_var.as_str() == Some("market")));
let mut postOnlyparamsPostOnlyVariable = self.handle_post_only(isMarket, Value::Bool(false), &[paramsOmitted2]);
let mut postOnly: Value = postOnlyparamsPostOnlyVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPostOnly: Value = postOnlyparamsPostOnlyVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (postOnly.as_bool() == Some(true)) {
let mut extendedPostFlags: Value = Value::Str("post".into());
if (flags != Value::Null) {
extendedPostFlags = Value::Str(format!("{}{}", flags, Value::Str(",post".into())).into());
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("oflags".into(), extendedPostFlags); }
}
if (flags != Value::Null) && !(matches!(&request, Value::Dict(__d) if __d.contains_key("oflags"))) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("oflags".into(), flags); }
}
let mut paramsOmitted3: Value = self.omit(paramsPostOnly, Value::from(vec![Value::Str("timeInForce".into()), Value::Str("reduceOnly".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("trailingAmount".into()), Value::Str("trailingPercent".into()), Value::Str("trailingLimitAmount".into()), Value::Str("trailingLimitPercent".into()), Value::Str("offset".into())]), &[]);
return Value::from(vec![request, paramsOmitted3]);
Value::Null
}
/*
* @method
* @name kraken#editOrder
* @description edit a trade order
* @see https://docs.kraken.com/api-reference/trading/amend-order
* @param {string} id order id
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} [amount] how much of the currency you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {float} [params.stopLossPrice] the price that a stop loss order is triggered at
* @param {float} [params.takeProfitPrice] the price that a take profit order is triggered at
* @param {string} [params.trailingAmount] the quote amount to trail away from the current market price
* @param {string} [params.trailingPercent] the percent to trail away from the current market price
* @param {string} [params.trailingLimitAmount] the quote amount away from the trailingAmount
* @param {string} [params.trailingLimitPercent] the percent away from the trailingAmount
* @param {string} [params.offset] '+' or '-' whether you want the trailingLimitAmount value to be positive or negative
* @param {boolean} [params.postOnly] if true, the order will only be posted to the order book and not executed immediately
* @param {string} [params.clientOrderId] the orders client order id
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if (market.as_map().and_then(|__m| __m.get("spot")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" editOrder() does not support ".into())).into()), market.as_map().and_then(|__m| __m.get("type")).cloned().unwrap_or(Value::Null)).into()), Value::Str(" orders, only spot orders are accepted".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("txid".to_string(), id);
m
});
let mut clientOrderId: Value = self.safe_string2(params.clone(), Value::Str("clientOrderId".into()), Value::Str("cl_ord_id".into()), &[]);
let mut paramsOmitted: Value = (if (clientOrderId != Value::Null) { self.omit(params.clone(), Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("cl_ord_id".into())]), &[]) } else { params });
if (clientOrderId != Value::Null) {
add_element_to_object(&mut request, &Value::Str("cl_ord_id".into()), clientOrderId);
request = self.omit(request.clone(), Value::Str("txid".into()), &[]);
}
let mut isMarket: Value = (Value::Bool(type_var.as_str() == Some("market")));
let mut postOnly: Value = Value::Null;
{ let __destr_tmp = self.handle_post_only(isMarket, Value::Bool(false), &[paramsOmitted.clone()]); postOnly = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsOmitted = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (postOnly.as_bool() == Some(true)) {
add_element_to_object(&mut request, &Value::Str("post_only".into()), Value::Str("true".into())); // not using boolean in this case, because the urlencodedNested transforms it into 'True' string
}
if (amount != Value::Null) {
add_element_to_object(&mut request, &Value::Str("order_qty".into()), self.amount_to_precision(symbol.clone(), amount));
}
if (price != Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit_price".into()), self.price_to_precision(symbol.clone(), price));
}
let mut allTriggerPrices: Value = self.safe_string_n(paramsOmitted.clone(), Value::from(vec![Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("trailingAmount".into()), Value::Str("trailingPercent".into()), Value::Str("trailingLimitAmount".into()), Value::Str("trailingLimitPercent".into())]), &[]);
if (allTriggerPrices != Value::Null) {
let mut offset: Value = self.safe_string_k(paramsOmitted.clone(), "offset", &[]);
paramsOmitted = self.omit(paramsOmitted.clone(), Value::from(vec![Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("trailingAmount".into()), Value::Str("trailingPercent".into()), Value::Str("trailingLimitAmount".into()), Value::Str("trailingLimitPercent".into()), Value::Str("offset".into())]), &[]);
if (offset != Value::Null) {
allTriggerPrices = Value::Str(format!("{}{}", offset, allTriggerPrices).into());
add_element_to_object(&mut request, &Value::Str("trigger_price".into()), allTriggerPrices.clone());
} else {
add_element_to_object(&mut request, &Value::Str("trigger_price".into()), self.price_to_precision(symbol, allTriggerPrices));
}
}
let __ws_arg_9 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_amend_order(&[__ws_arg_9]).await;
//
// {
// "error": [],
// "result": {
// "amend_id": "TJSMEH-AA67V-YUSQ6O"
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(result, &[market]);
Value::Null
}
/*
* @method
* @name kraken#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.kraken.com/api-reference/account-data/query-orders-info
* @param {string} id order id
* @param {string} symbol not used by kraken fetchOrder
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn 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 clientOrderId: Value = self.safe_value2(params.clone(), Value::Str("userref".into()), Value::Str("clientOrderId".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trades".to_string(), Value::Bool(true));
m.insert("txid".to_string(), id.clone());
m
});
let mut query: Value = params.clone();
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("userref".into(), clientOrderId); }
query = self.omit(params, Value::from(vec![Value::Str("userref".into()), Value::Str("clientOrderId".into())]), &[]);
}
let __ws_arg_10 = self.extend(request, &[query]);
let mut response: Value = self.private_post_query_orders(&[__ws_arg_10]).await;
//
// {
// "error":[],
// "result":{
// "OTLAS3-RRHUF-NDWH5A":{
// "refid":null,
// "userref":null,
// "status":"closed",
// "reason":null,
// "opentm":1586822919.3342,
// "closetm":1586822919.365,
// "starttm":0,
// "expiretm":0,
// "descr":{
// "pair":"XBTUSDT",
// "type":"sell",
// "ordertype":"market",
// "price":"0",
// "price2":"0",
// "leverage":"none",
// "order":"sell 0.21804000 XBTUSDT @ market",
// "close":""
// },
// "vol":"0.21804000",
// "vol_exec":"0.21804000",
// "cost":"1493.9",
// "fee":"3.8",
// "price":"6851.5",
// "stopprice":"0.00000",
// "limitprice":"0.00000",
// "misc":"",
// "oflags":"fciq",
// "trades":["TT5UC3-GOIRW-6AZZ6R"]
// }
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::from(vec![])]);
if !(in_op(&result, &id)) {
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)));
}
let __ws_arg_11 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m
}), &[result.as_map().and_then(|__m| id.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null)]);
return self.parse_order(__ws_arg_11, &[]);
Value::Null
}
/*
* @method
* @name kraken#fetchOrderTrades
* @description fetch all the trades made from a single order
* @see https://docs.kraken.com/api-reference/account-data/query-trades-info
* @param {string} id order id
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_order_trades(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __params_empty = indexmap::IndexMap::new();
let params = params.as_map().unwrap_or(&__params_empty);
let mut orderTrades: Value = (match params.get("trades") { Some(__v) if !matches!(__v, Value::Null) && !matches!(__v, Value::Str(__s) if __s.is_empty()) => __v.clone(), _ => Value::Null });
let mut tradeIds: Value = Value::from(vec![]);
if (orderTrades == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrderTrades() requires a unified order structure in the params argument or a 'trades' param (an array of trade id strings)".into()))));
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_835: bool = true;
while { if !__for_first_835 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_835 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&orderTrades).as_f64().unwrap_or(f64::NAN) } {
let mut orderTrade: Value = get_value(&orderTrades, &i);
let mut orderTrade: Value = get_value(&orderTrades, &i);
if matches!(&orderTrade, Value::Str(_)) {
append_to_array(&mut tradeIds, orderTrade.clone());
} else {
append_to_array(&mut tradeIds, crate::value::get_value_k(&orderTrade, "id"));
}
}
}
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolResolved: Value = (if (symbol != Value::Null) { self.symbol(symbol.clone()) } else { symbol });
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchOrderTrades", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut batchSize: Value = self.safe_integer_k(options, "batchSize", &[Value::Int(20)]);
let mut numTradeIds: Value = Value::Int(tradeIds.len() as i64);
let mut numBatches: Value = self.parse_to_int((match ((numTradeIds).as_f64(), (batchSize).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
numBatches = self.sum(&[numBatches.clone(), Value::Int(1)]);
let mut result: Value = Value::from(vec![]);
{
let mut j: Value = Value::Int(0);
let mut __for_first_838: bool = true;
while { if !__for_first_838 { j = (match (&(j), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_838 = false; j.as_f64().unwrap_or(f64::NAN) < numBatches.as_f64().unwrap_or(f64::NAN) } {
let mut requestIds: Value = Value::from(vec![]);
{
let mut k: Value = Value::Int(0);
let mut __for_first_836: bool = true;
while { if !__for_first_836 { k = (match (&(k), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_836 = false; k.as_f64().unwrap_or(f64::NAN) < batchSize.as_f64().unwrap_or(f64::NAN) } {
let mut index: Value = self.sum(&[(match (&(j), &(batchSize)) { (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 }), k.clone()]);
if index.as_f64().unwrap_or(f64::NAN) < numTradeIds.as_f64().unwrap_or(f64::NAN) {
append_to_array(&mut requestIds, get_value(&tradeIds, &index));
}
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("txid".to_string(), join(&requestIds, &Value::Str(",".into())));
m
});
let mut response: Value = self.private_post_query_trades(&[request]).await;
//
// {
// "error": [],
// "result": {
// 'TIMIRG-WUNNE-RRJ6GT': {
// "ordertxid": 'OQRPN2-LRHFY-HIFA7D',
// "postxid": 'TKH2SE-M7IF5-CFI7LT',
// "pair": 'USDCUSDT',
// "time": 1586340086.457,
// "type": 'sell',
// "ordertype": 'market',
// "price": '0.99860000',
// "cost": '22.16892001',
// "fee": '0.04433784',
// "vol": '22.20000000',
// "margin": '0.00000000',
// "misc": ''
// }
// }
// }
//
let mut rawTrades: Value = self.safe_value_k(response, "result", &[]);
let mut ids: Value = object_keys(&rawTrades);
{
let mut i: Value = Value::Int(0);
let mut __for_first_837: bool = true;
while { if !__for_first_837 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_837 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
add_element_to_object(get_value_mut(&mut rawTrades, &ids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)), &Value::Str("id".into()), ids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
}
}
let mut trades: Value = self.parse_trades(rawTrades, &[Value::Null, since.clone(), limit.clone()]);
let mut tradesFilteredBySymbol: Value = self.filter_by_symbol(trades, &[symbolResolved.clone()]);
result = self.array_concat(result.clone(), tradesFilteredBySymbol);
}
}
return result;
Value::Null
}
/*
* @method
* @name kraken#fetchOrdersByIds
* @description fetch orders by the list of order id
* @see https://docs.kraken.com/api-reference/account-data/get-closed-orders
* @param {string[]} [ids] list of order id
* @param {string} [symbol] unified ccxt market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_orders_by_ids(&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 __ws_arg_12 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trades".to_string(), Value::Bool(true));
m.insert("txid".to_string(), join(&ids, &Value::Str(",".into())));
m
}), &[params]);
let mut response: Value = self.private_post_query_orders(&[__ws_arg_12]).await;
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = Value::from(vec![]);
let mut orderIds: Value = object_keys(&result);
{
let mut i: Value = Value::Int(0);
let mut __for_first_839: bool = true;
while { if !__for_first_839 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_839 = false; i.as_f64().unwrap_or(f64::NAN) < ((orderIds.len() as i64) as f64) } {
let mut id: Value = orderIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut item: Value = result.as_map().and_then(|__m| id.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
let __ws_arg_13 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m
}), &[item]);
let mut order: Value = self.parse_order(__ws_arg_13, &[]);
append_to_array(&mut orders, order);
}
}
return orders;
Value::Null
}
/*
* @method
* @name kraken#fetchMyTrades
* @description fetch all trades made by the user
* @see https://docs.kraken.com/api-reference/account-data/get-trades-history
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest trade entry
* @param {int} [params.end] timestamp in seconds of the latest trade entry
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), 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 }))); }
}
let mut until: Value = self.safe_string2(params.clone(), Value::Str("until".into()), Value::Str("till".into()), &[]);
let mut paramsOmitted: Value = (if (until != Value::Null) { self.omit(params.clone(), Value::from(vec![Value::Str("until".into()), Value::Str("till".into())]), &[]) } else { params });
if (until != Value::Null) {
let mut untilDivided: Value = crate::precise::Precise::stringDiv(&until, &Value::Str("1000".into()));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), self.parse_to_int(crate::precise::Precise::stringAdd(&untilDivided, &Value::Str("1".into())))); }
}
let __ws_arg_14 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_trades_history(&[__ws_arg_14]).await;
//
// {
// "error": [],
// "result": {
// "trades": {
// "GJ3NYQ-XJRTF-THZABF": {
// "ordertxid": "TKH2SE-ZIF5E-CFI7LT",
// "postxid": "OEN3VX-M7IF5-JNBJAM",
// "pair": "XICNXETH",
// "time": 1527213229.4491,
// "type": "sell",
// "ordertype": "limit",
// "price": "0.001612",
// "cost": "0.025792",
// "fee": "0.000026",
// "vol": "16.00000000",
// "margin": "0.000000",
// "leverage": "5",
// "misc": ""
// "trade_id": 68230622,
// "maker": false
// },
// ...
// },
// "count": 9760,
// },
// }
//
let mut tradesResult: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut trades: Value = self.safe_dict_k(tradesResult, "trades", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ids: Value = object_keys(&trades);
{
let mut i: Value = Value::Int(0);
let mut __for_first_840: bool = true;
while { if !__for_first_840 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_840 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
add_element_to_object(get_value_mut(&mut trades, &ids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)), &Value::Str("id".into()), ids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
}
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut tradesList: Value = self.to_array(trades);
return self.parse_trades(tradesList, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name kraken#cancelOrder
* @description cancels an open order
* @see https://docs.kraken.com/api-reference/trading/cancel-order
* @param {string} id order id
* @param {string} [symbol] unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] the orders client order id
* @param {int} [params.userref] the orders user reference id
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = Value::Null;
let mut requestId: Value = self.safe_value_k(params.clone(), "userref", &[id.clone()]); // string or integer
let mut paramsUserref: Value = self.omit(params, Value::Str("userref".into()), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("txid".to_string(), requestId);
m
});
let mut clientOrderId: Value = self.safe_string2(paramsUserref.clone(), Value::Str("clientOrderId".into()), Value::Str("cl_ord_id".into()), &[]);
let mut paramsOmitted: Value = (if (clientOrderId != Value::Null) { self.omit(paramsUserref.clone(), Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("cl_ord_id".into())]), &[]) } else { paramsUserref });
if (clientOrderId != Value::Null) {
add_element_to_object(&mut request, &Value::Str("cl_ord_id".into()), clientOrderId);
request = self.omit(request.clone(), Value::Str("txid".into()), &[]);
}
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let __ws_arg_15 = self.extend(request, &[paramsOmitted]);
response = self.private_post_cancel_order(&[__ws_arg_15]).await;
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if (self.last_http_response.clone() != Value::Null) && (self.last_http_response.as_str() != Some("")) {
if Value::Int(self.last_http_response.as_str().and_then(|__s| __s.find("EOrder:Unknown order")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() error ".into())).into()), self.last_http_response.clone())));
}
}
panic!("{}", e);
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[]);
Value::Null
}
/*
* @method
* @name kraken#cancelOrders
* @description cancel multiple orders
* @see https://docs.kraken.com/api-reference/trading/cancel-order-batch
* @param {string[]} ids open orders transaction ID (txid) or user reference (userref)
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orders".to_string(), ids);
m
});
let __ws_arg_16 = self.extend(request, &[params]);
let mut response: Value = self.private_post_cancel_order_batch(&[__ws_arg_16]).await;
return Value::from(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[])]);
Value::Null
}
/*
* @method
* @name kraken#cancelAllOrders
* @description cancel all open orders
* @see https://docs.kraken.com/api-reference/trading/cancel-all-orders
* @param {string} [symbol] unified market symbol, not used by kraken cancelAllOrders (all open orders are cancelled)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut response: Value = self.private_post_cancel_all(&[params]).await;
return Value::from(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[])]);
Value::Null
}
/*
* @method
* @name kraken#cancelAllOrdersAfter
* @description dead man's switch, cancel all orders after the given timeout
* @see https://docs.kraken.com/api-reference/trading/cancel-all-orders-after-x
* @param {number} timeout time in milliseconds, 0 represents cancel the timer
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} the api result
*/
pub async fn cancel_all_orders_after(&mut self, mut timeout: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (timeout == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrdersAfter() missing timeout".into()))));
}
if timeout.as_f64().unwrap_or(f64::NAN) > ((86400000i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrdersAfter timeout should be less than 86400000 milliseconds".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (timeout == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrdersAfter() missing timeout".into()))));
}
let mut request: Value = Value::Map({
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_17 = self.extend(request, &[params]);
let mut response: Value = self.private_post_cancel_all_orders_after(&[__ws_arg_17]).await;
return response;
Value::Null
}
/*
* @method
* @name kraken#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://docs.kraken.com/api-reference/account-data/get-open-orders
* @param {string} [symbol] unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] the orders client order id
* @param {int} [params.userref] the orders user reference id
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), 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 }))); }
}
let mut userref: Value = self.safe_integer_k(params.clone(), "userref", &[]);
let mut paramsOmitted: Value = (if (userref != Value::Null) { self.omit(params.clone(), Value::Str("userref".into()), &[]) } else { params });
if (userref != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("userref".into(), userref); }
}
let mut clientOrderId: Value = self.safe_string_k(paramsOmitted.clone(), "clientOrderId", &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("cl_ord_id".into(), clientOrderId); }
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("clientOrderId".into()), &[]);
}
let __ws_arg_18 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_open_orders(&[__ws_arg_18]).await;
//
// {
// "error": [],
// "result": {
// "open": {
// "O45M52-BFD5S-YXKQOU": {
// "refid": null,
// "userref": null,
// "cl_ord_id": "1234",
// "status": "open",
// "opentm": 1733815269.370054,
// "starttm": 0,
// "expiretm": 0,
// "descr": {
// "pair": "XBTUSD",
// "type": "buy",
// "ordertype": "limit",
// "price": "70000.0",
// "price2": "0",
// "leverage": "none",
// "order": "buy 0.00010000 XBTUSD @ limit 70000.0",
// "close": ""
// },
// "vol": "0.00010000",
// "vol_exec": "0.00000000",
// "cost": "0.00000",
// "fee": "0.00000",
// "price": "0.00000",
// "stopprice": "0.00000",
// "limitprice": "0.00000",
// "misc": "",
// "oflags": "fciq"
// }
// }
// }
// }
//
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut open: Value = self.safe_dict_k(result, "open", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = Value::from(vec![]);
let mut orderIds: Value = object_keys(&open);
{
let mut i: Value = Value::Int(0);
let mut __for_first_841: bool = true;
while { if !__for_first_841 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_841 = false; i.as_f64().unwrap_or(f64::NAN) < ((orderIds.len() as i64) as f64) } {
let mut id: Value = orderIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut item: Value = open.as_map().and_then(|__m| id.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
append_to_array(&mut orders, self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m
}), &[item]));
}
}
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name kraken#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://docs.kraken.com/api-reference/account-data/get-closed-orders
* @param {string} [symbol] unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest entry
* @param {string} [params.clientOrderId] the orders client order id
* @param {int} [params.userref] the orders user reference id
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), 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 }))); }
}
let mut userref: Value = self.safe_integer_k(params.clone(), "userref", &[]);
let mut paramsOmitted: Value = (if (userref != Value::Null) { self.omit(params.clone(), Value::Str("userref".into()), &[]) } else { params });
if (userref != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("userref".into(), userref); }
}
let mut clientOrderId: Value = self.safe_string_k(paramsOmitted.clone(), "clientOrderId", &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("cl_ord_id".into(), clientOrderId); }
paramsOmitted = self.omit(paramsOmitted.clone(), Value::Str("clientOrderId".into()), &[]);
}
{ let __destr_tmp = self.handle_until_option(Value::Str("end".into()), request.clone(), paramsOmitted.clone(), &[]); request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); paramsOmitted = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let __ws_arg_19 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_closed_orders(&[__ws_arg_19]).await;
//
// {
// "error":[],
// "result":{
// "closed":{
// "OETZYO-UL524-QJMXCT":{
// "refid":null,
// "userref":null,
// "status":"canceled",
// "reason":"User requested",
// "opentm":1601489313.3898,
// "closetm":1601489346.5507,
// "starttm":0,
// "expiretm":0,
// "descr":{
// "pair":"ETHUSDT",
// "type":"buy",
// "ordertype":"limit",
// "price":"330.00",
// "price2":"0",
// "leverage":"none",
// "order":"buy 0.02100000 ETHUSDT @ limit 330.00",
// "close":""
// },
// "vol":"0.02100000",
// "vol_exec":"0.00000000",
// "cost":"0.00000",
// "fee":"0.00000",
// "price":"0.00000",
// "stopprice":"0.00000",
// "limitprice":"0.00000",
// "misc":"",
// "oflags":"fciq"
// },
// },
// "count":16
// }
// }
//
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut closed: Value = self.safe_dict_k(result, "closed", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orders: Value = Value::from(vec![]);
let mut orderIds: Value = object_keys(&closed);
{
let mut i: Value = Value::Int(0);
let mut __for_first_842: bool = true;
while { if !__for_first_842 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_842 = false; i.as_f64().unwrap_or(f64::NAN) < ((orderIds.len() as i64) as f64) } {
let mut id: Value = orderIds.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut item: Value = closed.as_map().and_then(|__m| id.as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null);
append_to_array(&mut orders, self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m
}), &[item]));
}
}
return self.parse_orders(orders, &[market, since, limit]);
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value) -> Value {
// IFEX transaction states
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Initial".to_string(), Value::Str("pending".into()));
m.insert("Pending".to_string(), Value::Str("pending".into()));
m.insert("Success".to_string(), Value::Str("ok".into()));
m.insert("Settled".to_string(), Value::Str("pending".into()));
m.insert("Failure".to_string(), Value::Str("failed".into()));
m.insert("Partial".to_string(), Value::Str("ok".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_network(&self, mut network: Value) -> Option<String> {
let mut withdrawMethods: Value = self.safe_dict_k(self.options.clone(), "withdrawMethods", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_string(withdrawMethods, network.clone(), &[network.clone()]).as_str().map(str::to_owned);
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// fetchDeposits
//
// {
// "method": "Ether (Hex)",
// "aclass": "currency",
// "asset": "XETH",
// "refid": "Q2CANKL-LBFVEE-U4Y2WQ",
// "txid": "0x57fd704dab1a73c20e24c8696099b695d596924b401b261513cfdab23…",
// "info": "0x615f9ba7a9575b0ab4d571b2b36b1b324bd83290",
// "amount": "7.9999257900",
// "fee": "0.0000000000",
// "time": 1529223212,
// "status": "Success"
// }
//
// there can be an additional 'status-prop' field present
// deposit pending review by exchange => 'on-hold'
// the deposit is initiated by the exchange => 'return'
//
// {
// "type": 'deposit',
// "method": 'Fidor Bank AG (Wire Transfer)',
// "aclass": 'currency',
// "asset": 'ZEUR',
// "refid": 'xxx-xxx-xxx',
// "txid": '12341234',
// "info": 'BANKCODEXXX',
// "amount": '38769.08',
// "fee": '0.0000',
// "time": 1644306552,
// "status": 'Success',
// status-prop: 'on-hold'
// }
//
//
// fetchWithdrawals
//
// {
// "method": "Ether",
// "aclass": "currency",
// "asset": "XETH",
// "refid": "A2BF34S-O7LBNQ-UE4Y4O",
// "txid": "0x288b83c6b0904d8400ef44e1c9e2187b5c8f7ea3d838222d53f701a15b5c274d",
// "info": "0x7cb275a5e07ba943fee972e165d80daa67cb2dd0",
// "amount": "9.9950000000",
// "fee": "0.0050000000",
// "time": 1530481750,
// "status": "Success"
// "key":"Huobi wallet",
// "network":"Tron"
// status-prop: 'on-hold' // this field might not be present in some cases
// }
//
// withdraw
//
// {
// "refid": "AGBSO6T-UFMTTQ-I7KGS6"
// }
//
let mut id: Value = self.safe_string_k(transaction.clone(), "refid", &[]);
let mut txid: Value = self.safe_string_k(transaction.clone(), "txid", &[]);
let mut timestamp: Value = self.safe_timestamp_k(transaction.clone(), "time", &[]);
let mut currencyId: Value = self.safe_string_k(transaction.clone(), "asset", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[currency]);
let mut address: Value = self.safe_string_k(transaction.clone(), "info", &[]);
let mut amount: Value = self.safe_number_k(transaction.clone(), "amount", &[]);
let mut status: Value = self.parse_transaction_status(self.safe_string_k(transaction.clone(), "status", &[]));
let mut statusProp: Option<String> = self.safe_string_k(transaction.clone(), "status-prop", &[]).as_str().map(str::to_owned);
let mut isOnHoldDeposit: bool = statusProp.as_deref() == Some("on-hold");
let mut isCancellationRequest: bool = statusProp.as_deref() == Some("cancel-pending");
let mut isOnHoldWithdrawal: bool = statusProp.as_deref() == Some("onhold");
if isOnHoldDeposit || isCancellationRequest || isOnHoldWithdrawal {
status = Value::Str("pending".into());
}
let mut type_var: Value = self.safe_string_k(transaction.clone(), "type", &[]); // injected from the outside
let mut feeCost: Value = self.safe_number_k(transaction.clone(), "fee", &[]);
if (feeCost == Value::Null) {
if (type_var.as_str() == Some("deposit")) {
feeCost = Value::Int(0);
}
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), id);
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), amount);
m.insert("network".to_string(), self.parse_network(self.safe_string_k(transaction, "network", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("address".to_string(), address);
m.insert("addressTo".to_string(), Value::Null);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("tag".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("type".to_string(), type_var);
m.insert("updated".to_string(), Value::Null);
m.insert("txid".to_string(), txid);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("comment".to_string(), Value::Null);
m.insert("internal".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), code);
m.insert("cost".to_string(), feeCost);
m
}));
m
});
Value::Null
}
pub fn parse_transactions_by_type(&self, mut type_var: Value, mut transactions: Value, 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 result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_843: bool = true;
while { if !__for_first_843 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_843 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&transactions).as_f64().unwrap_or(f64::NAN) } {
let __ws_arg_20 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), type_var.clone());
m
}), &[get_value(&transactions, &i)]);
let mut transaction: Value = self.parse_transaction(__ws_arg_20, &[]);
append_to_array(&mut result, transaction);
}
}
return self.filter_by_currency_since_limit(result, &[code, since, limit]);
Value::Null
}
/*
* @method
* @name kraken#fetchDeposits
* @description fetch all deposits made to an account
* @see https://docs.kraken.com/api-reference/funding/get-status-of-recent-deposits
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest transaction entry
* @param {int} [params.end] timestamp in seconds of the latest transaction entry
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// https://www.kraken.com/en-us/help/api#deposit-status
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (code != Value::Null) {
let mut currency: Value = self.currency(code.clone());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("asset".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
let mut sinceString: Value = self.number_to_string(since.clone());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), crate::precise::Precise::stringDiv(&sinceString, &Value::Str("1000".into()))); }
}
let mut until: Value = self.safe_string2(params.clone(), Value::Str("until".into()), Value::Str("till".into()), &[]);
let mut paramsOmitted: Value = (if (until != Value::Null) { self.omit(params.clone(), Value::from(vec![Value::Str("until".into()), Value::Str("till".into())]), &[]) } else { params });
if (until != Value::Null) {
let mut untilDivided: Value = crate::precise::Precise::stringDiv(&until, &Value::Str("1000".into()));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), crate::precise::Precise::stringAdd(&untilDivided, &Value::Str("1".into()))); }
}
let __ws_arg_21 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_deposit_status(&[__ws_arg_21]).await;
//
// { error: [],
// "result": [ { "method": "Ether (Hex)",
// "aclass": "currency",
// "asset": "XETH",
// "refid": "Q2CANKL-LBFVEE-U4Y2WQ",
// "txid": "0x57fd704dab1a73c20e24c8696099b695d596924b401b261513cfdab23…",
// "info": "0x615f9ba7a9575b0ab4d571b2b36b1b324bd83290",
// "amount": "7.9999257900",
// "fee": "0.0000000000",
// "time": 1529223212,
// "status": "Success" } ] }
//
let mut depositResult: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
return self.parse_transactions_by_type(Value::Str("deposit".into()), depositResult, &[code, since, limit]);
Value::Null
}
/*
* @method
* @name kraken#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://docs.kraken.com/api-reference/market-data/get-server-time
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// https://www.kraken.com/en-us/features/api#get-server-time
let mut response: Value = self.public_get_time(&[params]).await;
//
// {
// "error": [],
// "result": {
// "unixtime": 1591502873,
// "rfc1123": "Sun, 7 Jun 20 04:07:53 +0000"
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_timestamp_k(result, "unixtime", &[]);
Value::Null
}
/*
* @method
* @name kraken#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://docs.kraken.com/api-reference/funding/get-status-of-recent-withdrawals
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest transaction entry
* @param {int} [params.end] timestamp in seconds of the latest transaction entry
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginateparamsPaginateVariable = self.handle_option_bool_and_params(params, Value::Str("fetchWithdrawals".into()), Value::Str("paginate".into()), &[Value::Bool(false)]);
let mut paginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if is_true(&paginate) {
add_element_to_object(&mut paramsPaginate, &Value::Str("cursor".into()), Value::Bool(true));
return self.fetch_paginated_call_cursor(Value::Str("fetchWithdrawals".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("next_cursor".into()), Value::Str("cursor".into())]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (code != Value::Null) {
let mut currency: Value = self.currency(code.clone());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("asset".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
let mut sinceString: Value = self.number_to_string(since.clone());
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("start".into(), crate::precise::Precise::stringDiv(&sinceString, &Value::Str("1000".into()))); }
}
let mut until: Value = self.safe_string2(paramsPaginate.clone(), Value::Str("until".into()), Value::Str("till".into()), &[]);
let mut paramsOmitted: Value = (if (until != Value::Null) { self.omit(paramsPaginate.clone(), Value::from(vec![Value::Str("until".into()), Value::Str("till".into())]), &[]) } else { paramsPaginate });
if (until != Value::Null) {
let mut untilDivided: Value = crate::precise::Precise::stringDiv(&until, &Value::Str("1000".into()));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("end".into(), crate::precise::Precise::stringAdd(&untilDivided, &Value::Str("1".into()))); }
}
let __ws_arg_22 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_withdraw_status(&[__ws_arg_22]).await;
//
// with no pagination
// { error: [],
// "result": [ { "method": "Ether",
// "aclass": "currency",
// "asset": "XETH",
// "refid": "A2BF34S-O7LBNQ-UE4Y4O",
// "txid": "0x298c83c7b0904d8400ef43e1c9e2287b518f7ea3d838822d53f704a1565c274d",
// "info": "0x7cb275a5e07ba943fee972e165d80daa67cb2dd0",
// "amount": "9.9950000000",
// "fee": "0.0050000000",
// "time": 1530481750,
// "status": "Success" } ] }
// with pagination
// {
// "error":[],
// "result":{
// "withdrawals":[
// {
// "method":"Tether USD (TRC20)",
// "aclass":"currency",
// "asset":"USDT",
// "refid":"BSNFZU2-MEFN4G-J3NEZV",
// "txid":"1c7a642fb7387bbc2c6a2c509fd1ae146937f4cf793b4079a4f0715e3a02615a",
// "info":"TQmdxSuC16EhFg8FZWtYgrfFRosoRF7bCp",
// "amount":"1996.50000000",
// "fee":"2.50000000",
// "time":1669126657,
// "status":"Success",
// "key":"poloniex",
// "network":"Tron"
// },
// ...
// ],
// "next_cursor":"HgAAAAAAAABGVFRSd3k1LVF4Y0JQY05Gd0xRY0NxenFndHpybkwBAQH2AwEBAAAAAQAAAAAAAAABAAAAAAAZAAAAAAAAAA=="
// }
// }
//
let mut rawWithdrawals: Value = Value::Null;
let mut result: Value = self.safe_value_k(response, "result", &[]);
if !(matches!(&result, Value::Arr(_))) {
rawWithdrawals = self.add_pagination_cursor_to_result(result.clone());
} else {
rawWithdrawals = result;
}
return self.parse_transactions_by_type(Value::Str("withdrawal".into()), rawWithdrawals, &[code, since, limit]);
Value::Null
}
pub fn add_pagination_cursor_to_result(&self, mut result: Value) -> Value {
let mut cursor: Value = self.safe_string_k(result.clone(), "next_cursor", &[]);
let mut data: Value = self.safe_value_k(result, "withdrawals", &[]);
let mut dataLength: Value = get_array_length(&data);
if (cursor != Value::Null) && dataLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
let mut last: Value = get_value(&data, &subtract(&dataLength, &Value::Int(1)));
add_element_to_object(&mut last, &Value::Str("next_cursor".into()), cursor);
add_element_to_object(&mut data, &subtract(&dataLength, &Value::Int(1)), last);
}
return data;
Value::Null
}
/*
* @method
* @name kraken#createDepositAddress
* @description create a currency deposit address
* @see https://docs.kraken.com/api-reference/funding/get-deposit-addresses
* @param {string} code unified currency code of the currency for the deposit address
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [address structure]{@link https://docs.ccxt.com/?id=address-structure}
*/
pub async fn create_deposit_address(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("new".to_string(), Value::Str("true".into()));
m
});
let __ws_arg_23 = self.extend(request, &[params]);
return self.fetch_deposit_address(code, &[__ws_arg_23]).await;
Value::Null
}
/*
* @method
* @name kraken#fetchDepositMethods
* @description fetch deposit methods for a currency associated with this account
* @see https://docs.kraken.com/api-reference/funding/get-deposit-methods
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} of deposit methods
*/
pub async fn fetch_deposit_methods(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_24 = self.extend(request, &[params]);
let mut response: Value = self.private_post_deposit_methods(&[__ws_arg_24]).await;
return self.safe_value_k(response, "result", &[]);
Value::Null
}
/*
* @method
* @name kraken#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://docs.kraken.com/api-reference/funding/get-deposit-addresses
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [address structure]{@link https://docs.ccxt.com/?id=address-structure}
*/
pub async fn fetch_deposit_address(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut network: Value = self.safe_string_upper_k(params.clone(), "network", &[]);
let mut networks: Value = self.safe_dict_k(self.options.clone(), "networks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
network = self.safe_string(networks, network.clone(), &[network.clone()]); // support ETH > ERC20 aliases
let mut paramsOmitted: Value = self.omit(params, Value::Str("network".into()), &[]);
let mut codeResolved: Value = code.clone();
if (code.as_str() == Some("USDT")) && (network.as_str() == Some("TRC20")) {
codeResolved = Value::Str(format!("{}{}", Value::Str(format!("{}{}", code, Value::Str("-".into())).into()), network).into());
}
let mut defaultDepositMethods: Value = self.safe_dict_k(self.options.clone(), "depositMethods", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultDepositMethod: Value = self.safe_string(defaultDepositMethods, codeResolved.clone(), &[]);
let mut depositMethod: Value = self.safe_string_k(paramsOmitted.clone(), "method", &[defaultDepositMethod]);
// if the user has specified an exchange-specific method in params
// we pass it as is, otherwise we take the 'network' unified param
if (depositMethod == Value::Null) {
let mut depositMethods: Value = self.fetch_deposit_methods(codeResolved.clone(), &[]).await;
if (network != Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_844: bool = true;
while { if !__for_first_844 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_844 = false; i.as_f64().unwrap_or(f64::NAN) < ((depositMethods.len() as i64) as f64) } {
let mut entry: Value = self.safe_string(depositMethods.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null), Value::Str("method".into()), &[]);
if (entry == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchDepositAddress() missing entry".into()))));
}
if get_index_of(&entry, &network).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
depositMethod = entry.clone();
break;
}
}
}
}
// if depositMethod was not specified, fallback to the first available deposit method
if (depositMethod == Value::Null) {
let mut firstDepositMethod: Value = self.safe_dict(depositMethods, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
depositMethod = self.safe_string_k(firstDepositMethod, "method", &[]);
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("method".to_string(), depositMethod);
m
});
let __ws_arg_25 = self.extend(request, &[paramsOmitted]);
let mut response: Value = self.private_post_deposit_addresses(&[__ws_arg_25]).await;
//
// {
// "error":[],
// "result":[
// {"address":"0x77b5051f97efa9cc52c9ad5b023a53fc15c200d3","expiretm":"0"}
// ]
// }
//
let mut result: Value = self.safe_list_k(response, "result", &[Value::from(vec![])]);
let mut firstResult: Value = self.safe_dict(result, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (firstResult == Value::Null) {
panic!("{}", crate::exchange_errors::invalid_address(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" privatePostDepositAddresses() returned no addresses for ".into())).into()), codeResolved)));
}
return self.parse_deposit_address(firstResult, &[currency]);
Value::Null
}
pub fn parse_deposit_address(&self, mut depositAddress: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
// {
// "address":"0x77b5051f97efa9cc52c9ad5b023a53fc15c200d3",
// "expiretm":"0"
// }
//
let mut address: Value = self.safe_string_k(depositAddress.clone(), "address", &[]);
let mut tag: Value = self.safe_string_k(depositAddress.clone(), "tag", &[]);
let mut currencyResolved: Value = self.safe_currency(Value::Null, &[currency]);
let mut code: Value = currencyResolved.as_map().and_then(|__m| __m.get("code")).cloned().unwrap_or(Value::Null);
self.check_address(&[address.clone()]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), depositAddress);
m.insert("currency".to_string(), code);
m.insert("network".to_string(), Value::Null);
m.insert("address".to_string(), address);
m.insert("tag".to_string(), tag);
m
});
Value::Null
}
/*
* @method
* @name kraken#withdraw
* @description make a withdrawal
* @see https://docs.kraken.com/api-reference/funding/withdraw-funds
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to, not required can be '' or undefined/none/null
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.tag] memo / destination tag, required for currencies in options['withdrawTagRequiredCurrencies']
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut tagAndParams: Value = self.handle_param_string(params, Value::Str("tag".into()), &[]);
let mut tagWithdrawTag: Value = tagAndParams.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsWithdrawTag: Value = tagAndParams.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (matches!(¶msWithdrawTag, Value::Dict(__d) if __d.contains_key("key"))) {
self.load_markets(&[]).await;
let mut currency: Value = self.currency(code.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("amount".to_string(), amount);
m
});
if (address != Value::Null) && (address.as_str() != Some("")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("address".into(), address.clone()); }
self.check_address(&[address, code, tagWithdrawTag]);
}
let __ws_arg_26 = self.extend(request, &[paramsWithdrawTag.clone()]);
let mut response: Value = self.private_post_withdraw(&[__ws_arg_26]).await;
//
// {
// "error": [],
// "result": {
// "refid": "AGBSO6T-UFMTTQ-I7KGS6"
// }
// }
//
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transaction(result, &[currency]);
}
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" withdraw() requires a 'key' parameter (withdrawal key name, as set up on your account)".into()))));
Value::Null
}
/*
* @method
* @name kraken#fetchPositions
* @description fetch all open positions
* @see https://docs.kraken.com/api-reference/account-data/get-open-positions
* @param {string[]} [symbols] not used by fetchPositions ()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("docalcs".to_string(), Value::Str("true".into()));
m.insert("consolidation".to_string(), Value::Str("market".into()));
m
});
let __ws_arg_27 = self.extend(request, &[params]);
let mut response: Value = self.private_post_open_positions(&[__ws_arg_27]).await;
//
// no consolidation
//
// {
// "error": [],
// "result": {
// 'TGUFMY-FLESJ-VYIX3J': {
// "ordertxid": "O3LRNU-ZKDG5-XNCDFR",
// "posstatus": "open",
// "pair": "ETHUSDT",
// "time": 1611557231.4584,
// "type": "buy",
// "ordertype": "market",
// "cost": "28.49800",
// "fee": "0.07979",
// "vol": "0.02000000",
// "vol_closed": "0.00000000",
// "margin": "14.24900",
// "terms": "0.0200% per 4 hours",
// "rollovertm": "1611571631",
// "misc": "",
// "oflags": ""
// }
// }
// }
//
// consolidation by market
//
// {
// "error": [],
// "result": [
// {
// "pair": "ETHUSDT",
// "positions": "1",
// "type": "buy",
// "leverage": "2.00000",
// "cost": "28.49800",
// "fee": "0.07979",
// "vol": "0.02000000",
// "vol_closed": "0.00000000",
// "margin": "14.24900"
// }
// ]
// }
//
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut result: Value = self.safe_list_k(response, "result", &[]);
let mut results: Value = self.parse_positions(result, &[symbolsNormalized.clone()]);
return self.filter_by_array_positions(results, Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "pair": "ETHUSDT",
// "positions": "1",
// "type": "buy",
// "leverage": "2.00000",
// "cost": "28.49800",
// "fee": "0.07979",
// "vol": "0.02000000",
// "vol_closed": "0.00000000",
// "margin": "14.24900"
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "pair", &[]);
let mut rawSide: Option<String> = self.safe_string_k(position.clone(), "type", &[]).as_str().map(str::to_owned);
let mut side: Value = Value::Str("short".into());
if (rawSide.as_deref() == Some("buy")) {
side = Value::Str("long".into());
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("notional".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("entryPrice".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), self.safe_number_k(position.clone(), "net", &[]));
m.insert("realizedPnl".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("contracts".to_string(), self.safe_number_k(position.clone(), "vol", &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("markPrice".to_string(), Value::Null);
m.insert("lastPrice".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("hedged".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), self.safe_number_k(position.clone(), "margin", &[]));
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("leverage".to_string(), self.safe_number_k(position, "leverage", &[]));
m.insert("marginRatio".to_string(), Value::Null);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
pub fn parse_account_type(&self, mut account: Value) -> Value {
let mut accountByType: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("Spot Wallet".into()));
m.insert("swap".to_string(), Value::Str("Futures Wallet".into()));
m.insert("future".to_string(), Value::Str("Futures Wallet".into()));
m
});
return self.safe_string(accountByType, account.clone(), &[account.clone()]);
Value::Null
}
/*
* @method
* @name kraken#transferOut
* @description transfer from spot wallet to futures wallet
* @see https://docs.kraken.com/api-reference/transfers/initiate-wallet-transfer
* @param {str} code Unified currency code
* @param {float} amount Size of the transfer
* @param {dict} [params] Exchange specific parameters
* @returns a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
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("spot".into()), Value::Str("swap".into()), &[params]).await;
Value::Null
}
/*
* @method
* @name kraken#transfer
* @see https://docs.kraken.com/api-reference/transfers/initiate-wallet-transfer
* @description transfers currencies between sub-accounts (only spot->swap direction is supported)
* @param {string} code Unified currency code
* @param {float} amount Size of the transfer
* @param {string} fromAccount 'spot' or 'Spot Wallet'
* @param {string} toAccount 'swap' or 'Futures Wallet'
* @param {object} [params] Exchange specific parameters
* @returns a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut fromAccountParsed: Value = self.parse_account_type(fromAccount);
let mut toAccountParsed: Value = self.parse_account_type(toAccount);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.currency_to_precision(code, amount.clone(), &[]));
m.insert("from".to_string(), fromAccountParsed.clone());
m.insert("to".to_string(), toAccountParsed.clone());
m.insert("asset".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (fromAccountParsed.as_str() != Some("Spot Wallet")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" transfer cannot transfer from ".into())).into()), fromAccountParsed).into()), Value::Str(" to ".into())).into()), toAccountParsed).into()), Value::Str(". Use krakenfutures instead to transfer from the futures account.".into()))));
}
let __ws_arg_28 = self.extend(request, &[params]);
let mut response: Value = self.private_post_wallet_transfer(&[__ws_arg_28]).await;
//
// {
// "error":[
// ],
// "result":{
// "refid":"BOIUSIF-M7DLMN-UXZ3P5"
// }
// }
//
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(), fromAccountParsed);
m.insert("toAccount".to_string(), toAccountParsed);
m
})]);
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);
//
// transfer
//
// {
// "error":[
// ],
// "result":{
// "refid":"BOIUSIF-M7DLMN-UXZ3P5"
// }
// }
//
let mut result: Value = self.safe_dict_k(transfer.clone(), "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut refid: Value = self.safe_string_k(result, "refid", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer);
m.insert("id".to_string(), refid);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), 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(), Value::Str("sucess".into()));
m
});
Value::Null
}
pub fn sign(&mut self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("public".into()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("/".into()), self.version.clone()).into()), Value::Str("/".into())).into()), api).into()), Value::Str("/".into())).into()), path).into());
if (api.as_str() == Some("public")) {
if ((object_keys(¶ms).len() as i64) as f64) > ((0i64) as f64) {
// rawencode is used to address https://github.com/ccxt/ccxt/issues/12872
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode_nested(params.clone(), &[])).into())).into());
}
} else if (api.as_str() == Some("private")) {
let mut price: Value = self.safe_string_k(params.clone(), "price", &[]);
let mut isTriggerPercent: Value = Value::Bool(false);
if (price != Value::Null) {
isTriggerPercent = (if (ends_with(&price, &Value::Str("%".into()))) { Value::Bool(true) } else { Value::Bool(false) });
}
let mut isCancelOrderBatch: bool = path.as_str() == Some("CancelOrderBatch");
let mut isBatchOrder: bool = path.as_str() == Some("AddOrderBatch");
self.check_required_credentials(&[]);
// kraken rejects a nonce that is not greater than the previous one for the key (EAPI:Invalid nonce)
let mut nonce: Value = to_string_val(&self.incrementing_nonce());
let mut isJsonBody: bool = isCancelOrderBatch || is_true(&isTriggerPercent) || isBatchOrder;
// rawencode is used to address https://github.com/ccxt/ccxt/issues/12872
let mut bodySigned: Value = Value::Null;
if isJsonBody {
let __ws_arg_29 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
}), &[params.clone()]);
bodySigned = self.json(__ws_arg_29);
} else {
let __ws_arg_30 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
}), &[params]);
bodySigned = self.urlencode_nested(__ws_arg_30, &[]);
}
let mut auth: Value = self.encode(Value::Str(format!("{}{}", nonce, bodySigned).into()));
let mut hash: Value = self.hash(auth, Value::Str("sha256".into()), &[Value::Str("binary".into())]);
let mut binary: Value = self.encode(url.clone());
let mut binhash: Value = self.binary_concat(binary, &[hash]);
let mut secret: Value = self.base64_to_binary(self.secret.clone(), &[]);
let mut signature: Value = self.hmac(binhash, secret, Value::Str("sha512".into()), &[Value::Str("base64".into())]);
let mut headersSigned: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("API-Key".to_string(), self.apiKey.clone());
m.insert("API-Sign".to_string(), signature);
m
});
if isJsonBody {
if let Value::Dict(__d) = &mut headersSigned { std::sync::Arc::make_mut(__d).insert("Content-Type".into(), Value::Str("application/json".into())); }
} else {
if let Value::Dict(__d) = &mut headersSigned { std::sync::Arc::make_mut(__d).insert("Content-Type".into(), Value::Str("application/x-www-form-urlencoded".into())); }
}
let mut baseApiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), api.clone(), &[]);
if (baseApiUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
let mut urlSigned: Value = Value::Str(format!("{}{}", baseApiUrl, url).into());
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), urlSigned);
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), bodySigned);
m.insert("headers".to_string(), headersSigned);
m
});
} else {
url = Value::Str(format!("{}{}", Value::Str("/".into()), path).into());
}
let mut apiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), api, &[]);
if (apiUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str(format!("{}{}", apiUrl, url).into()));
m.insert("method".to_string(), method);
m.insert("body".to_string(), body);
m.insert("headers".to_string(), headers);
m
});
Value::Null
}
pub fn nonce(&self) -> Value {
return (match (&(self.milliseconds()), &(self.safe_integer_k(self.options.clone(), "timeDifference", &[Value::Int(0)]))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
Value::Null
}
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 (code.as_f64() == Some(520.0)) {
panic!("{}", crate::exchange_errors::exchange_not_available(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), to_string_val(&code)).into()), Value::Str(" ".into())).into()), reason)));
}
if (response == Value::Null) {
return Value::Null;
}
if (get_value(&body, &Value::Int(0)).as_str() == Some("{")) {
if !matches!(&response, Value::Str(_)) {
let mut message: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
if (in_op(&response, &Value::Str("error".into()))) {
let mut numErrors: Value = get_array_length(&get_value(&response, &Value::Str("error".into())));
if numErrors.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_845: bool = true;
while { if !__for_first_845 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_845 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&get_value(&response, &Value::Str("error".into()))).as_f64().unwrap_or(f64::NAN) } {
let mut error: Value = get_value(&crate::value::get_value_k(&response, "error"), &i);
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), error.clone(), message.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), error.clone(), message.clone());
}
}
panic!("{}", crate::exchange_errors::exchange_error(message));
}
}
// handleCreateOrdersErrors:
if (in_op(&response, &Value::Str("result".into()))) {
let mut result: Value = self.safe_dict_k(response, "result", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (matches!(&result, Value::Dict(__d) if __d.contains_key("orders"))) {
let mut orders: Value = self.safe_list_k(result, "orders", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_846: bool = true;
while { if !__for_first_846 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_846 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut order: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut error: Value = self.safe_string_k(order, "error", &[]);
if (error != Value::Null) {
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), error.clone(), message.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), error, message.clone());
panic!("{}", crate::exchange_errors::exchange_error(message));
}
}
}
}
}
}
}
return Value::Null;
Value::Null
}
}