// 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;
pub struct BlofinCore {
pub exchange: crate::exchange::Exchange,
}
impl BlofinCore {
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 = BlofinCore::describe(self);
self.initialize_properties(described);
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
}
/// 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 BlofinCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_ticker(self, ticker, &[market.clone()])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_trade(self, trade, &[market.clone()])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_order(self, order, &[market.clone()])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_ohlcv(self, ohlcv, &[market.clone()])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_position(self, position, &[market.clone()])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_funding_rate(self, rate, &[market.clone()])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_ledger_entry(self, entry, &[currency.clone()])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_transfer(self, transfer, &[currency.clone()])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_transaction(self, transaction, &[currency.clone()])
}
fn parse_adl_rank(&self, info: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_adl_rank(self, info, &[market.clone()])
}
fn parse_margin_mode(&self, margin_mode: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_margin_mode(self, margin_mode, &[market.clone()])
}
fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on BlofinCore.
BlofinCore::parse_leverage(self, leverage, &[market.clone()])
}
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 BlofinCore.
BlofinCore::sign(self, path, &[api.clone(), method.clone(), params.clone(), headers.clone(), body.clone()])
}
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 BlofinCore.
BlofinCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for BlofinCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"close_position" => self.close_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args.get(4..).unwrap_or(&[]).to_vec()[..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"create_tpsl_order_request" => self.create_tpsl_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..).unwrap_or(&[]).to_vec()[..]),
"fetch_balance" => self.fetch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_deposits" => self.fetch_deposits(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ledger" => self.fetch_ledger(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_leverage" => self.fetch_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_leverages" => self.fetch_leverages(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_margin_mode" => self.fetch_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_mark_price" => self.fetch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_markets" => self.fetch_markets(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_position_mode" => self.fetch_position_mode(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions" => self.fetch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions_adl_rank" => self.fetch_positions_adl_rank(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_positions_history" => self.fetch_positions_history(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_tickers" => self.fetch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"parse_adl_rank" => self.parse_adl_rank(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_balance_by_type" => self.parse_balance_by_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_funding_balance" => self.parse_funding_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ids" => self.parse_ids(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ledger_entry_type" => self.parse_ledger_entry_type(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_leverage" => self.parse_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_margin_mode" => self.parse_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_trading_fee" => self.parse_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"parse_transaction_deposit_status" => self.parse_transaction_deposit_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_transaction_withdrawal_status" => self.parse_transaction_withdrawal_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"set_position_mode" => self.set_position_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
"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.get(4..).unwrap_or(&[]).to_vec()[..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for BlofinCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for BlofinCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl BlofinCore {
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("blofin".to_string()));
m.insert("name".to_string(), Value::Str("BloFin".to_string()));
m.insert("countries".to_string(), Value::List(vec![Value::Str("US".to_string())]));
m.insert("version".to_string(), Value::Str("v1".to_string()));
m.insert("rateLimit".to_string(), Value::Int(100));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(false));
m.insert("borrowMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(false));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(true));
m.insert("createDepositAddress".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(false));
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("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(true));
m.insert("createPostOnlyOrder".to_string(), Value::Bool(false));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(false));
m.insert("createStopLimitOrder".to_string(), Value::Bool(false));
m.insert("createStopLossOrder".to_string(), Value::Bool(true));
m.insert("createStopMarketOrder".to_string(), Value::Bool(false));
m.insert("createStopOrder".to_string(), Value::Bool(false));
m.insert("createTakeProfitOrder".to_string(), Value::Bool(true));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(false));
m.insert("fetchAccounts".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBidsAsks".to_string(), Value::Null);
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("fetchCanceledOrders".to_string(), Value::Bool(false));
m.insert("fetchClosedOrder".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(false));
m.insert("fetchDeposit".to_string(), Value::Bool(false));
m.insert("fetchDepositAddress".to_string(), Value::Bool(false));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDepositAddressesByNetwork".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositsWithdrawals".to_string(), Value::Bool(false));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Str("emulated".to_string()));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(false));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(false));
m.insert("fetchGreeks".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("fetchL3OrderBook".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLedgerEntry".to_string(), Value::Null);
m.insert("fetchLeverage".to_string(), Value::Bool(true));
m.insert("fetchLeverages".to_string(), Value::Bool(true));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Bool(true));
m.insert("fetchMarginModes".to_string(), Value::Bool(false));
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(false));
m.insert("fetchMySettlementHistory".to_string(), Value::Bool(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(false));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
m.insert("fetchOpenOrder".to_string(), Value::Null);
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Null);
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrderBooks".to_string(), Value::Bool(false));
m.insert("fetchOrders".to_string(), Value::Bool(false));
m.insert("fetchOrderTrades".to_string(), Value::Bool(true));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositionADLRank".to_string(), Value::Bool(true));
m.insert("fetchPositionMode".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsADLRank".to_string(), Value::Bool(true));
m.insert("fetchPositionsForSymbol".to_string(), Value::Bool(false));
m.insert("fetchPositionsHistory".to_string(), Value::Bool(true));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchSettlementHistory".to_string(), Value::Bool(false));
m.insert("fetchStatus".to_string(), Value::Bool(false));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(false));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(false));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTradingLimits".to_string(), Value::Bool(false));
m.insert("fetchTransactionFee".to_string(), Value::Bool(false));
m.insert("fetchTransactionFees".to_string(), Value::Bool(false));
m.insert("fetchTransactions".to_string(), Value::Bool(false));
m.insert("fetchTransfer".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(false));
m.insert("fetchUnderlyingAssets".to_string(), Value::Bool(false));
m.insert("fetchVolatilityHistory".to_string(), Value::Bool(false));
m.insert("fetchWithdrawal".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("fetchWithdrawalWhitelist".to_string(), Value::Bool(false));
m.insert("reduceMargin".to_string(), Value::Bool(false));
m.insert("repayCrossMargin".to_string(), Value::Bool(false));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMargin".to_string(), Value::Bool(false));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(true));
m.insert("signIn".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(false));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".to_string()));
m.insert("3m".to_string(), Value::Str("3m".to_string()));
m.insert("5m".to_string(), Value::Str("5m".to_string()));
m.insert("15m".to_string(), Value::Str("15m".to_string()));
m.insert("30m".to_string(), Value::Str("30m".to_string()));
m.insert("1h".to_string(), Value::Str("1H".to_string()));
m.insert("2h".to_string(), Value::Str("2H".to_string()));
m.insert("4h".to_string(), Value::Str("4H".to_string()));
m.insert("6h".to_string(), Value::Str("6H".to_string()));
m.insert("8h".to_string(), Value::Str("8H".to_string()));
m.insert("12h".to_string(), Value::Str("12H".to_string()));
m.insert("1d".to_string(), Value::Str("1D".to_string()));
m.insert("3d".to_string(), Value::Str("3D".to_string()));
m.insert("1w".to_string(), Value::Str("1W".to_string()));
m.insert("1M".to_string(), Value::Str("1M".to_string()));
m
}));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/67edf117-6217-4cb8-95e7-9b03f314b1b1".to_string()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rest".to_string(), Value::Str("https://openapi.blofin.com".to_string()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rest".to_string(), Value::Str("https://demo-trading-openapi.blofin.com".to_string()));
m
}));
m.insert("referral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str("https://blofin.com/register?referral_code=f79EsS".to_string()));
m.insert("discount".to_string(), Value::Float(0.05));
m
}));
m.insert("www".to_string(), Value::Str("https://www.blofin.com".to_string()));
m.insert("doc".to_string(), Value::Str("https://blofin.com/docs".to_string()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market/instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/books".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/mark-price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/funding-rate".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/funding-rate-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/index-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/mark-price-candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/position-tiers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset/balances".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/bills".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/withdrawal-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/deposit-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/currencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/positions-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/margin-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/position-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/leverage-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/batch-leverage-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order-detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-tpsl-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order-tpsl-detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-algo-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-tpsl-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders-algo-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/fills-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order/price-range".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("affiliate/basic".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("affiliate/referral-code".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("affiliate/invitees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("affiliate/sub-invitees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("affiliate/sub-affiliates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("affiliate/invitees/daily/info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/config".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/account/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/account/positions-by-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/account/positions-details-by-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/account/positions-by-contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/account/position-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/account/leverage-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/orders-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/pending-tpsl-by-contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/position-history-by-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/orders-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/pending-tpsl-by-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("user/query-apikey".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/trade/fills-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("asset/demo-apply-money".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/set-margin-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/set-position-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("account/set-leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order-tpsl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/cancel-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/cancel-batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/cancel-tpsl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/cancel-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/close-position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/account/set-position-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/account/set-leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/place-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/cancel-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/place-tpsl-by-contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/cancel-tpsl-by-contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/place-tpsl-by-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/cancel-tpsl-by-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/close-position-by-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("copytrading/trade/close-position-by-contract".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.00060".to_string()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.00020".to_string()), &[]));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(true));
m.insert("password".to_string(), Value::Bool(true));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("default".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Int(10));
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::Int(100));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("untilDays".to_string(), Value::Int(100000));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Null);
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(100));
m.insert("trigger".to_string(), Value::Bool(true));
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::Int(1000));
m.insert("daysBack".to_string(), Value::Int(100000));
m.insert("daysBackCanceled".to_string(), Value::Int(1));
m.insert("untilDays".to_string(), Value::Int(100000));
m.insert("trigger".to_string(), Value::Bool(true));
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(1440));
m
}));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".to_string()));
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(false));
m.insert("takeProfitPrice".to_string(), Value::Bool(false));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m.insert("hedged".to_string(), Value::Bool(false));
m
}));
m
}));
m.insert("forDerivatives".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".to_string()));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(true));
m.insert("triggerPrice".to_string(), Value::Bool(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::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("price".to_string(), Value::Bool(true));
m
}));
m.insert("hedged".to_string(), Value::Bool(true));
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forDerivatives".to_string()));
m
}));
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("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("400".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("401".to_string(), Value::Str("AuthenticationError".to_string()).clone());
m.insert("500".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("404".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("405".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("406".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("429".to_string(), Value::Str("RateLimitExceeded".to_string()).clone());
m.insert("152001".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("152002".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("152003".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("152004".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("152005".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("152006".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("152007".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("152008".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("152009".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("150003".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("150004".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("542".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102002".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102005".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102014".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102015".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102022".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102037".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102038".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102039".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102040".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102047".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102048".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102049".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102050".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102051".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102052".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102053".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102054".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102055".to_string(), Value::Str("InvalidOrder".to_string()).clone());
m.insert("102064".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("102065".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("102068".to_string(), Value::Str("BadRequest".to_string()).clone());
m.insert("103013".to_string(), Value::Str("ExchangeError".to_string()).clone());
m.insert("Order failed. Insufficient USDT margin in account".to_string(), Value::Str("InsufficientFunds".to_string()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Internal Server Error".to_string(), Value::Str("ExchangeNotAvailable".to_string()).clone());
m.insert("server error".to_string(), Value::Str("ExchangeNotAvailable".to_string()).clone());
m
}));
m
}));
m.insert("httpExceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("429".to_string(), Value::Str("ExchangeNotAvailable".to_string()).clone());
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountsByType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("swap".to_string(), Value::Str("futures".to_string()));
m.insert("funding".to_string(), Value::Str("funding".to_string()));
m.insert("future".to_string(), Value::Str("futures".to_string()));
m.insert("copy_trading".to_string(), Value::Str("copy_trading".to_string()));
m.insert("earn".to_string(), Value::Str("earn".to_string()));
m.insert("spot".to_string(), Value::Str("spot".to_string()));
m
}));
m.insert("accountsById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("funding".to_string(), Value::Str("funding".to_string()));
m.insert("futures".to_string(), Value::Str("swap".to_string()));
m.insert("copy_trading".to_string(), Value::Str("copy_trading".to_string()));
m.insert("earn".to_string(), Value::Str("earn".to_string()));
m.insert("spot".to_string(), Value::Str("spot".to_string()));
m
}));
m.insert("defaultNetwork".to_string(), Value::Str("ERC20".to_string()));
m.insert("defaultNetworks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ETH".to_string(), Value::Str("ERC20".to_string()));
m.insert("BTC".to_string(), Value::Str("BTC".to_string()));
m.insert("USDT".to_string(), Value::Str("TRC20".to_string()));
m
}));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("BTC".to_string(), Value::Str("Bitcoin".to_string()));
m.insert("BEP20".to_string(), Value::Str("BSC".to_string()));
m.insert("ERC20".to_string(), Value::Str("ERC20".to_string()));
m.insert("TRC20".to_string(), Value::Str("TRC20".to_string()));
m
}));
m.insert("fetchOpenInterestHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("5m".to_string(), Value::Str("5m".to_string()));
m.insert("1h".to_string(), Value::Str("1H".to_string()));
m.insert("8h".to_string(), Value::Str("8H".to_string()));
m.insert("1d".to_string(), Value::Str("1D".to_string()));
m.insert("5M".to_string(), Value::Str("5m".to_string()));
m.insert("1H".to_string(), Value::Str("1H".to_string()));
m.insert("8H".to_string(), Value::Str("8H".to_string()));
m.insert("1D".to_string(), Value::Str("1D".to_string()));
m
}));
m
}));
m.insert("defaultType".to_string(), Value::Str("swap".to_string()));
m.insert("brokerId".to_string(), Value::Str("ec6dd3a7dd982d0b".to_string()));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetTradeOrdersPending".to_string()));
m
}));
m.insert("cancelOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privatePostTradeCancelBatchOrders".to_string()));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetTradeOrdersHistory".to_string()));
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("password".to_string(), Value::Null);
m.insert("pwd".to_string(), Value::Null);
m
}));
m.insert("exchangeType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("SPOT".to_string()));
m.insert("swap".to_string(), Value::Str("SWAP".to_string()));
m.insert("SPOT".to_string(), Value::Str("SPOT".to_string()));
m.insert("SWAP".to_string(), Value::Str("SWAP".to_string()));
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name blofin#fetchMarkets
* @description retrieves data on all markets for blofin
* @see https://blofin.com/docs#get-instruments
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_market_instruments(&[params.clone()]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_markets(data.clone());
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
let mut id: Value = self.safe_string_k(market.clone(), "instId", &[]);
let mut type_var: Value = self.safe_string_lower(market.clone(), Value::Str("instType".to_string()), &[]);
let mut spot: Value = Value::Bool(is_equal(&type_var, &Value::Str("spot".to_string())));
let mut future: Value = Value::Bool(is_equal(&type_var, &Value::Str("future".to_string())));
let mut swap: Value = Value::Bool(is_equal(&type_var, &Value::Str("swap".to_string())));
let mut option: Value = Value::Bool(is_equal(&type_var, &Value::Str("option".to_string())));
let mut contract: Value = Value::Bool(is_true(&swap) || is_true(&future));
let mut baseId: Value = self.safe_string_k(market.clone(), "baseCurrency", &[]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "quoteCurrency", &[]);
let mut settleId: Value = self.safe_string_k(market.clone(), "settleCurrency", &[quoteId.clone()]);
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
let mut symbol: Value = add(&add(&base, &Value::Str("/".to_string())), "e);
if is_true(&swap) {
symbol = add(&add(&symbol, &Value::Str(":".to_string())), &settle);
}
let mut expiry: Value = Value::Null;
let mut strikePrice: Value = Value::Null;
let mut optionType: Value = Value::Null;
let mut tickSize: Value = self.safe_string_k(market.clone(), "tickSize", &[]);
let mut fees: Value = self.safe_dict2(self.fees.clone(), type_var.clone(), Value::Str("trading".to_string()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut taker: Value = self.safe_number_k(fees.clone(), "taker", &[]);
let mut maker: Value = self.safe_number_k(fees.clone(), "maker", &[]);
let mut maxLeverage: Value = self.safe_string_k(market.clone(), "maxLeverage", &[Value::Str("100".to_string())]);
maxLeverage = crate::precise::Precise::stringMax(&maxLeverage, &Value::Str("1".to_string()));
let mut isActive: Value = Value::Bool(is_equal(&self.safe_string_k(market.clone(), "state", &[]), &Value::Str("live".to_string())));
let mut isMargin: Value = Value::Bool(is_true(&spot) && is_true(&(crate::precise::Precise::stringGt(&maxLeverage, &Value::Str("1".to_string())))));
let mut contractType: Value = self.safe_string_k(market.clone(), "contractType", &[]);
let mut maxLimitAmount: Value = self.safe_number_k(market.clone(), "maxLimitSize", &[]);
let mut maxSpotCost: Value = self.safe_number_k(market.clone(), "maxMarketSize", &[]); // for spot, market-buy size is denominated in the quote currency, i.e. cost
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("base".to_string(), base.clone());
m.insert("quote".to_string(), quote.clone());
m.insert("baseId".to_string(), baseId.clone());
m.insert("quoteId".to_string(), quoteId.clone());
m.insert("settle".to_string(), settle.clone());
m.insert("settleId".to_string(), settleId.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("spot".to_string(), spot.clone());
m.insert("option".to_string(), option.clone());
m.insert("margin".to_string(), isMargin.clone());
m.insert("swap".to_string(), swap.clone());
m.insert("future".to_string(), future.clone());
m.insert("active".to_string(), isActive.clone());
m.insert("taker".to_string(), taker.clone());
m.insert("maker".to_string(), maker.clone());
m.insert("contract".to_string(), contract.clone());
m.insert("linear".to_string(), ternary(is_true(&contract), Value::Bool((is_equal(&contractType, &Value::Str("linear".to_string())))), Value::Null));
m.insert("inverse".to_string(), ternary(is_true(&contract), Value::Bool((is_equal(&contractType, &Value::Str("inverse".to_string())))), Value::Null));
m.insert("contractSize".to_string(), ternary(is_true(&contract), self.safe_number_k(market.clone(), "contractValue", &[]), Value::Null));
m.insert("expiry".to_string(), expiry.clone());
m.insert("expiryDatetime".to_string(), expiry.clone());
m.insert("strike".to_string(), strikePrice.clone());
m.insert("optionType".to_string(), optionType.clone());
m.insert("created".to_string(), self.safe_integer_k(market.clone(), "listTime", &[]));
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.safe_number_k(market.clone(), "lotSize", &[]));
m.insert("price".to_string(), self.parse_number(tickSize.clone(), &[]));
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".to_string()), &[]));
m.insert("max".to_string(), self.parse_number(maxLeverage.clone(), &[]));
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(), "minSize", &[]));
m.insert("max".to_string(), maxLimitAmount.clone());
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), ternary(is_true(&contract), Value::Null, maxSpotCost.clone()));
m
}));
m
}));
m.insert("info".to_string(), market.clone());
m
})]);
Value::Null
}
/*
* @method
* @name blofin#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://blofin.com/docs#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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
limit = ternary(is_true(&(is_equal(&limit, &Value::Null))), Value::Int(50), limit.clone());
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("size".to_string()), limit.clone()); // max 100
}
let __ws_arg_0 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_market_books(&[__ws_arg_0]).await;
//
// {
// "code": "0",
// "msg": "",
// "data": [
// {
// "asks": [
// ["0.07228","4.211619","0","2"], // price, amount, liquidated orders, total open orders
// ["0.0723","299.880364","0","2"],
// ["0.07231","3.72832","0","1"],
// ],
// "bids": [
// ["0.07221","18.5","0","1"],
// ["0.0722","18.5","0","1"],
// ["0.07219","0.505407","0","1"],
// ],
// "ts": "1621438475342"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_k(first.clone(), "ts", &[]);
return self.parse_order_book(first.clone(), symbol.clone(), &[timestamp.clone()]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// response similar for REST & WS
//
// {
// instId: "ADA-USDT",
// ts: "1707736811486",
// last: "0.5315",
// lastSize: "4",
// askPrice: "0.5318",
// askSize: "248",
// bidPrice: "0.5315",
// bidSize: "63",
// open24h: "0.5555",
// high24h: "0.5563",
// low24h: "0.5315",
// volCurrency24h: "198560100",
// vol24h: "1985601",
// }
//
let mut timestamp: Value = self.safe_integer_k(ticker.clone(), "ts", &[]);
let mut marketId: Value = self.safe_string_k(ticker.clone(), "instId", &[]);
market = self.safe_market(&[marketId.clone(), market.clone(), Value::Str("-".to_string())]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut last: Value = self.safe_string_k(ticker.clone(), "last", &[]);
let mut open: Value = self.safe_string_k(ticker.clone(), "open24h", &[]);
let mut spot: Value = self.safe_bool_k(market.clone(), "spot", &[Value::Bool(false)]);
let mut quoteVolume: Value = ternary(is_true(&(is_equal(&spot, &Value::Bool(true)))), self.safe_string_k(ticker.clone(), "volCurrency24h", &[]), Value::Null);
let mut baseVolume: Value = self.safe_string_k(ticker.clone(), "vol24h", &[]);
let mut high: Value = self.safe_string_k(ticker.clone(), "high24h", &[]);
let mut low: Value = self.safe_string_k(ticker.clone(), "low24h", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("high".to_string(), high.clone());
m.insert("low".to_string(), low.clone());
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "bidPrice", &[]));
m.insert("bidVolume".to_string(), self.safe_string_k(ticker.clone(), "bidSize", &[]));
m.insert("ask".to_string(), self.safe_string_k(ticker.clone(), "askPrice", &[]));
m.insert("askVolume".to_string(), self.safe_string_k(ticker.clone(), "askSize", &[]));
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), open.clone());
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last.clone());
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.clone());
m.insert("quoteVolume".to_string(), quoteVolume.clone());
m.insert("indexPrice".to_string(), self.safe_string_k(ticker.clone(), "indexPrice", &[]));
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "markPrice", &[]));
m.insert("info".to_string(), ticker.clone());
m
}), &[market.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://blofin.com/docs#get-tickers
* @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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let __ws_arg_1 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_market_tickers(&[__ws_arg_1]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(first.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchMarkPrice
* @description fetches mark price for the market
* @see https://docs.blofin.com/index.html#get-mark-price
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subType] "linear" or "inverse"
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_mark_price(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &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("symbol".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let __ws_arg_2 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_market_mark_price(&[__ws_arg_2]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(first.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://blofin.com/docs#get-tickers
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/?id=ticker-structure}
*/
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut response: Value = self.public_get_market_tickers(&[params.clone()]).await;
let mut tickers: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_tickers(tickers.clone(), &[symbols.clone()]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetch trades (response similar for REST & WS)
//
// {
// "tradeId": "3263934920",
// "instId": "LTC-USDT",
// "price": "67.87",
// "size": "1",
// "side": "buy",
// "ts": "1707232020854"
// }
//
// my trades
// {
// "instId": "LTC-USDT",
// "tradeId": "1440847",
// "orderId": "2075705202",
// "fillPrice": "67.850000000000000000",
// "fillSize": "1.000000000000000000",
// "fillPnl": "0.000000000000000000",
// "side": "buy",
// "positionSide": "net",
// "fee": "0.040710000000000000",
// "ts": "1707224678878",
// "brokerId": ""
// }
//
// fetchMyTrades spot
// {
// "instId": "DOGE-USDT",
// "tradeId": "6000001623870",
// "orderId": "6000011777113",
// "fillPrice": "0.091480000000000000",
// "fillSize": "30.000000000000000000",
// "fillPnl": null,
// "side": "buy",
// "fee": "0.030000000000000000",
// "ts": "1775213753407",
// "brokerId": null,
// "feeCurrency": "base_currency"
// }
//
let mut id: Value = self.safe_string_k(trade.clone(), "tradeId", &[]);
let mut marketId: Value = self.safe_string_k(trade.clone(), "instId", &[]);
market = self.safe_market(&[marketId.clone(), market.clone(), Value::Str("-".to_string())]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "ts", &[]);
let mut price: Value = self.safe_string2(trade.clone(), Value::Str("price".to_string()), Value::Str("fillPrice".to_string()), &[]);
let mut amount: Value = self.safe_string2(trade.clone(), Value::Str("size".to_string()), Value::Str("fillSize".to_string()), &[]);
let mut side: Value = self.safe_string_k(trade.clone(), "side", &[]);
let mut orderId: Value = self.safe_string_k(trade.clone(), "orderId", &[]);
let mut feeCost: Value = self.safe_string_k(trade.clone(), "fee", &[]);
let mut fee: Value = Value::Null;
let mut feeCurrency: Value = self.safe_string_k(trade.clone(), "feeCurrency", &[]);
let mut isSpot: bool = !is_equal(&feeCurrency, &Value::Null);
if is_equal(&feeCurrency, &Value::Null) {
feeCurrency = get_value(&market, &Value::Str("settle".to_string()));
} else if is_equal(&feeCurrency, &Value::Str("base_currency".to_string())) {
feeCurrency = get_value(&market, &Value::Str("base".to_string()));
} else if is_equal(&feeCurrency, &Value::Str("quote_currency".to_string())) {
feeCurrency = get_value(&market, &Value::Str("quote".to_string()));
}
if !is_equal(&feeCost, &Value::Null) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), feeCost.clone());
m.insert("currency".to_string(), feeCurrency.clone());
m
});
}
if is_true(&isSpot) {
let mut spotSymbol: Value = add(&add(&get_value(&market, &Value::Str("base".to_string())), &Value::Str("/".to_string())), &get_value(&market, &Value::Str("quote".to_string())));
let mut cost: Value = self.parse_number(crate::precise::Precise::stringMul(&price, &amount), &[]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("symbol".to_string(), spotSymbol.clone());
m.insert("id".to_string(), id.clone());
m.insert("order".to_string(), orderId.clone());
m.insert("type".to_string(), Value::Null);
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), self.parse_number(price.clone(), &[]));
m.insert("amount".to_string(), self.parse_number(amount.clone(), &[]));
m.insert("cost".to_string(), cost.clone());
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(feeCost.clone(), &[]));
m.insert("currency".to_string(), feeCurrency.clone());
m
}));
m
});
return result;
} else {
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("symbol".to_string(), symbol.clone());
m.insert("id".to_string(), id.clone());
m.insert("order".to_string(), orderId.clone());
m.insert("type".to_string(), Value::Null);
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), price.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee.clone());
m
}), &[market.clone()]);
}
Value::Null
}
/*
* @method
* @name blofin#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://blofin.com/docs#get-trades
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] *only applies to publicGetMarketHistoryTrades* default false, when true will automatically paginate by calling this endpoint multiple times
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTrades".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchTrades".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("tradeId".to_string()), Value::Str("after".to_string()), Value::Null, Value::Int(100)]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut response: Value = Value::Null;
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone()); // default 100
}
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTrades".to_string()), Value::Str("method".to_string()), &[Value::Str("publicGetMarketTrades".to_string())]); method = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&method, &Value::Str("publicGetMarketTrades".to_string())) {
let __ws_arg_3 = self.extend(request.clone(), &[params.clone()]);
response = self.public_get_market_trades(&[__ws_arg_3]).await;
}
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_trades(data.clone(), &[market.clone(), since.clone(), limit.clone()]);
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::List(vec![self.safe_integer(ohlcv.clone(), Value::Int(0), &[]), self.safe_number(ohlcv.clone(), Value::Int(1), &[]), self.safe_number(ohlcv.clone(), Value::Int(2), &[]), self.safe_number(ohlcv.clone(), Value::Int(3), &[]), self.safe_number(ohlcv.clone(), Value::Int(4), &[]), self.safe_number(ohlcv.clone(), Value::Int(6), &[])]);
Value::Null
}
/*
* @method
* @name blofin#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://blofin.com/docs#get-candlesticks
* @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 {int} [params.until] timestamp in ms of the latest candle to fetch
* @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".to_string()));
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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".to_string()), &[symbol.clone(), since.clone(), limit.clone(), timeframe.clone(), params.clone(), Value::Int(100)]).await;
}
if is_equal(&limit, &Value::Null) {
limit = Value::Int(100); // default 100, max 100
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("bar".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m.insert("limit".to_string(), limit.clone());
m
});
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("after".to_string()), until.clone());
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
}
let __ws_arg_4 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_market_candles(&[__ws_arg_4]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_ohlc_vs(data.clone(), &[market.clone(), timeframe.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://blofin.com/docs#get-funding-rate-history
* @param {string} symbol unified symbol of the market to fetch the funding rate history for
* @param {int} [since] timestamp in ms of the earliest funding rate to fetch
* @param {int} [limit] the maximum amount of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure} to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @param {int} [params.until] timestamp in ms of the latest funding rate to fetch
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/?id=funding-rate-history-structure}
*/
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchFundingRateHistory() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchFundingRateHistory".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchFundingRateHistory".to_string()), &[symbol.clone(), since.clone(), limit.clone(), Value::Str("8h".to_string()), params.clone(), Value::Int(100)]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("before".to_string()), crate::runtime::Math::max(&subtract(&since, &Value::Int(1)), &Value::Int(0)));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if !is_equal(&until, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("after".to_string()), until.clone());
params = self.omit(params.clone(), Value::Str("until".to_string()), &[]);
}
let __ws_arg_5 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_market_funding_rate_history(&[__ws_arg_5]).await;
let mut rates: Value = Value::List(vec![]);
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_439: bool = true;
while { if !__for_first_439 { i = add(&i, &Value::Int(1)); } __for_first_439 = false; is_less_than(&i, &get_array_length(&data)) } {
let mut rate: Value = get_value(&data, &i);
let mut rate: Value = get_value(&data, &i);
let mut timestamp: Value = self.safe_integer_k(rate.clone(), "fundingTime", &[]);
append_to_array(&mut rates, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), rate.clone());
m.insert("symbol".to_string(), get_value(&market, &Value::Str("symbol".to_string())));
m.insert("fundingRate".to_string(), self.safe_number_k(rate.clone(), "fundingRate", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m
}));
}
}
let mut sorted: Value = self.sort_by(rates.clone(), Value::Str("timestamp".to_string()), &[]);
return self.filter_by_symbol_since_limit(sorted.clone(), &[get_value(&market, &Value::Str("symbol".to_string())), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_funding_rate(&self, mut contract: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "fundingRate": "0.00027815",
// "fundingTime": "1634256000000",
// "instId": "BTC-USD-SWAP",
// }
//
let mut marketId: Value = self.safe_string_k(contract.clone(), "instId", &[]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone()]);
let mut fundingTime: Value = self.safe_integer_k(contract.clone(), "fundingTime", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
m.insert("interestRate".to_string(), self.parse_number(Value::Str("0".to_string()), &[]));
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("fundingRate".to_string(), self.safe_number_k(contract.clone(), "fundingRate", &[]));
m.insert("fundingTimestamp".to_string(), fundingTime.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(fundingTime.clone()));
m.insert("nextFundingRate".to_string(), Value::Null);
m.insert("nextFundingTimestamp".to_string(), Value::Null);
m.insert("nextFundingDatetime".to_string(), Value::Null);
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name blofin#fetchFundingRate
* @description fetch the current funding rate
* @see https://blofin.com/docs#get-funding-rate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
if !is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
panic!("{}", crate::exchange_errors::exchange_error(add(&self.id, &Value::Str(" fetchFundingRate() is only valid for swap markets".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let __ws_arg_6 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.public_get_market_funding_rate(&[__ws_arg_6]).await;
//
// {
// "code": "0",
// "data": [
// {
// "fundingRate": "0.00027815",
// "fundingTime": "1634256000000",
// "instId": "BTC-USD-SWAP",
// }
// ],
// "msg": ""
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut entry: Value = self.safe_dict(data.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_funding_rate(entry.clone(), &[market.clone()]);
Value::Null
}
pub fn parse_balance_by_type(&self, mut response: Value) -> Value {
let mut data: Value = self.safe_list_k(response.clone(), "data", &[]);
if is_true(&(!is_equal(&data, &Value::Null))) && is_true(&Value::Bool(is_array(&data))) {
return self.parse_funding_balance(response.clone());
} else {
return self.parse_balance(response.clone());
}
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
//
// "data" similar for REST & WS
//
// {
// "code": "0",
// "msg": "success",
// "data": {
// "ts": "1697021343571",
// "totalEquity": "10011254.077985990315787910",
// "isolatedEquity": "861.763132108800000000",
// "details": [
// {
// "currency": "USDT",
// "equity": "10014042.988958415234430699548",
// "balance": "10013119.885958415234430699",
// "ts": "1697021343571",
// "isolatedEquity": "862.003200000000000000048",
// "available": "9996399.4708691159703362725",
// "availableEquity": "9996399.4708691159703362725",
// "frozen": "15805.149672632597427761",
// "orderFrozen": "14920.994472632597427761",
// "equityUsd": "10011254.077985990315787910",
// "isolatedUnrealizedPnl": "-22.151999999999999999952",
// "bonus": "0" // present only in REST
// "unrealizedPnl": "0" // present only in WS
// }
// ]
// }
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_k(data.clone(), "ts", &[]);
let mut details: Value = self.safe_list_k(data.clone(), "details", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_440: bool = true;
while { if !__for_first_440 { i = add(&i, &Value::Int(1)); } __for_first_440 = false; is_less_than(&i, &get_array_length(&details)) } {
let mut balance: Value = get_value(&details, &i);
let mut balance: Value = get_value(&details, &i);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut account: Value = self.account();
// it may be incorrect to use total, free and used for swap accounts
let mut eq: Value = self.safe_string_k(balance.clone(), "equity", &[]);
let mut availEq: Value = self.safe_string_k(balance.clone(), "available", &[]);
if is_true(&(is_equal(&eq, &Value::Null))) || is_true(&(is_equal(&availEq, &Value::Null))) {
add_element_to_object(&mut account, &Value::Str("free".to_string()), self.safe_string_k(balance.clone(), "availableEquity", &[]));
add_element_to_object(&mut account, &Value::Str("used".to_string()), self.safe_string_k(balance.clone(), "frozen", &[]));
} else {
add_element_to_object(&mut account, &Value::Str("total".to_string()), eq.clone());
add_element_to_object(&mut account, &Value::Str("free".to_string()), availEq.clone());
}
add_element_to_object(&mut result, &code, account.clone());
}
}
add_element_to_object(&mut result, &Value::Str("timestamp".to_string()), timestamp.clone());
add_element_to_object(&mut result, &Value::Str("datetime".to_string()), self.iso8601(timestamp.clone()));
return self.safe_balance(result.clone());
Value::Null
}
pub fn parse_funding_balance(&self, mut response: Value) -> Value {
//
// {
// "code": "0",
// "msg": "success",
// "data": [
// {
// "currency": "USDT",
// "balance": "10012514.919418081548717298",
// "available": "9872132.414278782284622898",
// "frozen": "138556.471805965930761067",
// "bonus": "0"
// }
// ]
// }
//
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_441: bool = true;
while { if !__for_first_441 { i = add(&i, &Value::Int(1)); } __for_first_441 = false; is_less_than(&i, &get_array_length(&data)) } {
let mut balance: Value = get_value(&data, &i);
let mut balance: Value = get_value(&data, &i);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut account: Value = self.account();
// it may be incorrect to use total, free and used for swap accounts
add_element_to_object(&mut account, &Value::Str("total".to_string()), self.safe_string_k(balance.clone(), "balance", &[]));
add_element_to_object(&mut account, &Value::Str("free".to_string()), self.safe_string_k(balance.clone(), "available", &[]));
add_element_to_object(&mut account, &Value::Str("used".to_string()), self.safe_string_k(balance.clone(), "frozen", &[]));
add_element_to_object(&mut result, &code, account.clone());
}
}
return self.safe_balance(result.clone());
Value::Null
}
pub fn parse_trading_fee(&self, mut fee: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("maker".to_string(), self.parse_number(crate::precise::Precise::stringNeg(&self.safe_string2(fee.clone(), Value::Str("maker".to_string()), Value::Str("makerU".to_string()), &[])), &[]));
m.insert("taker".to_string(), self.parse_number(crate::precise::Precise::stringNeg(&self.safe_string2(fee.clone(), Value::Str("taker".to_string()), Value::Str("takerU".to_string()), &[])), &[]));
m.insert("percentage".to_string(), Value::Null);
m.insert("tierBased".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name blofin#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://blofin.com/docs#get-balance
* @see https://blofin.com/docs#get-futures-account-balance
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.accountType] the type of account to fetch the balance for, either 'funding' or 'futures' or 'copy_trading' or 'earn'
* @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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut accountType: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params2(params.clone(), Value::Str("fetchBalance".to_string()), Value::Str("accountType".to_string()), Value::Str("type".to_string()), &[]); accountType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if !is_equal(&accountType, &Value::Null) && !is_equal(&accountType, &Value::Str("swap".to_string())) {
let mut options: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut parsedAccountType: Value = self.safe_string(options.clone(), accountType.clone(), &[accountType.clone()]);
add_element_to_object(&mut request, &Value::Str("accountType".to_string()), parsedAccountType.clone());
let __ws_arg_7 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_asset_balances(&[__ws_arg_7]).await;
} else {
let __ws_arg_8 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_account_balance(&[__ws_arg_8]).await;
}
return self.parse_balance_by_type(response.clone());
Value::Null
}
pub fn create_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&type_var, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires a type argument".to_string()))));
}
if is_equal(&side, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires a side argument".to_string()))));
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("side".to_string(), side.clone());
m.insert("orderType".to_string(), type_var.clone());
m.insert("size".to_string(), self.amount_to_precision(symbol.clone(), amount.clone()));
m.insert("brokerId".to_string(), self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("ec6dd3a7dd982d0b".to_string())]));
m
});
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("createOrder".to_string()), &[params.clone(), Value::Str("cross".to_string())]); marginMode = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
add_element_to_object(&mut request, &Value::Str("marginMode".to_string()), marginMode.clone());
let mut triggerPriceAny: Value = self.safe_string_n(params.clone(), Value::List(vec![Value::Str("triggerPrice".to_string()), Value::Str("stopLossPrice".to_string()), Value::Str("takeProfitPrice".to_string())]), &[]);
let mut triggerPriceSlTp: Value = self.safe_string2(params.clone(), Value::Str("stopLossPrice".to_string()), Value::Str("takeProfitPrice".to_string()), &[]);
let mut timeInForce: Value = self.safe_string_k(params.clone(), "timeInForce", &[Value::Str("GTC".to_string())]);
let mut isHedged: Value = self.safe_bool_k(params.clone(), "hedged", &[Value::Bool(false)]);
if is_equal(&isHedged, &Value::Bool(true)) {
add_element_to_object(&mut request, &Value::Str("positionSide".to_string()), ternary(is_true(&(is_equal(&side, &Value::Str("buy".to_string())))), Value::Str("long".to_string()), Value::Str("short".to_string())));
}
let mut isMarketOrder: Value = Value::Bool(is_equal(&type_var, &Value::Str("market".to_string())));
params = self.omit(params.clone(), Value::List(vec![Value::Str("timeInForce".to_string())]), &[]);
let mut ioc: bool = is_true(&(is_equal(&timeInForce, &Value::Str("IOC".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("ioc".to_string()))));
let mut marketIOC: bool = is_true(&isMarketOrder) && is_true(&ioc);
if is_true(&isMarketOrder) || is_true(&marketIOC) {
add_element_to_object(&mut request, &Value::Str("orderType".to_string()), Value::Str("market".to_string()));
} else {
let mut key: Value = ternary(is_true(&(!is_equal(&triggerPriceAny, &Value::Null))), Value::Str("orderPrice".to_string()), Value::Str("price".to_string()));
add_element_to_object(&mut request, &key, self.price_to_precision(symbol.clone(), price.clone()));
}
let mut postOnly: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_post_only(isMarketOrder.clone(), Value::Bool(is_equal(&type_var, &Value::Str("post_only".to_string()))), &[params.clone()]); postOnly = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&postOnly) {
add_element_to_object(&mut request, &Value::Str("type".to_string()), Value::Str("post_only".to_string()));
}
let mut stopLoss: Value = self.safe_dict_k(params.clone(), "stopLoss", &[]);
let mut takeProfit: Value = self.safe_dict_k(params.clone(), "takeProfit", &[]);
params = self.omit(params.clone(), Value::List(vec![Value::Str("stopLoss".to_string()), Value::Str("takeProfit".to_string()), Value::Str("hedged".to_string())]), &[]);
let mut hasStopLoss: bool = !is_equal(&stopLoss, &Value::Null);
let mut hasTakeProfit: bool = !is_equal(&takeProfit, &Value::Null);
if is_true(&hasStopLoss) || is_true(&hasTakeProfit) {
if is_true(&hasStopLoss) {
let mut slTriggerPrice: Value = self.safe_string2(stopLoss.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("slTriggerPrice".to_string()), self.price_to_precision(symbol.clone(), slTriggerPrice.clone()));
let mut slOrderPrice: Value = self.safe_string_k(stopLoss.clone(), "price", &[Value::Str("-1".to_string())]);
add_element_to_object(&mut request, &Value::Str("slOrderPrice".to_string()), self.price_to_precision(symbol.clone(), slOrderPrice.clone()));
}
if is_true(&hasTakeProfit) {
let mut tpTriggerPrice: Value = self.safe_string2(takeProfit.clone(), Value::Str("triggerPrice".to_string()), Value::Str("stopPrice".to_string()), &[]);
add_element_to_object(&mut request, &Value::Str("tpTriggerPrice".to_string()), self.price_to_precision(symbol.clone(), tpTriggerPrice.clone()));
let mut tpPrice: Value = self.safe_string_k(takeProfit.clone(), "price", &[Value::Str("-1".to_string())]);
add_element_to_object(&mut request, &Value::Str("tpOrderPrice".to_string()), self.price_to_precision(symbol.clone(), tpPrice.clone()));
}
} else if !is_equal(&triggerPriceAny, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("orderType".to_string()), Value::Str("trigger".to_string()));
add_element_to_object(&mut request, &Value::Str("triggerPrice".to_string()), self.price_to_precision(symbol.clone(), triggerPriceAny.clone()));
if is_true(&isMarketOrder) {
add_element_to_object(&mut request, &Value::Str("orderPrice".to_string()), Value::Str("-1".to_string()));
}
if !is_equal(&triggerPriceSlTp, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("reduceOnly".to_string()), Value::Bool(true));
}
params = self.omit(params.clone(), Value::List(vec![Value::Str("stopLossPrice".to_string()), Value::Str("takeProfitPrice".to_string()), Value::Str("triggerPrice".to_string())]), &[]);
}
return self.extend(request.clone(), &[params.clone()]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("canceled".to_string(), Value::Str("canceled".to_string()));
m.insert("order_failed".to_string(), Value::Str("canceled".to_string()));
m.insert("live".to_string(), Value::Str("open".to_string()));
m.insert("partially_filled".to_string(), Value::Str("open".to_string()));
m.insert("filled".to_string(), Value::Str("closed".to_string()));
m.insert("effective".to_string(), Value::Str("closed".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// response similar for REST & WS
//
// {
// "orderId": "2075628533",
// "clientOrderId": "",
// "instId": "LTC-USDT",
// "marginMode": "cross",
// "positionSide": "net",
// "side": "buy",
// "orderType": "market",
// "price": "0.000000000000000000",
// "size": "1.000000000000000000",
// "reduceOnly": "true",
// "leverage": "3",
// "state": "filled",
// "filledSize": "1.000000000000000000",
// "pnl": "-0.050000000000000000",
// "averagePrice": "68.110000000000000000",
// "fee": "0.040866000000000000",
// "createTime": "1706891359010",
// "updateTime": "1706891359098",
// "orderCategory": "normal",
// "tpTriggerPrice": null,
// "tpOrderPrice": null,
// "slTriggerPrice": null,
// "slOrderPrice": null,
// "cancelSource": "not_canceled",
// "cancelSourceReason": null,
// "brokerId": "ec6dd3a7dd982d0b"
// "filled_amount": "1.000000000000000000", // filledAmount in "ws" watchOrders
// "cancelSource": "", // only in WS
// "instType": "SWAP", // only in WS
// }
//
let mut id: Value = self.safe_string_n(order.clone(), Value::List(vec![Value::Str("tpslId".to_string()), Value::Str("orderId".to_string()), Value::Str("algoId".to_string())]), &[]);
let mut timestamp: Value = self.safe_integer_k(order.clone(), "createTime", &[]);
let mut lastUpdateTimestamp: Value = self.safe_integer_k(order.clone(), "updateTime", &[]);
let mut lastTradeTimestamp: Value = self.safe_integer_k(order.clone(), "fillTime", &[]);
let mut side: Value = self.safe_string_k(order.clone(), "side", &[]);
let mut type_var: Value = self.safe_string_k(order.clone(), "orderType", &[]);
let mut postOnly: Value = Value::Null;
let mut timeInForce: Value = Value::Null;
if is_equal(&type_var, &Value::Str("post_only".to_string())) {
postOnly = Value::Bool(true);
type_var = Value::Str("limit".to_string());
} else if is_equal(&type_var, &Value::Str("fok".to_string())) {
timeInForce = Value::Str("FOK".to_string());
type_var = Value::Str("limit".to_string());
} else if is_equal(&type_var, &Value::Str("ioc".to_string())) {
timeInForce = Value::Str("IOC".to_string());
type_var = Value::Str("limit".to_string());
} else if is_equal(&type_var, &Value::Str("conditional".to_string())) {
type_var = Value::Str("trigger".to_string());
}
let mut marketId: Value = self.safe_string_k(order.clone(), "instId", &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut symbol: Value = self.safe_symbol(marketId.clone(), &[market.clone(), Value::Str("-".to_string())]);
let mut filled: Value = self.safe_string_k(order.clone(), "filledSize", &[]);
let mut price: Value = self.safe_string_n(order.clone(), Value::List(vec![Value::Str("px".to_string()), Value::Str("price".to_string()), Value::Str("orderPrice".to_string())]), &[]);
let mut average: Value = self.safe_string_k(order.clone(), "averagePrice", &[]);
let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "state", &[]));
let mut feeCostString: Value = self.safe_string_k(order.clone(), "fee", &[]);
let mut amount: Value = self.safe_string_k(order.clone(), "size", &[]);
let mut contractSize: Value = self.safe_string_k(market.clone(), "contractSize", &[]);
let mut baseAmount: Value = crate::precise::Precise::stringMul(&contractSize, &filled);
let mut cost: Value = Value::Null;
if !is_equal(&average, &Value::Null) {
cost = crate::precise::Precise::stringMul(&average, &baseAmount);
}
// spot market buy: "sz" can refer either to base currency units or to quote currency units
let mut fee: Value = Value::Null;
if !is_equal(&feeCostString, &Value::Null) {
let mut feeCostSigned: Value = crate::precise::Precise::stringAbs(&feeCostString);
let mut feeCurrencyId: Value = self.safe_string_k(order.clone(), "feeCcy", &[Value::Str("USDT".to_string())]);
let mut feeCurrencyCode: Value = self.safe_currency_code(feeCurrencyId.clone(), &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(feeCostSigned.clone(), &[]));
m.insert("currency".to_string(), feeCurrencyCode.clone());
m
});
}
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "clientOrderId", &[]);
if is_true(&(!is_equal(&clientOrderId, &Value::Null))) && is_true(&(is_less_than(&get_array_length(&clientOrderId), &Value::Int(1)))) {
clientOrderId = Value::Null; // fix empty clientOrderId string
}
let mut stopLossTriggerPrice: Value = self.safe_number_k(order.clone(), "slTriggerPrice", &[]);
let mut stopLossPrice: Value = self.safe_number_k(order.clone(), "slOrderPrice", &[]);
let mut takeProfitTriggerPrice: Value = self.safe_number_k(order.clone(), "tpTriggerPrice", &[]);
let mut takeProfitPrice: Value = self.safe_number_k(order.clone(), "tpOrderPrice", &[]);
let mut reduceOnlyRaw: Value = self.safe_string_k(order.clone(), "reduceOnly", &[]);
let mut reduceOnly: Value = Value::Bool(is_equal(&reduceOnlyRaw, &Value::Str("true".to_string())));
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), id.clone());
m.insert("clientOrderId".to_string(), clientOrderId.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("lastTradeTimestamp".to_string(), lastTradeTimestamp.clone());
m.insert("lastUpdateTimestamp".to_string(), lastUpdateTimestamp.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("timeInForce".to_string(), timeInForce.clone());
m.insert("postOnly".to_string(), postOnly.clone());
m.insert("side".to_string(), side.clone());
m.insert("price".to_string(), price.clone());
m.insert("stopLossTriggerPrice".to_string(), stopLossTriggerPrice.clone());
m.insert("takeProfitTriggerPrice".to_string(), takeProfitTriggerPrice.clone());
m.insert("stopLossPrice".to_string(), stopLossPrice.clone());
m.insert("takeProfitPrice".to_string(), takeProfitPrice.clone());
m.insert("average".to_string(), average.clone());
m.insert("cost".to_string(), cost.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("filled".to_string(), filled.clone());
m.insert("remaining".to_string(), Value::Null);
m.insert("status".to_string(), status.clone());
m.insert("fee".to_string(), fee.clone());
m.insert("trades".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), reduceOnly.clone());
m
}), &[market.clone()]);
Value::Null
}
/*
* @method
* @name blofin#createOrder
* @description create a trade order
* @see https://blofin.com/docs#place-order
* @see https://blofin.com/docs#place-tpsl-order
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit' or 'post_only' or 'ioc' or 'fok'
* @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 {string} [params.triggerPrice] the trigger price for a trigger order
* @param {bool} [params.reduceOnly] a mark to reduce the position size for margin, swap and future orders
* @param {bool} [params.postOnly] true to place a post only order
* @param {string} [params.marginMode] 'cross' or 'isolated', default is 'cross'
* @param {float} [params.stopLossPrice] stop loss trigger price (will use privatePostTradeOrderTpsl)
* @param {float} [params.takeProfitPrice] take profit trigger price (will use privatePostTradeOrderTpsl)
* @param {string} [params.positionSide] *stopLossPrice/takeProfitPrice orders only* 'long' or 'short' or 'net' default is 'net'
* @param {boolean} [params.hedged] if true, the positionSide will be set to long/short instead of net, default is false
* @param {string} [params.clientOrderId] a unique id for the order
* @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {float} [params.takeProfit.price] take profit order price (if not provided the order will be a market order)
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {float} [params.stopLoss.price] stop loss order price (if not provided the order will be a market order)
* @param {float} [params.tpsl] whether to force to send the order to the combined TPSL oco order endpoint
* @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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut isStopLossPriceDefined: bool = !is_equal(&self.safe_string_k(params.clone(), "stopLossPrice", &[]), &Value::Null);
let mut isTakeProfitPriceDefined: bool = !is_equal(&self.safe_string_k(params.clone(), "takeProfitPrice", &[]), &Value::Null);
let mut isTriggerOrder: bool = !is_equal(&self.safe_string_k(params.clone(), "triggerPrice", &[]), &Value::Null);
let mut isTpslEndpoint: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("createOrder".to_string()), Value::Str("tpsl".to_string()), &[Value::Bool(false)]); isTpslEndpoint = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut isCombinedSlTp: bool = is_true(&(is_true(&isStopLossPriceDefined) && is_true(&isTakeProfitPriceDefined))) || is_true(&isTpslEndpoint);
let mut isSlOrTp: bool = is_true(&isStopLossPriceDefined) || is_true(&isTakeProfitPriceDefined);
let mut response: Value = Value::Null;
let mut reduceOnly: Value = self.safe_bool_k(params.clone(), "reduceOnly", &[]);
if !is_equal(&reduceOnly, &Value::Null) {
add_element_to_object(&mut params, &Value::Str("reduceOnly".to_string()), ternary(is_true(&reduceOnly), Value::Str("true".to_string()), Value::Str("false".to_string())));
}
if is_true(&isCombinedSlTp) {
let mut tpslRequest: Value = self.create_tpsl_order_request(symbol.clone(), type_var.clone(), side.clone(), &[amount.clone(), price.clone(), params.clone()]);
response = self.private_post_trade_order_tpsl(&[tpslRequest.clone()]).await;
} else if is_true(&isTriggerOrder) || is_true(&isSlOrTp) {
let mut triggerRequest: Value = self.create_order_request(symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]);
response = self.private_post_trade_order_algo(&[triggerRequest.clone()]).await;
} else {
let mut request: Value = self.create_order_request(symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]);
response = self.private_post_trade_order(&[request.clone()]).await;
}
if is_true(&isCombinedSlTp) || is_true(&isSlOrTp) || is_true(&isTriggerOrder) {
let mut dataDict: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_order(dataDict.clone(), &[market.clone()]);
}
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
let mut order: Value = self.parse_order(first.clone(), &[market.clone()]);
add_element_to_object(&mut order, &Value::Str("type".to_string()), type_var.clone());
add_element_to_object(&mut order, &Value::Str("side".to_string()), side.clone());
return order;
Value::Null
}
pub fn create_tpsl_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut market: Value = self.market(symbol.clone());
let mut hedged: Value = self.safe_bool_k(params.clone(), "hedged", &[Value::Bool(false)]);
let mut positionSide: Value = Value::Str("net".to_string());
if is_equal(&hedged, &Value::Bool(true)) {
positionSide = ternary(is_true(&(is_equal(&side, &Value::Str("buy".to_string())))), Value::Str("short".to_string()), Value::Str("long".to_string()));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("side".to_string(), side.clone());
m.insert("positionSide".to_string(), positionSide.clone());
m.insert("brokerId".to_string(), self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("ec6dd3a7dd982d0b".to_string())]));
m.insert("reduceOnly".to_string(), self.safe_bool_k(params.clone(), "reduceOnly", &[Value::Bool(true)]));
m
});
if !is_equal(&amount, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("size".to_string()), self.amount_to_precision(symbol.clone(), amount.clone()));
}
let mut marginMode: Value = self.safe_string_k(params.clone(), "marginMode", &[Value::Str("cross".to_string())]); // cross or isolated
if !is_equal(&marginMode, &Value::Str("cross".to_string())) && !is_equal(&marginMode, &Value::Str("isolated".to_string())) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" createTpslOrder() requires a marginMode parameter that must be either cross or isolated".to_string()))));
}
let mut stopLossPrice: Value = self.safe_string_k(params.clone(), "stopLossPrice", &[]);
let mut takeProfitPrice: Value = self.safe_string_k(params.clone(), "takeProfitPrice", &[]);
if !is_equal(&stopLossPrice, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("slTriggerPrice".to_string()), self.price_to_precision(symbol.clone(), stopLossPrice.clone()));
if is_equal(&type_var, &Value::Str("market".to_string())) {
add_element_to_object(&mut request, &Value::Str("slOrderPrice".to_string()), Value::Str("-1".to_string()));
} else {
let mut slLimitPrice: Value = self.safe_string_k(params.clone(), "stopLossLimitPrice", &[]);
if is_equal(&slLimitPrice, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createTpslOrder() requires a \"stopLossLimitPrice\" parameter (instead of \"price\" argument) for stop loss orders when the order type is not market".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("slOrderPrice".to_string()), self.price_to_precision(symbol.clone(), slLimitPrice.clone()));
params = self.omit(params.clone(), Value::Str("stopLossLimitPrice".to_string()), &[]);
}
}
if !is_equal(&takeProfitPrice, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("tpTriggerPrice".to_string()), self.price_to_precision(symbol.clone(), takeProfitPrice.clone()));
if is_equal(&type_var, &Value::Str("market".to_string())) {
add_element_to_object(&mut request, &Value::Str("tpOrderPrice".to_string()), Value::Str("-1".to_string()));
} else {
let mut tpLimitPrice: Value = self.safe_string_k(params.clone(), "takeProfitLimitPrice", &[]);
if is_equal(&tpLimitPrice, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" createTpslOrder() requires a \"takeProfitLimitPrice\" parameter (instead of \"price\" argument) for take profit orders when the order type is not market".to_string()))));
}
add_element_to_object(&mut request, &Value::Str("tpOrderPrice".to_string()), self.price_to_precision(symbol.clone(), tpLimitPrice.clone()));
params = self.omit(params.clone(), Value::Str("takeProfitLimitPrice".to_string()), &[]);
}
}
add_element_to_object(&mut request, &Value::Str("marginMode".to_string()), marginMode.clone());
params = self.omit(params.clone(), Value::List(vec![Value::Str("stopLossPrice".to_string()), Value::Str("takeProfitPrice".to_string()), Value::Str("reduceOnly".to_string()), Value::Str("hedged".to_string())]), &[]);
return self.extend(request.clone(), &[params.clone()]);
Value::Null
}
/*
* @method
* @name blofin#cancelOrder
* @description cancels an open order
* @see https://blofin.com/docs#cancel-order
* @see https://blofin.com/docs#cancel-tpsl-order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.trigger] True if cancelling a trigger/conditional
* @param {boolean} [params.tpsl] True if cancelling a tpsl order
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelOrder() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let mut isTrigger: Value = self.safe_bool_k(params.clone(), "trigger", &[Value::Bool(false)]);
let mut isTpsl: Value = self.safe_bool2(params.clone(), Value::Str("tpsl".to_string()), Value::Str("TPSL".to_string()), &[Value::Bool(false)]);
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[]);
if !is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("clientOrderId".to_string()), clientOrderId.clone());
} else {
if is_true(&(!is_equal(&isTrigger, &Value::Bool(true)))) && is_true(&(!is_equal(&isTpsl, &Value::Bool(true)))) {
add_element_to_object(&mut request, &Value::Str("orderId".to_string()), to_string_val(&id));
} else if is_equal(&isTpsl, &Value::Bool(true)) {
add_element_to_object(&mut request, &Value::Str("tpslId".to_string()), to_string_val(&id));
} else if is_equal(&isTrigger, &Value::Bool(true)) {
add_element_to_object(&mut request, &Value::Str("algoId".to_string()), to_string_val(&id));
}
}
let mut query: Value = self.omit(params.clone(), Value::List(vec![Value::Str("orderId".to_string()), Value::Str("clientOrderId".to_string()), Value::Str("stop".to_string()), Value::Str("trigger".to_string()), Value::Str("tpsl".to_string())]), &[]);
if is_equal(&isTpsl, &Value::Bool(true)) {
let mut tpslResponse: Value = self.cancel_orders(Value::List(vec![id.clone()]), &[symbol.clone(), params.clone()]).await;
let mut first: Value = self.safe_dict(tpslResponse.clone(), Value::Int(0), &[]);
return first;
} else if is_equal(&isTrigger, &Value::Bool(true)) {
let __ws_arg_9 = self.extend(request.clone(), &[query.clone()]);
let mut triggerResponse: Value = self.private_post_trade_cancel_algo(&[__ws_arg_9]).await;
let mut triggerData: Value = self.safe_dict_k(triggerResponse.clone(), "data", &[]);
return self.parse_order(triggerData.clone(), &[market.clone()]);
}
let __ws_arg_10 = self.extend(request.clone(), &[query.clone()]);
let mut response: Value = self.private_post_trade_cancel_order(&[__ws_arg_10]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut order: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
return self.parse_order(order.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name blofin#createOrders
* @description create a list of trade orders
* @see https://blofin.com/docs#place-multiple-orders
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut ordersRequests: Value = Value::List(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_442: bool = true;
while { if !__for_first_442 { i = add(&i, &Value::Int(1)); } __for_first_442 = false; is_less_than(&i, &get_array_length(&orders)) } {
let mut rawOrder: Value = get_value(&orders, &i);
let mut rawOrder: Value = get_value(&orders, &i);
let mut marketId: Value = self.safe_string_k(rawOrder.clone(), "symbol", &[]);
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.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut extendedParams: Value = self.extend(orderParams.clone(), &[params.clone()]); // the request does not accept extra params since it's a list, so we're extending each order with the common params
let mut orderRequest: Value = self.create_order_request(marketId.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), extendedParams.clone()]);
append_to_array(&mut ordersRequests, orderRequest.clone());
}
}
let mut response: Value = self.private_post_trade_batch_orders(&[ordersRequests.clone()]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_orders(data.clone(), &[]);
Value::Null
}
/*
* @method
* @name blofin#fetchOpenOrders
* @description Fetch orders that are still open
* @see https://blofin.com/docs#get-active-orders
* @see https://blofin.com/docs#get-active-tpsl-orders
* @see https://docs.blofin.com/index.html#get-active-algo-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 {bool} [params.trigger] True if fetching trigger or conditional orders
* @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 {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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOpenOrders".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchOpenOrders".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
add_element_to_object(&mut request, &Value::Str("instId".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone()); // default 100, max 100
}
let mut isTrigger: Value = self.safe_bool_n(params.clone(), Value::List(vec![Value::Str("stop".to_string()), Value::Str("trigger".to_string())]), &[Value::Bool(false)]);
let mut isTpSl: Value = self.safe_bool2(params.clone(), Value::Str("tpsl".to_string()), Value::Str("TPSL".to_string()), &[Value::Bool(false)]);
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOpenOrders".to_string()), Value::Str("method".to_string()), &[Value::Str("privateGetTradeOrdersPending".to_string())]); method = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut query: Value = self.omit(params.clone(), Value::List(vec![Value::Str("method".to_string()), Value::Str("stop".to_string()), Value::Str("trigger".to_string()), Value::Str("tpsl".to_string()), Value::Str("TPSL".to_string())]), &[]);
let mut response: Value = Value::Null;
if is_true(&(is_equal(&isTpSl, &Value::Bool(true)))) || is_true(&(is_equal(&method, &Value::Str("privateGetTradeOrdersTpslPending".to_string())))) {
let __ws_arg_11 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_trade_orders_tpsl_pending(&[__ws_arg_11]).await;
} else if is_true(&(is_equal(&isTrigger, &Value::Bool(true)))) || is_true(&(is_equal(&method, &Value::Str("privateGetTradeOrdersAlgoPending".to_string())))) {
add_element_to_object(&mut request, &Value::Str("orderType".to_string()), Value::Str("trigger".to_string()));
let __ws_arg_12 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_trade_orders_algo_pending(&[__ws_arg_12]).await;
} else {
let __ws_arg_13 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_trade_orders_pending(&[__ws_arg_13]).await;
}
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_orders(data.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchMyTrades
* @description fetch all trades made by the user
* @see https://blofin.com/docs#get-trade-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 time to retrieve trades for
* @param {string} [params.type] 'swap' or 'spot' (defaults to 'swap'), required to fetch spot trade history
* @param {string} [params.instId] *spot markets only* the market id of the spot market to fetch the trade history for (e.g. 'BTC-USDT')
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchMyTrades".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchMyTrades".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
add_element_to_object(&mut request, &Value::Str("instId".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
{ let __destr_tmp = self.handle_until_option(Value::Str("end".to_string()), request.clone(), params.clone(), &[]); request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone()); // default 100, max 100
}
let mut type_var: Value = Value::Str("swap".to_string());
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchMyTrades".to_string()), &[market.clone(), params.clone(), type_var.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut response: Value = Value::Null;
if is_equal(&type_var, &Value::Str("spot".to_string())) {
add_element_to_object(&mut request, &Value::Str("instType".to_string()), Value::Str("SPOT".to_string()));
//
// {
// "code": "0",
// "msg": "success",
// "data": [
// {
// "instId": "DOGE-USDT",
// "tradeId": "6000001623870",
// "orderId": "6000011777113",
// "fillPrice": "0.091480000000000000",
// "fillSize": "30.000000000000000000",
// "fillPnl": null,
// "side": "buy",
// "fee": "0.030000000000000000",
// "ts": "1775213753407",
// "brokerId": null,
// "feeCurrency": "base_currency"
// }
// ]
// }
//
let __ws_arg_14 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_spot_trade_fills_history(&[__ws_arg_14]).await;
} else {
let __ws_arg_15 = self.extend(request.clone(), &[params.clone()]);
response = self.private_get_trade_fills_history(&[__ws_arg_15]).await;
}
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_trades(data.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchDeposits
* @description fetch all deposits made to an account
* @see https://blofin.com/docs#get-deposite-history
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch entries for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchDeposits".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchDeposits".to_string()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if !is_equal(&code, &Value::Null) {
currency = self.currency(code.clone());
add_element_to_object(&mut request, &Value::Str("currency".to_string()), get_value(¤cy, &Value::Str("id".to_string())));
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("before".to_string()), crate::runtime::Math::max(&subtract(&since, &Value::Int(1)), &Value::Int(0)));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone()); // default 100, max 100
}
{ let __destr_tmp = self.handle_until_option(Value::Str("after".to_string()), request.clone(), params.clone(), &[]); request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let __ws_arg_16 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_asset_deposit_history(&[__ws_arg_16]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_transactions(data.clone(), &[currency.clone(), since.clone(), limit.clone(), params.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://blofin.com/docs#get-withdraw-history
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch entries for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchWithdrawals".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchWithdrawals".to_string()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if !is_equal(&code, &Value::Null) {
currency = self.currency(code.clone());
add_element_to_object(&mut request, &Value::Str("currency".to_string()), get_value(¤cy, &Value::Str("id".to_string())));
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("before".to_string()), crate::runtime::Math::max(&subtract(&since, &Value::Int(1)), &Value::Int(0)));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone()); // default 100, max 100
}
{ let __destr_tmp = self.handle_until_option(Value::Str("after".to_string()), request.clone(), params.clone(), &[]); request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let __ws_arg_17 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_asset_withdrawal_history(&[__ws_arg_17]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_transactions(data.clone(), &[currency.clone(), since.clone(), limit.clone(), params.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
* @see https://blofin.com/docs#get-funds-transfer-history
* @param {string} [code] unified currency code, default is undefined
* @param {int} [since] timestamp in ms of the earliest ledger entry, default is undefined
* @param {int} [limit] max number of ledger entries to return, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @param {int} [params.until] the latest time in ms to fetch entries for
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object} a [ledger structure]{@link https://docs.ccxt.com/?id=ledger-entry-structure}
*/
pub async fn fetch_ledger(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchLedger".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchLedger".to_string()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone());
}
let mut currency: Value = Value::Null;
if !is_equal(&code, &Value::Null) {
currency = self.currency(code.clone());
add_element_to_object(&mut request, &Value::Str("currency".to_string()), get_value(¤cy, &Value::Str("id".to_string())));
}
{ let __destr_tmp = self.handle_until_option(Value::Str("end".to_string()), request.clone(), params.clone(), &[]); request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let __ws_arg_18 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_asset_bills(&[__ws_arg_18]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_ledger(data.clone(), &[currency.clone(), since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
//
//
// fetchDeposits
//
// {
// "currency": "USDT",
// "chain": "TRC20",
// "address": "TGfJLtnsh3B9EqekFEBZ1nR14QanBUf5Be",
// "txId": "892f4e0c32268b29b2e541ef30d32a30bbf10f902adcc4b1428319ed7c3758fd",
// "type": "0",
// "amount": "86.975843",
// "state": "1",
// "ts": "1703163304153",
// "tag": null,
// "confirm": "16",
// "depositId": "36c8e2a7ea184a219de72215a696acaf"
// }
// fetchWithdrawals
// {
// "currency": "USDT",
// "chain": "TRC20",
// "address": "TYgB3sVXHPEDQUu288EG1uMFh9Pk2swLgW",
// "txId": "1fd5ac52df414d7ea66194cadd9a5b4d2422c2b9720037f66d98207f9858fd96",
// "type": "0",
// "amount": "9",
// "fee": "1",
// "feeCurrency": "USDT",
// "state": "3",
// "clientId": null,
// "ts": "1707217439351",
// "tag": null,
// "memo": null,
// "withdrawId": "e0768698cfdf4aee8e54654c3775914b"
// }
//
let mut type_var: Value = Value::Null;
let mut id: Value = Value::Null;
let mut status: Value = Value::Null;
let mut withdrawalId: Value = self.safe_string_k(transaction.clone(), "withdrawId", &[]);
let mut depositId: Value = self.safe_string_k(transaction.clone(), "depositId", &[]);
let mut addressTo: Value = self.safe_string_k(transaction.clone(), "address", &[]);
let mut address: Value = addressTo.clone();
let mut tagTo: Value = self.safe_string_k(transaction.clone(), "tag", &[]);
if !is_equal(&withdrawalId, &Value::Null) {
type_var = Value::Str("withdrawal".to_string());
id = withdrawalId.clone();
status = self.parse_transaction_withdrawal_status(self.safe_string_k(transaction.clone(), "state", &[]));
} else {
id = depositId.clone();
type_var = Value::Str("deposit".to_string());
status = self.parse_transaction_deposit_status(self.safe_string_k(transaction.clone(), "state", &[]));
}
let mut currencyId: Value = self.safe_string_k(transaction.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
let mut amount: Value = self.safe_number_k(transaction.clone(), "amount", &[]);
let mut txid: Value = self.safe_string_k(transaction.clone(), "txId", &[]);
let mut timestamp: Value = self.safe_integer_k(transaction.clone(), "ts", &[]);
let mut feeCurrencyId: Value = self.safe_string_k(transaction.clone(), "feeCurrency", &[]);
let mut feeCode: Value = self.safe_currency_code(feeCurrencyId.clone(), &[]);
let mut feeCost: Value = self.safe_number_k(transaction.clone(), "fee", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), id.clone());
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), amount.clone());
m.insert("network".to_string(), Value::Null);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("addressTo".to_string(), addressTo.clone());
m.insert("address".to_string(), address.clone());
m.insert("tagFrom".to_string(), Value::Null);
m.insert("tagTo".to_string(), tagTo.clone());
m.insert("tag".to_string(), tagTo.clone());
m.insert("status".to_string(), status.clone());
m.insert("type".to_string(), type_var.clone());
m.insert("updated".to_string(), Value::Null);
m.insert("txid".to_string(), txid.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("internal".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), feeCode.clone());
m.insert("cost".to_string(), feeCost.clone());
m
}));
m
});
Value::Null
}
pub fn parse_transaction_withdrawal_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("pending".to_string()));
m.insert("2".to_string(), Value::Str("failed".to_string()));
m.insert("3".to_string(), Value::Str("ok".to_string()));
m.insert("4".to_string(), Value::Str("failed".to_string()));
m.insert("6".to_string(), Value::Str("pending".to_string()));
m.insert("7".to_string(), Value::Str("pending".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_transaction_deposit_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("pending".to_string()));
m.insert("1".to_string(), Value::Str("ok".to_string()));
m.insert("2".to_string(), Value::Str("failed".to_string()));
m.insert("3".to_string(), Value::Str("pending".to_string()));
m
});
return self.safe_string(statuses.clone(), status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Value {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1".to_string(), Value::Str("transfer".to_string()));
m.insert("2".to_string(), Value::Str("trade".to_string()));
m.insert("3".to_string(), Value::Str("trade".to_string()));
m.insert("4".to_string(), Value::Str("rebate".to_string()));
m.insert("5".to_string(), Value::Str("trade".to_string()));
m.insert("6".to_string(), Value::Str("transfer".to_string()));
m.insert("7".to_string(), Value::Str("trade".to_string()));
m.insert("8".to_string(), Value::Str("fee".to_string()));
m.insert("9".to_string(), Value::Str("trade".to_string()));
m.insert("10".to_string(), Value::Str("trade".to_string()));
m.insert("11".to_string(), Value::Str("trade".to_string()));
m
});
return self.safe_string(types.clone(), type_var.clone(), &[type_var.clone()]);
Value::Null
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let mut currencyId: Value = self.safe_string_k(item.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId.clone(), &[currency.clone()]);
currency = self.safe_currency(currencyId.clone(), &[currency.clone()]);
let mut timestamp: Value = self.safe_integer_k(item.clone(), "ts", &[]);
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item.clone());
m.insert("id".to_string(), self.safe_string_k(item.clone(), "transferId", &[]));
m.insert("direction".to_string(), Value::Null);
m.insert("account".to_string(), Value::Null);
m.insert("referenceId".to_string(), self.safe_string_k(item.clone(), "clientId", &[]));
m.insert("referenceAccount".to_string(), Value::Null);
m.insert("type".to_string(), self.parse_ledger_entry_type(self.safe_string_k(item.clone(), "type", &[])));
m.insert("currency".to_string(), code.clone());
m.insert("amount".to_string(), self.safe_number_k(item.clone(), "amount", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), Value::Null);
m.insert("status".to_string(), Value::Str("ok".to_string()));
m.insert("fee".to_string(), Value::Null);
m
}), &[currency.clone()]);
Value::Null
}
pub fn parse_ids(&self, mut ids: Value) -> Value {
/*
* @ignore
* @method
* @name blofin#parseIds
* @param {string[]|string} ids order ids
* @returns {string[]} list of order ids
*/
if is_string(&ids) {
return split(&ids, &Value::Str(",".to_string()));
} else {
return ids;
}
Value::Null
}
/*
* @method
* @name blofin#cancelOrders
* @description cancel multiple orders
* @see https://blofin.com/docs#cancel-multiple-orders
* @param {string[]} ids order ids
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.trigger] whether the order is a stop/trigger order
* @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
}));
// TODO : the original endpoint signature differs, according to that you can skip individual symbol and assign ids in batch. At this moment, `params` is not being used too.
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelOrders() requires a symbol argument".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::List(vec![]);
let mut method: Value = self.handle_option(Value::Str("cancelOrders".to_string()), Value::Str("method".to_string()), &[Value::Str("privatePostTradeCancelBatchOrders".to_string())]);
let mut clientOrderIds: Value = self.parse_ids(self.safe_value_k(params.clone(), "clientOrderId", &[]));
let mut tpslIds: Value = self.parse_ids(self.safe_value_k(params.clone(), "tpslId", &[]));
let mut trigger: Value = self.safe_bool_n(params.clone(), Value::List(vec![Value::Str("stop".to_string()), Value::Str("trigger".to_string()), Value::Str("tpsl".to_string())]), &[]);
if is_equal(&trigger, &Value::Bool(true)) {
method = Value::Str("privatePostTradeCancelTpsl".to_string());
}
if is_equal(&clientOrderIds, &Value::Null) {
ids = self.parse_ids(ids.clone());
if !is_equal(&tpslIds, &Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_443: bool = true;
while { if !__for_first_443 { i = add(&i, &Value::Int(1)); } __for_first_443 = false; is_less_than(&i, &get_array_length(&tpslIds)) } {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tpslId".to_string(), get_value(&tpslIds, &i));
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
}));
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_444: bool = true;
while { if !__for_first_444 { i = add(&i, &Value::Int(1)); } __for_first_444 = false; is_less_than(&i, &get_array_length(&ids)) } {
if is_equal(&trigger, &Value::Bool(true)) {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tpslId".to_string(), get_value(&ids, &i));
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
}));
} else {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), get_value(&ids, &i));
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
}));
}
}
}
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_445: bool = true;
while { if !__for_first_445 { i = add(&i, &Value::Int(1)); } __for_first_445 = false; is_less_than(&i, &get_array_length(&clientOrderIds)) } {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("clientOrderId".to_string(), get_value(&clientOrderIds, &i));
m
}));
}
}
}
let mut response: Value = Value::Null;
if is_equal(&method, &Value::Str("privatePostTradeCancelTpsl".to_string())) {
response = self.private_post_trade_cancel_tpsl(&[request.clone()]).await; // * dont extend with params, otherwise ARRAY will be turned into OBJECT
} else {
response = self.private_post_trade_cancel_batch_orders(&[request.clone()]).await; // * dont extend with params, otherwise ARRAY will be turned into OBJECT
}
let mut ordersData: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_orders(ordersData.clone(), &[market.clone(), Value::Null, Value::Null, params.clone()]);
Value::Null
}
/*
* @method
* @name blofin#transfer
* @description transfer currency internally between wallets on the same account
* @see https://blofin.com/docs#funds-transfer
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount account to transfer from (funding, swap, copy_trading, earn)
* @param {string} toAccount account to transfer to (funding, swap, copy_trading, earn)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/?id=transfer-structure}
*/
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut accountsByType: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromId: Value = self.safe_string(accountsByType.clone(), fromAccount.clone(), &[fromAccount.clone()]);
let mut toId: Value = self.safe_string(accountsByType.clone(), toAccount.clone(), &[toAccount.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), get_value(¤cy, &Value::Str("id".to_string())));
m.insert("amount".to_string(), self.currency_to_precision(code.clone(), amount.clone(), &[]));
m.insert("fromAccount".to_string(), fromId.clone());
m.insert("toAccount".to_string(), toId.clone());
m
});
let __ws_arg_19 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_asset_transfer(&[__ws_arg_19]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transfer(data.clone(), &[currency.clone()]);
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 mut id: Value = self.safe_string_k(transfer.clone(), "transferId", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), id.clone());
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("currency".to_string(), 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::Null);
m
});
Value::Null
}
/*
* @method
* @name blofin#fetchPosition
* @description fetch data on a single open contract trade position
* @see https://blofin.com/docs#get-positions
* @param {string} symbol unified market symbol of the market the position is held in, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.instType] MARGIN, SWAP, FUTURES, OPTION
* @returns {object} a [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let __ws_arg_20 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_account_positions(&[__ws_arg_20]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut position: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
if is_equal(&position, &Value::Null) {
panic!("{}", crate::exchange_errors::null_response(add(&self.id, &Value::Str(" fetchPosition() returned empty position".to_string()))));
}
return self.parse_position(position.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchPositions
* @description fetch data on a single open contract trade position
* @see https://blofin.com/docs#get-positions
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.instType] MARGIN, SWAP, FUTURES, OPTION
* @returns {object} a [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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut response: Value = self.private_get_account_positions(&[params.clone()]).await;
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut result: Value = self.parse_positions(data.clone(), &[]);
return self.filter_by_array_positions(result.clone(), Value::Str("symbol".to_string()), &[symbols.clone(), Value::Bool(false)]);
Value::Null
}
/*
* @method
* @name blofin#fetchPositionsHistory
* @description fetches historical positions
* @see https://docs.blofin.com/index.html#get-positions-history
* @param {string[]} [symbols] unified contract symbols
* @param {int} [since] timestamp in ms of the earliest position to fetch, default=3 months ago, max range for params["until"] - since is 3 months
* @param {int} [limit] the maximum amount of records to fetch, default=20, max=100
* @param {object} params extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest position to fetch, max range for params["until"] - since is 3 months
* @param {string} [params.productType] USDT-FUTURES (default), COIN-FUTURES, USDC-FUTURES, SUSDT-FUTURES, SCOIN-FUTURES, or SUSDC-FUTURES
* @param {boolean} [params.uta] set to true for the unified trading account (uta), defaults to false
* @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if !is_equal(&symbols, &Value::Null) {
let mut symbolsLength: Value = get_array_length(&symbols);
if is_equal(&symbolsLength, &Value::Int(0)) {
market = self.market(get_value(&symbols, &Value::Int(0)));
add_element_to_object(&mut request, &Value::Str("instId".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), crate::runtime::Math::min(&limit, &Value::Int(100)));
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("begin".to_string()), since.clone());
}
{ let __destr_tmp = self.handle_until_option(Value::Str("end".to_string()), request.clone(), params.clone(), &[]); request = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let __ws_arg_21 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_account_positions_history(&[__ws_arg_21]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": [
// {
// "historyId": "110307402",
// "positionId": "1000000722711",
// "instId": "BTC-USDT",
// "instType": "SWAP",
// "marginMode": "cross",
// "positionSide": "net",
// "closePositions": "0.0006",
// "maxPositions": "0.0006",
// "liquidationPositions": "0",
// "openAveragePrice": "81550.1",
// "closeAveragePrice": "81550",
// "createTime": "1777995583329",
// "updateTime": "1777995588333",
// "leverage": "50",
// "realizedPnl": "-0.058776036",
// "realizedPnlRatio": "-0.060061275216094155",
// "fee": "-0.058716036"
// },
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
let mut positions: Value = self.parse_positions(data.clone(), &[symbols.clone(), params.clone()]);
return self.filter_by_since_limit(positions.clone(), &[since.clone(), limit.clone()]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// response similar for REST & WS
//
// {
// instType: 'SWAP',
// instId: 'LTC-USDT',
// marginMode: 'cross',
// positionId: '644159',
// positionSide: 'net',
// positions: '1',
// availablePositions: '1',
// averagePrice: '68.16',
// unrealizedPnl: '0.80631223',
// unrealizedPnlRatio: '0.03548909463028169',
// leverage: '3',
// liquidationPrice: '10.116655172370356435',
// markPrice: '68.96',
// initialMargin: '22.988770743333333333',
// margin: '', // this field might not exist in rest response
// marginRatio: '152.523509620342499273',
// maintenanceMargin: '0.34483156115',
// adl: '4',
// createTime: '1707235776528',
// updateTime: '1707235776528'
// }
//
//
// positions-history
//
// {
// "positionId": "1000000722711",
// "instId": "BTC-USDT",
// "instType": "SWAP",
// "marginMode": "cross",
// "positionSide": "net",
// "createTime": "1777995583329",
// "updateTime": "1777995588333",
// "leverage": "50",
// "realizedPnl": "-0.058776036",
// "realizedPnlRatio": "-0.060061275216094155",
// "fee": "-0.058716036"
// "historyId": "110307402",
// "closePositions": "0.0006",
// "maxPositions": "0.0006",
// "liquidationPositions": "0",
// "openAveragePrice": "81550.1",
// "closeAveragePrice": "81550",
// },
//
let mut marketId: Value = self.safe_string_k(position.clone(), "instId", &[]);
market = self.safe_market(&[marketId.clone(), market.clone()]);
let mut symbol: Value = get_value(&market, &Value::Str("symbol".to_string()));
let mut pos: Value = self.safe_string_k(position.clone(), "positions", &[]);
let mut contractsAbs: Value = crate::precise::Precise::stringAbs(&pos);
let mut side: Value = self.safe_string_k(position.clone(), "positionSide", &[]);
let mut hedged: Value = Value::Bool(!is_equal(&side, &Value::Str("net".to_string())));
let mut contracts: Value = self.parse_number(contractsAbs.clone(), &[]);
if !is_equal(&pos, &Value::Null) {
if is_equal(&side, &Value::Str("net".to_string())) {
if is_true(&crate::precise::Precise::stringGt(&pos, &Value::Str("0".to_string()))) {
side = Value::Str("long".to_string());
} else if is_true(&crate::precise::Precise::stringLt(&pos, &Value::Str("0".to_string()))) {
side = Value::Str("short".to_string());
} else {
side = Value::Null;
}
}
}
let mut contractSize: Value = self.safe_number_k(market.clone(), "contractSize", &[]);
let mut contractSizeString: Value = self.number_to_string(contractSize.clone());
let mut markPriceString: Value = self.safe_string_k(position.clone(), "markPrice", &[]);
let mut notionalString: Value = self.safe_string_k(position.clone(), "notionalUsd", &[]);
if is_equal(&get_value(&market, &Value::Str("inverse".to_string())), &Value::Bool(true)) {
notionalString = crate::precise::Precise::stringDiv(&crate::precise::Precise::stringMul(&contractsAbs, &contractSizeString), &markPriceString);
}
let mut notional: Value = self.parse_number(notionalString.clone(), &[]);
let mut marginMode: Value = self.safe_string_k(position.clone(), "marginMode", &[]);
let mut initialMarginString: Value = Value::Null;
let mut entryPriceString: Value = self.safe_string2(position.clone(), Value::Str("averagePrice".to_string()), Value::Str("openAveragePrice".to_string()), &[]);
let mut unrealizedPnlString: Value = self.safe_string_k(position.clone(), "unrealizedPnl", &[]);
let mut leverageString: Value = self.safe_string_k(position.clone(), "leverage", &[]);
let mut initialMarginPercentage: Value = Value::Null;
let mut collateralString: Value = Value::Null;
if is_equal(&marginMode, &Value::Str("cross".to_string())) {
initialMarginString = self.safe_string_k(position.clone(), "initialMargin", &[]);
collateralString = crate::precise::Precise::stringAdd(&initialMarginString, &unrealizedPnlString);
} else if is_equal(&marginMode, &Value::Str("isolated".to_string())) {
initialMarginPercentage = crate::precise::Precise::stringDiv(&Value::Str("1".to_string()), &leverageString);
collateralString = self.safe_string_k(position.clone(), "margin", &[]);
}
let mut maintenanceMarginString: Value = self.safe_string_k(position.clone(), "maintenanceMargin", &[]);
let mut maintenanceMargin: Value = self.parse_number(maintenanceMarginString.clone(), &[]);
let mut maintenanceMarginPercentageString: Value = crate::precise::Precise::stringDiv(&maintenanceMarginString, ¬ionalString);
if is_equal(&initialMarginPercentage, &Value::Null) {
initialMarginPercentage = self.parse_number(crate::precise::Precise::stringDivPrec(&initialMarginString, ¬ionalString, &Value::Int(4)), &[]);
} else if is_equal(&initialMarginString, &Value::Null) {
let mut initialMarginPercentageString: Value = self.number_to_string(initialMarginPercentage.clone());
initialMarginString = crate::precise::Precise::stringMul(&initialMarginPercentageString, ¬ionalString);
}
let mut rounder: Value = Value::Str("0.00005".to_string()); // round to closest 0.01%
let mut maintenanceMarginPercentage: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&crate::precise::Precise::stringAdd(&maintenanceMarginPercentageString, &rounder), &Value::Str("1".to_string()), &Value::Int(4)), &[]);
let mut liquidationPrice: Value = self.safe_number_k(position.clone(), "liquidationPrice", &[]);
let mut percentageString: Value = self.safe_string_k(position.clone(), "unrealizedPnlRatio", &[]);
let mut percentage: Value = self.parse_number(crate::precise::Precise::stringMul(&percentageString, &Value::Str("100".to_string())), &[]);
let mut timestamp: Value = self.safe_integer_k(position.clone(), "updateTime", &[]);
let mut marginRatio: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&maintenanceMarginString, &collateralString, &Value::Int(4)), &[]);
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol.clone());
m.insert("notional".to_string(), notional.clone());
m.insert("marginMode".to_string(), marginMode.clone());
m.insert("liquidationPrice".to_string(), liquidationPrice.clone());
m.insert("entryPrice".to_string(), self.parse_number(entryPriceString.clone(), &[]));
m.insert("exitPrice".to_string(), self.safe_number_k(position.clone(), "closeAveragePrice", &[]));
m.insert("unrealizedPnl".to_string(), self.parse_number(unrealizedPnlString.clone(), &[]));
m.insert("realizedPnl".to_string(), self.safe_number_k(position.clone(), "realizedPnl", &[]));
m.insert("percentage".to_string(), percentage.clone());
m.insert("contracts".to_string(), contracts.clone());
m.insert("contractSize".to_string(), contractSize.clone());
m.insert("markPrice".to_string(), self.parse_number(markPriceString.clone(), &[]));
m.insert("lastPrice".to_string(), Value::Null);
m.insert("side".to_string(), side.clone());
m.insert("hedged".to_string(), hedged.clone());
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("lastUpdateTimestamp".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), maintenanceMargin.clone());
m.insert("maintenanceMarginPercentage".to_string(), maintenanceMarginPercentage.clone());
m.insert("collateral".to_string(), self.parse_number(collateralString.clone(), &[]));
m.insert("initialMargin".to_string(), self.parse_number(initialMarginString.clone(), &[]));
m.insert("initialMarginPercentage".to_string(), self.parse_number(initialMarginPercentage.clone(), &[]));
m.insert("leverage".to_string(), self.parse_number(leverageString.clone(), &[]));
m.insert("marginRatio".to_string(), marginRatio.clone());
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name blofin#fetchLeverages
* @description fetch the set leverage for all contract markets
* @see https://docs.blofin.com/index.html#get-multiple-leverage
* @param {string[]} symbols a list of unified market symbols, required on blofin
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @returns {object} a list of [leverage structures]{@link https://docs.ccxt.com/?id=leverage-structure}
*/
pub async fn fetch_leverages(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
if is_equal(&symbols, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" fetchLeverages() requires a symbols argument".to_string()))));
}
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("fetchLeverages".to_string()), &[params.clone()]); marginMode = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&marginMode, &Value::Null) {
marginMode = self.safe_string_k(params.clone(), "marginMode", &[Value::Str("cross".to_string())]); // cross as default marginMode
}
if is_true(&(!is_equal(&marginMode, &Value::Str("cross".to_string())))) && is_true(&(!is_equal(&marginMode, &Value::Str("isolated".to_string())))) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchLeverages() requires a marginMode parameter that must be either cross or isolated".to_string()))));
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut symbolsList: Value = symbols.clone();
let mut instIds: Value = Value::Str("".to_string());
{
let mut i: Value = Value::Int(0);
let mut __for_first_446: bool = true;
while { if !__for_first_446 { i = add(&i, &Value::Int(1)); } __for_first_446 = false; is_less_than(&i, &get_array_length(&symbolsList)) } {
let mut entry: Value = get_value(&symbolsList, &i);
let mut entry: Value = get_value(&symbolsList, &i);
let mut entryMarket: Value = self.market(entry.clone());
if is_greater_than(&i, &Value::Int(0)) {
instIds = add(&add(&instIds, &Value::Str(",".to_string())), &get_value(&entryMarket, &Value::Str("id".to_string())));
} else {
instIds = add(&instIds, &get_value(&entryMarket, &Value::Str("id".to_string())));
}
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), instIds.clone());
m.insert("marginMode".to_string(), marginMode.clone());
m
});
let __ws_arg_22 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_account_batch_leverage_info(&[__ws_arg_22]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": [
// {
// "leverage": "3",
// "marginMode": "cross",
// "instId": "BTC-USDT"
// },
// ]
// }
//
let mut leverages: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_leverages(leverages.clone(), &[symbols.clone(), Value::Str("instId".to_string())]);
Value::Null
}
/*
* @method
* @name blofin#fetchLeverage
* @description fetch the set leverage for a market
* @see https://docs.blofin.com/index.html#get-leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @returns {object} a [leverage structure]{@link https://docs.ccxt.com/?id=leverage-structure}
*/
pub async fn fetch_leverage(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("fetchLeverage".to_string()), &[params.clone()]); marginMode = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_equal(&marginMode, &Value::Null) {
marginMode = self.safe_string_k(params.clone(), "marginMode", &[Value::Str("cross".to_string())]); // cross as default marginMode
}
if is_true(&(!is_equal(&marginMode, &Value::Str("cross".to_string())))) && is_true(&(!is_equal(&marginMode, &Value::Str("isolated".to_string())))) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" fetchLeverage() requires a marginMode parameter that must be either cross or isolated".to_string()))));
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("marginMode".to_string(), marginMode.clone());
m
});
let __ws_arg_23 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_get_account_leverage_info(&[__ws_arg_23]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": {
// "leverage": "3",
// "marginMode": "cross",
// "instId": "BTC-USDT"
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_leverage(data.clone(), &[market.clone()]);
Value::Null
}
pub fn parse_leverage(&self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = self.safe_string_k(leverage.clone(), "instId", &[]);
let mut leverageValue: Value = self.safe_integer_k(leverage.clone(), "leverage", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), leverage.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone()]));
m.insert("marginMode".to_string(), self.safe_string_lower(leverage.clone(), Value::Str("marginMode".to_string()), &[]));
m.insert("longLeverage".to_string(), leverageValue.clone());
m.insert("shortLeverage".to_string(), leverageValue.clone());
m
});
Value::Null
}
/*
* @method
* @name blofin#setLeverage
* @description set the level of leverage for a market
* @see https://blofin.com/docs#set-leverage
* @param {int} leverage the rate of leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.marginMode] 'cross' or 'isolated'
* @param {string} [params.positionSide] 'long' or 'short' - required for hedged mode in isolated margin
* @returns {object} response from the exchange
*/
pub async fn set_leverage(&mut self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&symbol, &Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" setLeverage() requires a symbol argument".to_string()))));
}
// WARNING: THIS WILL INCREASE LIQUIDATION PRICE FOR OPEN ISOLATED LONG POSITIONS
// AND DECREASE LIQUIDATION PRICE FOR OPEN ISOLATED SHORT POSITIONS
if is_true(&(is_less_than(&leverage, &Value::Int(1)))) || is_true(&(is_greater_than(&leverage, &Value::Int(125)))) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" setLeverage() leverage should be between 1 and 125".to_string()))));
}
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("setLeverage".to_string()), &[params.clone(), Value::Str("cross".to_string())]); marginMode = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&(!is_equal(&marginMode, &Value::Str("cross".to_string())))) && is_true(&(!is_equal(&marginMode, &Value::Str("isolated".to_string())))) {
panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" setLeverage() requires a marginMode parameter that must be either cross or isolated".to_string()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), leverage.clone());
m.insert("marginMode".to_string(), marginMode.clone());
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m
});
let __ws_arg_24 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_account_set_leverage(&[__ws_arg_24]).await;
return response;
Value::Null
}
/*
* @method
* @name blofin#closePosition
* @description closes open positions for a market
* @see https://blofin.com/docs#close-positions
* @param {string} symbol Unified CCXT market symbol
* @param {string} [side] 'buy' or 'sell', leave as undefined in net mode
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] a unique identifier for the order
* @param {string} [params.marginMode] 'cross' or 'isolated', default is 'cross;
* @param {string} [params.code] *required in the case of closing cross MARGIN position for Single-currency margin* margin currency
*
* EXCHANGE SPECIFIC PARAMETERS
* @param {boolean} [params.autoCxl] whether any pending orders for closing out needs to be automatically canceled when close position via a market order. false or true, the default is false
* @param {string} [params.tag] order tag a combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters
* @returns {object[]} [A list of position structures]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn close_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut side = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[]);
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("closePosition".to_string()), &[params.clone(), Value::Str("cross".to_string())]); marginMode = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), get_value(&market, &Value::Str("id".to_string())));
m.insert("marginMode".to_string(), marginMode.clone());
m
});
if !is_equal(&clientOrderId, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("clientOrderId".to_string()), clientOrderId.clone());
}
let __ws_arg_25 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_trade_close_position(&[__ws_arg_25]).await;
return self.safe_dict_k(response.clone(), "data", &[]);
Value::Null
}
/*
* @method
* @name blofin#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://blofin.com/docs#get-order-history
* @see https://blofin.com/docs#get-tpsl-order-history
* @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 orde structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {bool} [params.trigger] True if fetching trigger or conditional orders
* @param {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 {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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchClosedOrders".to_string()), Value::Str("paginate".to_string()), &[]); paginate = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchClosedOrders".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
add_element_to_object(&mut request, &Value::Str("instId".to_string()), get_value(&market, &Value::Str("id".to_string())));
}
if !is_equal(&limit, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("limit".to_string()), limit.clone()); // default 100, max 100
}
if !is_equal(&since, &Value::Null) {
add_element_to_object(&mut request, &Value::Str("begin".to_string()), since.clone());
}
let mut isTrigger: Value = self.safe_bool_n(params.clone(), Value::List(vec![Value::Str("stop".to_string()), Value::Str("trigger".to_string()), Value::Str("tpsl".to_string()), Value::Str("TPSL".to_string())]), &[Value::Bool(false)]);
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchClosedOrders".to_string()), Value::Str("method".to_string()), &[Value::Str("privateGetTradeOrdersHistory".to_string())]); method = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
let mut query: Value = self.omit(params.clone(), Value::List(vec![Value::Str("method".to_string()), Value::Str("stop".to_string()), Value::Str("trigger".to_string()), Value::Str("tpsl".to_string()), Value::Str("TPSL".to_string())]), &[]);
let mut response: Value = Value::Null;
if is_true(&(is_equal(&isTrigger, &Value::Bool(true)))) || is_true(&(is_equal(&method, &Value::Str("privateGetTradeOrdersTpslHistory".to_string())))) {
let __ws_arg_26 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_trade_orders_tpsl_history(&[__ws_arg_26]).await;
} else {
let __ws_arg_27 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_trade_orders_history(&[__ws_arg_27]).await;
}
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_orders(data.clone(), &[market.clone(), since.clone(), limit.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchMarginMode
* @description fetches the margin mode of a trading pair
* @see https://docs.blofin.com/index.html#get-margin-mode
* @param {string} symbol unified symbol of the market to fetch the margin mode for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin mode structure]{@link https://docs.ccxt.com/?id=margin-mode-structure}
*/
pub async fn fetch_margin_mode(&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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut response: Value = self.private_get_account_margin_mode(&[params.clone()]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": {
// "marginMode": "cross"
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_mode(data.clone(), &[market.clone()]);
Value::Null
}
pub fn parse_margin_mode(&self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), marginMode.clone());
m.insert("symbol".to_string(), self.safe_string_k(market.clone(), "symbol", &[]));
m.insert("marginMode".to_string(), self.safe_string_k(marginMode.clone(), "marginMode", &[]));
m
});
Value::Null
}
/*
* @method
* @name blofin#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://docs.blofin.com/index.html#set-margin-mode
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} [symbol] unified market symbol (not used in blofin setMarginMode)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_argument(Value::Str("setMarginMode".to_string()), marginMode.clone(), Value::Str("marginMode".to_string()), &[Value::List(vec![Value::Str("cross".to_string()), Value::Str("isolated".to_string())])]);
if is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if !is_equal(&symbol, &Value::Null) {
market = self.market(symbol.clone());
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), marginMode.clone());
m
});
let __ws_arg_28 = self.extend(request.clone(), &[params.clone()]);
let mut response: Value = self.private_post_account_set_margin_mode(&[__ws_arg_28]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": {
// "marginMode": "isolated"
// }
// }
//
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_mode(data.clone(), &[market.clone()]);
Value::Null
}
/*
* @method
* @name blofin#fetchPositionMode
* @description fetchs the position mode, hedged or one way
* @see https://docs.blofin.com/index.html#get-position-mode
* @param {string} [symbol] unified symbol of the market to fetch the position mode for (not used in blofin fetchPositionMode)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an object detailing whether the market is in hedged or one-way mode
*/
pub async fn fetch_position_mode(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.private_get_account_position_mode(&[params.clone()]).await;
let mut data: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positionMode: Value = self.safe_string_k(data.clone(), "positionMode", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data.clone());
m.insert("hedged".to_string(), Value::Bool(is_equal(&positionMode, &Value::Str("long_short_mode".to_string()))));
m
});
Value::Null
}
/*
* @method
* @name blofin#setPositionMode
* @description set hedged to true or false for a market
* @see https://docs.blofin.com/index.html#set-position-mode
* @param {bool} hedged set to true to use hedged mode, false for one-way mode
* @param {string} [symbol] not used by setPositionMode ()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
pub async fn set_position_mode(&mut self, mut hedged: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("positionMode".to_string(), ternary(is_true(&hedged), Value::Str("long_short_mode".to_string()), Value::Str("net_mode".to_string())));
m
});
let __ws_arg_29 = self.extend(request.clone(), &[params.clone()]);
return self.private_post_account_set_position_mode(&[__ws_arg_29]).await;
Value::Null
}
/*
* @method
* @name blofin#fetchPositionsADLRank
* @description fetches the auto deleveraging rank and risk percentage for a list of symbols
* @see https://docs.blofin.com/index.html#get-positions
* @param {string[]} [symbols] a list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of [auto de leverage structures]{@link https://docs.ccxt.com/?id=auto-de-leverage-structure}
*/
pub async fn fetch_positions_adl_rank(&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 is_equal(&self.markets, &Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(true), Value::Bool(true)]);
let mut response: Value = self.private_get_account_positions(&[params.clone()]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": [
// {
// "positionId": "756786",
// "instId": "BTC-USDT",
// "instType": "SWAP",
// "marginMode": "cross",
// "positionSide": "net",
// "adl": "1",
// "positions": "0.1",
// "availablePositions": "0.1",
// "averagePrice": "88564.9",
// "markPrice": "88546.3696492756",
// "marginRatio": "822.305183525552961566",
// "liquidationPrice": "",
// "unrealizedPnl": "-0.00185303507244",
// "unrealizedPnlRatio": "-0.000627687178252332",
// "initialMargin": "2.951545654975853333",
// "maintenanceMargin": "0.02656391089478268",
// "createTime": "1767169876207",
// "updateTime": "1767169876207",
// "leverage": "3"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[Value::List(vec![])]);
return self.parse_adl_ranks(data.clone(), &[symbols.clone()]);
Value::Null
}
pub fn parse_adl_rank(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchPositionsADLRank
//
// {
// "positionId": "756786",
// "instId": "BTC-USDT",
// "instType": "SWAP",
// "marginMode": "cross",
// "positionSide": "net",
// "adl": "1",
// "positions": "0.1",
// "availablePositions": "0.1",
// "averagePrice": "88564.9",
// "markPrice": "88546.3696492756",
// "marginRatio": "822.305183525552961566",
// "liquidationPrice": "",
// "unrealizedPnl": "-0.00185303507244",
// "unrealizedPnlRatio": "-0.000627687178252332",
// "initialMargin": "2.951545654975853333",
// "maintenanceMargin": "0.02656391089478268",
// "createTime": "1767169876207",
// "updateTime": "1767169876207",
// "leverage": "3"
// }
//
let mut marketId: Value = self.safe_string_k(info.clone(), "instId", &[]);
let mut timestamp: Value = self.safe_integer_omit_zero(info.clone(), Value::Str("createTime".to_string()), &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone(), Value::Null, Value::Str("contract".to_string())]));
m.insert("rank".to_string(), self.safe_integer_k(info.clone(), "adl", &[]));
m.insert("rating".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m
});
Value::Null
}
pub fn handle_errors(&self, mut httpCode: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if is_equal(&response, &Value::Null) {
return Value::Null;
}
//
// {"code":"152002","msg":"Parameter bar error."}
//
let mut code: Value = self.safe_string_k(response.clone(), "code", &[]);
let mut message: Value = self.safe_string_k(response.clone(), "msg", &[]);
let mut feedback: Value = add(&add(&self.id, &Value::Str(" ".to_string())), &body);
if !is_equal(&code, &Value::Null) && !is_equal(&code, &Value::Str("0".to_string())) {
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), message.clone(), feedback.clone());
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), code.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), message.clone(), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
//
// {
// orderId: null,
// clientOrderId: '',
// msg: 'Order failed. Insufficient USDT margin in account',
// code: '103003'
// }
//
let mut data: Value = self.safe_list_k(response.clone(), "data", &[]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
let mut insideMsg: Value = self.safe_string_k(first.clone(), "msg", &[]);
let mut insideCode: Value = self.safe_string_k(first.clone(), "code", &[]);
if !is_equal(&insideCode, &Value::Null) && !is_equal(&insideCode, &Value::Str("0".to_string())) {
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), insideCode.clone(), feedback.clone());
self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), insideMsg.clone(), feedback.clone());
self.throw_broadly_matched_exception(get_value(&self.exceptions, &Value::Str("broad".to_string())), insideMsg.clone(), feedback.clone());
}
return Value::Null;
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::Str("public".to_string()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".to_string()));
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 request: Value = add(&add(&add(&Value::Str("/api/".to_string()), &self.version), &Value::Str("/".to_string())), &self.implode_params(path.clone(), params.clone()));
let mut query: Value = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
let mut url: Value = add(&get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &Value::Str("rest".to_string())), &request);
// const type = this.getPathAuthenticationType (path);
if is_equal(&api, &Value::Str("public".to_string())) {
if !is_true(&self.is_empty(query.clone())) {
url = add(&url, &add(&Value::Str("?".to_string()), &self.urlencode(query.clone(), &[])));
}
} else if is_equal(&api, &Value::Str("private".to_string())) {
self.check_required_credentials(&[]);
let mut timestamp: Value = to_string_val(&self.milliseconds());
headers = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ACCESS-KEY".to_string(), self.apiKey.clone());
m.insert("ACCESS-PASSPHRASE".to_string(), self.password.clone());
m.insert("ACCESS-TIMESTAMP".to_string(), timestamp.clone());
m.insert("ACCESS-NONCE".to_string(), timestamp.clone());
m
});
let mut sign_body: Value = Value::Str("".to_string());
if is_equal(&method, &Value::Str("GET".to_string())) {
if !is_true(&self.is_empty(query.clone())) {
let mut urlencodedQuery: Value = add(&Value::Str("?".to_string()), &self.urlencode(query.clone(), &[]));
url = add(&url, &urlencodedQuery);
request = add(&request, &urlencodedQuery);
}
} else {
if !is_true(&self.is_empty(query.clone())) {
body = self.json(query.clone());
sign_body = body.clone();
}
add_element_to_object(&mut headers, &Value::Str("Content-Type".to_string()), Value::Str("application/json".to_string()));
}
let mut auth: Value = add(&add(&add(&add(&request, &method), ×tamp), ×tamp), &sign_body);
let mut signature: Value = self.string_to_base64(self.hmac(self.encode(auth.clone()), self.encode(self.secret.clone()), Value::Str("sha256".to_string()), &[]), &[]);
add_element_to_object(&mut headers, &Value::Str("ACCESS-SIGN".to_string()), signature.clone());
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), body.clone());
m.insert("headers".to_string(), headers.clone());
m
});
Value::Null
}
}