// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
pub struct 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])
}
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])
}
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])
}
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])
}
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])
}
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])
}
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])
}
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])
}
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])
}
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])
}
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])
}
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])
}
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, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
// Forward to the inherent method on 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[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"close_position" => self.close_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"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[3.min(args.len())..]),
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args[..]).await,
"fetch_ledger" => self.fetch_ledger(&args[..]).await,
"fetch_leverage" => self.fetch_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_leverages" => self.fetch_leverages(&args[..]).await,
"fetch_margin_mode" => self.fetch_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_mark_price" => self.fetch_mark_price(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_position_mode" => self.fetch_position_mode(&args[..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_positions_adl_rank" => self.fetch_positions_adl_rank(&args[..]).await,
"fetch_positions_history" => self.fetch_positions_history(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"parse_adl_rank" => self.parse_adl_rank(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"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[1.min(args.len())..]),
"parse_ids" => self.parse_ids(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_leverage" => self.parse_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_mode" => self.parse_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order_status" => self.parse_order_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trading_fee" => self.parse_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction_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[1.min(args.len())..]),
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_position_mode" => self.set_position_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"transfer" => self.transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
// Fall through to the base-only methods (cancelOrderWithClientOrderId, …).
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for 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".into()));
m.insert("name".to_string(), Value::Str("BloFin".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("rateLimit".to_string(), Value::Int(200));
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".into()));
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(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".into()));
m.insert("3m".to_string(), Value::Str("3m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15m".to_string(), Value::Str("15m".into()));
m.insert("30m".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1H".into()));
m.insert("2h".to_string(), Value::Str("2H".into()));
m.insert("4h".to_string(), Value::Str("4H".into()));
m.insert("6h".to_string(), Value::Str("6H".into()));
m.insert("8h".to_string(), Value::Str("8H".into()));
m.insert("12h".to_string(), Value::Str("12H".into()));
m.insert("1d".to_string(), Value::Str("1D".into()));
m.insert("3d".to_string(), Value::Str("3D".into()));
m.insert("1w".to_string(), Value::Str("1W".into()));
m.insert("1M".to_string(), Value::Str("1M".into()));
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".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("rest".to_string(), Value::Str("https://openapi.blofin.com".into()));
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".into()));
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".into()));
m.insert("discount".to_string(), Value::Float(0.05));
m
}));
m.insert("www".to_string(), Value::Str("https://www.blofin.com".into()));
m.insert("doc".to_string(), Value::Str("https://blofin.com/docs".into()));
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/instruments-history".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.insert("spot/market/instruments".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/market/tickers".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/market/books".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/market/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("spot/market/candles".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("asset/deposit-address".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/funding-fees".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::Float(1.67));
m
}));
m.insert("trade/order-detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/orders-tpsl-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/order-tpsl-detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/orders-algo-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/orders-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/orders-tpsl-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/orders-algo-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/fills-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/order/price-range".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
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::Float(1.67));
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::Float(1.67));
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::Float(1.67));
m
}));
m.insert("copytrading/trade/orders-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
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::Float(1.67));
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.insert("spot/trade/orders-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/order-detail".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/orders-algo-pending".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/orders-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/orders-algo-history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/order/price-range".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
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("asset/withdrawal-apply".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::Float(1.67));
m
}));
m.insert("account/set-position-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("account/set-leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/order-tpsl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/cancel-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/cancel-batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/cancel-tpsl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/cancel-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/amend-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/amend-batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/amend-tpsl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/amend-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("trade/close-position".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/order-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/cancel-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/cancel-batch-orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("spot/trade/cancel-algo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("copytrading/account/set-position-mode".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("copytrading/account/set-leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("copytrading/trade/place-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
m
}));
m.insert("copytrading/trade/cancel-order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Float(1.67));
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::Float(1.67));
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::Float(1.67));
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::Float(1.67));
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::Float(1.67));
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::Float(1.67));
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::Float(1.67));
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".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.00020".into()), &[]));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(true));
m.insert("password".to_string(), Value::Bool(true));
m
}));
m.insert("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".into()));
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".into()));
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".into()));
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".into()).clone());
m.insert("401".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("500".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("404".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("405".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("406".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("429".to_string(), Value::Str("RateLimitExceeded".into()).clone());
m.insert("152001".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152002".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152003".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152004".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152005".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152006".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("152007".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("152008".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("152009".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("150003".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("150004".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("542".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102002".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102005".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102014".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102015".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102022".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102037".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102038".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102039".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102040".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102047".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102048".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102049".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102050".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102051".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102052".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102053".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102054".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102055".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("102064".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("102065".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("102068".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("103013".to_string(), Value::Str("ExchangeError".into()).clone());
m.insert("102067".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("102089".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("102148".to_string(), Value::Str("DuplicateOrderId".into()).clone());
m.insert("103003".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("110006".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("110019".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("148082".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("148083".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152011".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("152012".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152013".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("152014".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152015".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152020".to_string(), Value::Str("InvalidAddress".into()).clone());
m.insert("152022".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152023".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("152024".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("152025".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("152026".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152027".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152028".to_string(), Value::Str("InsufficientFunds".into()).clone());
m.insert("152029".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("152030".to_string(), Value::Str("DuplicateOrderId".into()).clone());
m.insert("152031".to_string(), Value::Str("InvalidAddress".into()).clone());
m.insert("152032".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("152401".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("152402".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("152404".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("152405".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("152406".to_string(), Value::Str("PermissionDenied".into()).clone());
m.insert("152407".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("152408".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("152409".to_string(), Value::Str("AuthenticationError".into()).clone());
m.insert("152410".to_string(), Value::Str("InvalidNonce".into()).clone());
m.insert("152420".to_string(), Value::Str("DuplicateOrderId".into()).clone());
m.insert("152421".to_string(), Value::Str("DuplicateOrderId".into()).clone());
m.insert("152422".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152423".to_string(), Value::Str("InvalidOrder".into()).clone());
m.insert("152428".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("152429".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("Order failed. Insufficient USDT margin in account".to_string(), Value::Str("InsufficientFunds".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Internal Server Error".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m.insert("server error".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m
}));
m
}));
m.insert("httpExceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("429".to_string(), Value::Str("ExchangeNotAvailable".into()).clone());
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountsByType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("swap".to_string(), Value::Str("futures".into()));
m.insert("funding".to_string(), Value::Str("funding".into()));
m.insert("future".to_string(), Value::Str("futures".into()));
m.insert("copy_trading".to_string(), Value::Str("copy_trading".into()));
m.insert("earn".to_string(), Value::Str("earn".into()));
m.insert("spot".to_string(), Value::Str("spot".into()));
m
}));
m.insert("accountsById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("funding".to_string(), Value::Str("funding".into()));
m.insert("futures".to_string(), Value::Str("swap".into()));
m.insert("copy_trading".to_string(), Value::Str("copy_trading".into()));
m.insert("earn".to_string(), Value::Str("earn".into()));
m.insert("spot".to_string(), Value::Str("spot".into()));
m
}));
m.insert("defaultNetwork".to_string(), Value::Str("ERC20".into()));
m.insert("defaultNetworks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("ETH".to_string(), Value::Str("ERC20".into()));
m.insert("BTC".to_string(), Value::Str("BTC".into()));
m.insert("USDT".to_string(), Value::Str("TRC20".into()));
m
}));
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("BTC".to_string(), Value::Str("Bitcoin".into()));
m.insert("SOL".to_string(), Value::Str("Solana".into()));
m.insert("MATIC".to_string(), Value::Str("Polygon POS".into()));
m.insert("AVAXC".to_string(), Value::Str("AVAX C-Chain".into()));
m.insert("ARBITRUM".to_string(), Value::Str("Arbitrum One".into()));
m.insert("OP".to_string(), Value::Str("Optimism".into()));
m.insert("KAIA".to_string(), Value::Str("KAIA".into()));
m
}));
m.insert("networkPrefixes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("TRC20".to_string(), Value::Str("Tron".into()));
m.insert("ERC20".to_string(), Value::Str("Ethereum".into()));
m.insert("BEP20".to_string(), Value::Str("BNB Smart Chain".into()));
m.insert("APT".to_string(), Value::Str("APT".into()));
m.insert("TON".to_string(), Value::Str("TON".into()));
m
}));
m.insert("networkSuffixes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("TON".to_string(), Value::Str("Toncoin".into()));
m
}));
m.insert("networkCodesBySuffix".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Toncoin".to_string(), Value::Str("TON".into()));
m
}));
m.insert("networksById".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Bitcoin".to_string(), Value::Str("BTC".into()));
m.insert("Solana".to_string(), Value::Str("SOL".into()));
m.insert("Polygon POS".to_string(), Value::Str("MATIC".into()));
m.insert("AVAX C-Chain".to_string(), Value::Str("AVAXC".into()));
m.insert("Arbitrum One".to_string(), Value::Str("ARBITRUM".into()));
m.insert("Optimism".to_string(), Value::Str("OP".into()));
m.insert("BSC".to_string(), Value::Str("BEP20".into()));
m
}));
m.insert("fetchOpenInterestHistory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("1h".to_string(), Value::Str("1H".into()));
m.insert("8h".to_string(), Value::Str("8H".into()));
m.insert("1d".to_string(), Value::Str("1D".into()));
m.insert("5M".to_string(), Value::Str("5m".into()));
m.insert("1H".to_string(), Value::Str("1H".into()));
m.insert("8H".to_string(), Value::Str("8H".into()));
m.insert("1D".to_string(), Value::Str("1D".into()));
m
}));
m
}));
m.insert("defaultType".to_string(), Value::Str("swap".into()));
m.insert("brokerId".to_string(), Value::Str("ec6dd3a7dd982d0b".into()));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetTradeOrdersPending".into()));
m
}));
m.insert("cancelOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privatePostTradeCancelBatchOrders".into()));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("privateGetTradeOrdersHistory".into()));
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("password".to_string(), Value::Null);
m.insert("pwd".to_string(), Value::Null);
m
}));
m.insert("exchangeType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("spot".to_string(), Value::Str("SPOT".into()));
m.insert("swap".to_string(), Value::Str("SWAP".into()));
m.insert("SPOT".to_string(), Value::Str("SPOT".into()));
m.insert("SWAP".to_string(), Value::Str("SWAP".into()));
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]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_markets(data);
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_k(market.clone(), "instType", &[]);
let mut spot: Value = (Value::Bool(type_var.as_str() == Some("spot")));
let mut future: Value = (Value::Bool(type_var.as_str() == Some("future")));
let mut swap: Value = (Value::Bool(type_var.as_str() == Some("swap")));
let mut option: Value = (Value::Bool(type_var.as_str() == Some("option")));
let mut contract: Value = Value::Bool(matches!(&swap, Value::Bool(true)) || matches!(&future, Value::Bool(true)));
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 = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
if matches!(&swap, Value::Bool(true)) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str(":".into())).into()), settle).into());
}
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".into()), &[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, "maker", &[]);
let mut maxLeverage: Value = self.safe_string_k(market.clone(), "maxLeverage", &[Value::Str("100".into())]);
maxLeverage = crate::precise::Precise::stringMax(&maxLeverage, &Value::Str("1".into()));
let mut isActive: Value = (Value::Bool(self.safe_string_k(market.clone(), "state", &[]).as_str() == Some("live")));
let mut isMargin: Value = Value::Bool(matches!(&spot, Value::Bool(true)) && is_true(&(crate::precise::Precise::stringGt(&maxLeverage, &Value::Str("1".into())))));
let mut contractType: Option<String> = self.safe_string_k(market.clone(), "contractType", &[]).as_str().map(str::to_owned);
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);
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settle".to_string(), settle);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), type_var);
m.insert("spot".to_string(), spot);
m.insert("option".to_string(), option);
m.insert("margin".to_string(), isMargin);
m.insert("swap".to_string(), swap);
m.insert("future".to_string(), future);
m.insert("active".to_string(), isActive);
m.insert("taker".to_string(), taker);
m.insert("maker".to_string(), maker);
m.insert("contract".to_string(), contract.clone());
m.insert("linear".to_string(), (if matches!(&contract, Value::Bool(true)) { (Value::Bool(contractType.as_deref() == Some("linear"))) } else { Value::Null }));
m.insert("inverse".to_string(), (if matches!(&contract, Value::Bool(true)) { (Value::Bool(contractType.as_deref() == Some("inverse"))) } else { Value::Null }));
m.insert("contractSize".to_string(), (if matches!(&contract, Value::Bool(true)) { self.safe_number_k(market.clone(), "contractValue", &[]) } else { Value::Null }));
m.insert("expiry".to_string(), expiry.clone());
m.insert("expiryDatetime".to_string(), expiry);
m.insert("strike".to_string(), strikePrice);
m.insert("optionType".to_string(), optionType);
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, &[]));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_number(Value::Str("1".into()), &[]));
m.insert("max".to_string(), self.parse_number(maxLeverage, &[]));
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);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), (if matches!(&contract, Value::Bool(true)) { Value::Null } else { maxSpotCost }));
m
}));
m
}));
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
/*
* @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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
limit = (if (limit == Value::Null) { Value::Int(50) } else { limit.clone() });
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("size".into(), limit); }; // max 100
}
let __ws_arg_0 = self.extend(request, &[params]);
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, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.safe_integer_k(first.clone(), "ts", &[]);
return self.parse_order_book(first, symbol, &[timestamp]);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// 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, market.clone(), Value::Str("-".into())]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut last: Value = self.safe_string_k(ticker.clone(), "last", &[]);
let mut open: Value = self.safe_string_k(ticker.clone(), "open24h", &[]);
let mut spot: Value = self.safe_bool_k(market.clone(), "spot", &[Value::Bool(false)]);
let mut quoteVolume: Value = (if (spot.as_bool() == Some(true)) { self.safe_string_k(ticker.clone(), "volCurrency24h", &[]) } else { Value::Null });
let mut baseVolume: Value = self.safe_string_k(ticker.clone(), "vol24h", &[]);
let mut high: Value = self.safe_string_k(ticker.clone(), "high24h", &[]);
let mut low: Value = self.safe_string_k(ticker.clone(), "low24h", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("high".to_string(), high);
m.insert("low".to_string(), low);
m.insert("bid".to_string(), self.safe_string_k(ticker.clone(), "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);
m.insert("close".to_string(), last.clone());
m.insert("last".to_string(), last);
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), baseVolume);
m.insert("quoteVolume".to_string(), quoteVolume);
m.insert("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);
m
}), &[market]);
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_1 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_tickers(&[__ws_arg_1]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(first, &[market]);
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_2 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_mark_price(&[__ws_arg_2]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(first, &[market]);
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut response: Value = self.public_get_market_tickers(&[params]).await;
let mut tickers: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_tickers(tickers, &[symbols]);
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, market.clone(), Value::Str("-".into())]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_k(trade.clone(), "ts", &[]);
let mut price: Value = self.safe_string2(trade.clone(), Value::Str("price".into()), Value::Str("fillPrice".into()), &[]);
let mut amount: Value = self.safe_string2(trade.clone(), Value::Str("size".into()), Value::Str("fillSize".into()), &[]);
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 = feeCurrency != Value::Null;
if (feeCurrency == Value::Null) {
feeCurrency = market.as_map().and_then(|__m| __m.get("settle")).cloned().unwrap_or(Value::Null);
} else if (feeCurrency.as_str() == Some("base_currency")) {
feeCurrency = market.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null);
} else if (feeCurrency.as_str() == Some("quote_currency")) {
feeCurrency = market.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null);
}
if (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 isSpot {
let mut spotSymbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", market.as_map().and_then(|__m| __m.get("base")).cloned().unwrap_or(Value::Null), Value::Str("/".into())).into()), market.as_map().and_then(|__m| __m.get("quote")).cloned().unwrap_or(Value::Null)).into());
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);
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);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(feeCost, &[]));
m.insert("currency".to_string(), feeCurrency);
m
}));
m
});
return result;
} else {
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("id".to_string(), id);
m.insert("order".to_string(), orderId);
m.insert("type".to_string(), Value::Null);
m.insert("takerOrMaker".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[market]);
}
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 (self.markets.clone() == 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".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_cursor(Value::Str("fetchTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), params.clone(), Value::Str("tradeId".into()), Value::Str("after".into()), Value::Null, Value::Int(100)]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut response: Value = Value::Null;
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100
}
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchTrades".into()), Value::Str("method".into()), &[Value::Str("publicGetMarketTrades".into())]); method = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (method.as_str() == Some("publicGetMarketTrades")) {
let __ws_arg_3 = self.extend(request, &[params]);
response = self.public_get_market_trades(&[__ws_arg_3]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(data, &[market, since, limit]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_integer(ohlcv.clone(), Value::Int(0), &[]), self.safe_number(ohlcv.clone(), Value::Int(1), &[]), self.safe_number(ohlcv.clone(), Value::Int(2), &[]), self.safe_number(ohlcv.clone(), Value::Int(3), &[]), self.safe_number(ohlcv.clone(), Value::Int(4), &[]), self.safe_number(ohlcv, 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".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOHLCV".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchOHLCV".into()), &[symbol, since.clone(), limit.clone(), timeframe.clone(), params.clone(), Value::Int(100)]).await;
}
if (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(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
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 (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("after".into(), until); }
params = self.omit(params.clone(), Value::Str("until".into()), &[]);
}
let __ws_arg_4 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_candles(&[__ws_arg_4]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_ohlc_vs(data, &[market, timeframe, since, limit]);
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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut paginate: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchFundingRateHistory".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_deterministic(Value::Str("fetchFundingRateHistory".into()), &[symbol.clone(), since.clone(), limit.clone(), Value::Str("8h".into()), params.clone(), Value::Int(100)]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), crate::runtime::Math::max(&(match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &Value::Int(0))); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("after".into(), until); }
params = self.omit(params.clone(), Value::Str("until".into()), &[]);
}
let __ws_arg_5 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_funding_rate_history(&[__ws_arg_5]).await;
let mut rates: Value = Value::from(vec![]);
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_442: bool = true;
while { if !__for_first_442 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_442 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut rate: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_k(rate.clone(), "fundingTime", &[]);
append_to_array(&mut rates, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), rate.clone());
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("fundingRate".to_string(), self.safe_number_k(rate, "fundingRate", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
}));
}
}
let mut sorted: Value = self.sort_by(rates, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), since, limit]);
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, &[market]);
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);
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
m.insert("interestRate".to_string(), self.parse_number(Value::Str("0".into()), &[]));
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("fundingRate".to_string(), self.safe_number_k(contract, "fundingRate", &[]));
m.insert("fundingTimestamp".to_string(), fundingTime.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(fundingTime));
m.insert("nextFundingRate".to_string(), 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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
if (market.as_map().and_then(|__m| __m.get("swap")).cloned().unwrap_or(Value::Null).as_bool() != Some(true)) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRate() is only valid for swap markets".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_6 = self.extend(request, &[params]);
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, "data", &[Value::from(vec![])]);
let mut entry: Value = self.safe_dict(data, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_funding_rate(entry, &[market]);
Value::Null
}
pub fn parse_balance_by_type(&self, mut response: Value) -> Value {
let mut data: Value = self.safe_list_k(response.clone(), "data", &[]);
if (data != Value::Null) && (matches!(&data, Value::Arr(_))) {
return self.parse_funding_balance(response.clone());
} else {
return self.parse_balance(response);
}
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, "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, "details", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_443: bool = true;
while { if !__for_first_443 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_443 = false; i.as_f64().unwrap_or(f64::NAN) < ((details.len() as i64) as f64) } {
let mut balance: Value = details.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
// it may be incorrect to use total, free and used for swap accounts
let mut eq: Value = self.safe_string_k(balance.clone(), "equity", &[]);
let mut availEq: Value = self.safe_string_k(balance.clone(), "available", &[]);
if (eq == Value::Null) || (availEq == Value::Null) {
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(balance.clone(), "availableEquity", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(balance, "frozen", &[])); }
} else {
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), eq); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), availEq); }
}
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("timestamp".into(), timestamp.clone()); }
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert("datetime".into(), self.iso8601(timestamp)); }
return self.safe_balance(result);
Value::Null
}
pub fn parse_funding_balance(&self, mut response: Value) -> Value {
//
// {
// "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, "data", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_444: bool = true;
while { if !__for_first_444 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_444 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut balance: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut currencyId: Value = self.safe_string_k(balance.clone(), "currency", &[]);
let mut code: Value = self.safe_currency_code(currencyId, &[]);
let mut account: Value = self.account();
// it may be incorrect to use total, free and used for swap accounts
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(balance.clone(), "balance", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(balance.clone(), "available", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("used".into(), self.safe_string_k(balance, "frozen", &[])); }
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
}
return self.safe_balance(result);
Value::Null
}
pub fn parse_trading_fee(&self, mut fee: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market]));
m.insert("maker".to_string(), self.parse_number(crate::precise::Precise::stringNeg(&self.safe_string2(fee.clone(), Value::Str("maker".into()), Value::Str("makerU".into()), &[])), &[]));
m.insert("taker".to_string(), self.parse_number(crate::precise::Precise::stringNeg(&self.safe_string2(fee, Value::Str("taker".into()), Value::Str("takerU".into()), &[])), &[]));
m.insert("percentage".to_string(), Value::Null);
m.insert("tierBased".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name 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 (self.markets.clone() == 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".into()), Value::Str("accountType".into()), Value::Str("type".into()), &[]); accountType = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut response: Value = Value::Null;
if (accountType != Value::Null) && (accountType.as_str() != Some("swap")) {
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, accountType.clone(), &[accountType.clone()]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("accountType".into(), parsedAccountType); }
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, &[params]);
response = self.private_get_account_balance(&[__ws_arg_8]).await;
}
return self.parse_balance_by_type(response);
Value::Null
}
pub fn create_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("side".to_string(), side.clone());
m.insert("orderType".to_string(), type_var.clone());
m.insert("size".to_string(), self.amount_to_precision(symbol.clone(), amount));
m.insert("brokerId".to_string(), self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("ec6dd3a7dd982d0b".into())]));
m
});
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("createOrder".into()), &[params.clone(), Value::Str("cross".into())]); marginMode = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("marginMode".into(), marginMode); }
let mut triggerPriceAny: Value = self.safe_string_n(params.clone(), Value::from(vec![Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]);
let mut triggerPriceSlTp: Option<String> = self.safe_string2(params.clone(), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), &[]).as_str().map(str::to_owned);
let mut timeInForce: Option<String> = self.safe_string_k(params.clone(), "timeInForce", &[Value::Str("GTC".into())]).as_str().map(str::to_owned);
let mut isHedged: Value = self.safe_bool_k(params.clone(), "hedged", &[Value::Bool(false)]);
if (isHedged.as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("positionSide".into(), (if (side.as_str() == Some("buy")) { Value::Str("long".into()) } else { Value::Str("short".into()) })); }
}
let mut isMarketOrder: Value = Value::Bool(type_var.as_str() == Some("market"));
params = self.omit(params.clone(), Value::from(vec![Value::Str("timeInForce".into())]), &[]);
let mut ioc: bool = (timeInForce.as_deref() == Some("IOC")) || (type_var.as_str() == Some("ioc"));
let mut marketIOC: bool = matches!(&isMarketOrder, Value::Bool(true)) && ioc;
if matches!(&isMarketOrder, Value::Bool(true)) || marketIOC {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderType".into(), Value::Str("market".into())); }
} else {
let mut key: Value = (if (triggerPriceAny != Value::Null) { Value::Str("orderPrice".into()) } else { Value::Str("price".into()) });
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&key), self.price_to_precision(symbol.clone(), price)); }
}
let mut postOnly: Value = Value::Bool(false);
{ let __destr_tmp = self.handle_post_only(isMarketOrder.clone(), Value::Bool(type_var.as_str() == Some("post_only")), &[params.clone()]); postOnly = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&postOnly) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("type".into(), Value::Str("post_only".into())); }
}
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::from(vec![Value::Str("stopLoss".into()), Value::Str("takeProfit".into()), Value::Str("hedged".into())]), &[]);
let mut hasStopLoss: bool = stopLoss != Value::Null;
let mut hasTakeProfit: bool = takeProfit != Value::Null;
if hasStopLoss || hasTakeProfit {
if hasStopLoss {
let mut slTriggerPrice: Value = self.safe_string2(stopLoss.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("slTriggerPrice".into(), self.price_to_precision(symbol.clone(), slTriggerPrice)); }
let mut slOrderPrice: Value = self.safe_string_k(stopLoss, "price", &[Value::Str("-1".into())]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("slOrderPrice".into(), self.price_to_precision(symbol.clone(), slOrderPrice)); }
}
if hasTakeProfit {
let mut tpTriggerPrice: Value = self.safe_string2(takeProfit.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("tpTriggerPrice".into(), self.price_to_precision(symbol.clone(), tpTriggerPrice)); }
let mut tpPrice: Value = self.safe_string_k(takeProfit, "price", &[Value::Str("-1".into())]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("tpOrderPrice".into(), self.price_to_precision(symbol.clone(), tpPrice)); }
}
} else if (triggerPriceAny != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderType".into(), Value::Str("trigger".into())); }
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("triggerPrice".into(), self.price_to_precision(symbol, triggerPriceAny)); }
if matches!(&isMarketOrder, Value::Bool(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderPrice".into(), Value::Str("-1".into())); }
}
if (triggerPriceSlTp.is_some()) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("reduceOnly".into(), Value::Bool(true)); }
}
params = self.omit(params.clone(), Value::from(vec![Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("triggerPrice".into())]), &[]);
}
return self.extend(request, &[params]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("order_failed".to_string(), Value::Str("canceled".into()));
m.insert("live".to_string(), Value::Str("open".into()));
m.insert("partially_filled".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("effective".to_string(), Value::Str("closed".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// 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::from(vec![Value::Str("tpslId".into()), Value::Str("orderId".into()), Value::Str("algoId".into())]), &[]);
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 (type_var.as_str() == Some("post_only")) {
postOnly = Value::Bool(true);
type_var = Value::Str("limit".into());
} else if (type_var.as_str() == Some("fok")) {
timeInForce = Value::Str("FOK".into());
type_var = Value::Str("limit".into());
} else if (type_var.as_str() == Some("ioc")) {
timeInForce = Value::Str("IOC".into());
type_var = Value::Str("limit".into());
} else if (type_var.as_str() == Some("conditional")) {
type_var = Value::Str("trigger".into());
}
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, &[market.clone(), Value::Str("-".into())]);
let mut filled: Value = self.safe_string_k(order.clone(), "filledSize", &[]);
let mut price: Value = self.safe_string_n(order.clone(), Value::from(vec![Value::Str("px".into()), Value::Str("price".into()), Value::Str("orderPrice".into())]), &[]);
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 (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 (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".into())]);
let mut feeCurrencyCode: Value = self.safe_currency_code(feeCurrencyId, &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.parse_number(feeCostSigned, &[]));
m.insert("currency".to_string(), feeCurrencyCode);
m
});
}
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "clientOrderId", &[]);
if (clientOrderId != Value::Null) && (((clientOrderId.len() as i64) as f64) < ((1i64) as f64)) {
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: Option<String> = self.safe_string_k(order.clone(), "reduceOnly", &[]).as_str().map(str::to_owned);
let mut reduceOnly: Value = (Value::Bool(reduceOnlyRaw.as_deref() == Some("true")));
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order);
m.insert("id".to_string(), id);
m.insert("clientOrderId".to_string(), clientOrderId);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), lastTradeTimestamp);
m.insert("lastUpdateTimestamp".to_string(), lastUpdateTimestamp);
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), type_var);
m.insert("timeInForce".to_string(), timeInForce);
m.insert("postOnly".to_string(), postOnly);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("stopLossTriggerPrice".to_string(), stopLossTriggerPrice);
m.insert("takeProfitTriggerPrice".to_string(), takeProfitTriggerPrice);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("average".to_string(), average);
m.insert("cost".to_string(), cost);
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), Value::Null);
m.insert("status".to_string(), status);
m.insert("fee".to_string(), fee);
m.insert("trades".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), reduceOnly);
m
}), &[market]);
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut isStopLossPriceDefined: bool = self.safe_string_k(params.clone(), "stopLossPrice", &[]) != Value::Null;
let mut isTakeProfitPriceDefined: bool = self.safe_string_k(params.clone(), "takeProfitPrice", &[]) != Value::Null;
let mut isTriggerOrder: bool = 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".into()), Value::Str("tpsl".into()), &[Value::Bool(false)]); isTpslEndpoint = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut isCombinedSlTp: bool = (isStopLossPriceDefined && isTakeProfitPriceDefined) || is_true(&isTpslEndpoint);
let mut isSlOrTp: bool = isStopLossPriceDefined || isTakeProfitPriceDefined;
let mut response: Value = Value::Null;
let mut reduceOnly: Value = self.safe_bool_k(params.clone(), "reduceOnly", &[]);
if (reduceOnly != Value::Null) {
if let Value::Dict(__d) = &mut params { std::sync::Arc::make_mut(__d).insert("reduceOnly".into(), (if reduceOnly.as_bool() == Some(true) { Value::Str("true".into()) } else { Value::Str("false".into()) })); }
}
if 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]).await;
} else if isTriggerOrder || 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]).await;
} else {
let mut request: Value = self.create_order_request(symbol, type_var.clone(), side.clone(), amount, &[price, params]);
response = self.private_post_trade_order(&[request]).await;
}
if isCombinedSlTp || isSlOrTp || 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, &[market.clone()]);
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[]);
let mut order: Value = self.parse_order(first, &[market]);
add_element_to_object(&mut order, &Value::Str("type".into()), type_var);
add_element_to_object(&mut order, &Value::Str("side".into()), side);
return order;
Value::Null
}
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".into());
if (hedged.as_bool() == Some(true)) {
positionSide = (if (side.as_str() == Some("buy")) { Value::Str("short".into()) } else { Value::Str("long".into()) });
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("side".to_string(), side);
m.insert("positionSide".to_string(), positionSide);
m.insert("brokerId".to_string(), self.safe_string_k(self.options.clone(), "brokerId", &[Value::Str("ec6dd3a7dd982d0b".into())]));
m.insert("reduceOnly".to_string(), self.safe_bool_k(params.clone(), "reduceOnly", &[Value::Bool(true)]));
m
});
if (amount != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("size".into(), self.amount_to_precision(symbol.clone(), amount)); }
}
let mut marginMode: Value = self.safe_string_k(params.clone(), "marginMode", &[Value::Str("cross".into())]); // cross or isolated
if (marginMode.as_str() != Some("cross")) && (marginMode.as_str() != Some("isolated")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" createTpslOrder() requires a marginMode parameter that must be either cross or isolated".into()))));
}
let mut stopLossPrice: Value = self.safe_string_k(params.clone(), "stopLossPrice", &[]);
let mut takeProfitPrice: Value = self.safe_string_k(params.clone(), "takeProfitPrice", &[]);
if (stopLossPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("slTriggerPrice".into(), self.price_to_precision(symbol.clone(), stopLossPrice)); }
if (type_var.as_str() == Some("market")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("slOrderPrice".into(), Value::Str("-1".into())); }
} else {
let mut slLimitPrice: Value = self.safe_string_k(params.clone(), "stopLossLimitPrice", &[]);
if (slLimitPrice == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createTpslOrder() requires a \"stopLossLimitPrice\" parameter (instead of \"price\" argument) for stop loss orders when the order type is not market".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("slOrderPrice".into(), self.price_to_precision(symbol.clone(), slLimitPrice)); }
params = self.omit(params.clone(), Value::Str("stopLossLimitPrice".into()), &[]);
}
}
if (takeProfitPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("tpTriggerPrice".into(), self.price_to_precision(symbol.clone(), takeProfitPrice)); }
if (type_var.as_str() == Some("market")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("tpOrderPrice".into(), Value::Str("-1".into())); }
} else {
let mut tpLimitPrice: Value = self.safe_string_k(params.clone(), "takeProfitLimitPrice", &[]);
if (tpLimitPrice == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createTpslOrder() requires a \"takeProfitLimitPrice\" parameter (instead of \"price\" argument) for take profit orders when the order type is not market".into()))));
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("tpOrderPrice".into(), self.price_to_precision(symbol, tpLimitPrice)); }
params = self.omit(params.clone(), Value::Str("takeProfitLimitPrice".into()), &[]);
}
}
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("marginMode".into(), marginMode); }
params = self.omit(params.clone(), Value::from(vec![Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("reduceOnly".into()), Value::Str("hedged".into())]), &[]);
return self.extend(request, &[params]);
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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let mut isTrigger: Value = self.safe_bool_k(params.clone(), "trigger", &[Value::Bool(false)]);
let mut isTpsl: Value = self.safe_bool2(params.clone(), Value::Str("tpsl".into()), Value::Str("TPSL".into()), &[Value::Bool(false)]);
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[]);
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clientOrderId".into(), clientOrderId); }
} else {
if (isTrigger.as_bool() != Some(true)) && (isTpsl.as_bool() != Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderId".into(), to_string_val(&id)); }
} else if (isTpsl.as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("tpslId".into(), to_string_val(&id)); }
} else if (isTrigger.as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("algoId".into(), to_string_val(&id)); }
}
}
let mut query: Value = self.omit(params.clone(), Value::from(vec![Value::Str("orderId".into()), Value::Str("clientOrderId".into()), Value::Str("stop".into()), Value::Str("trigger".into()), Value::Str("tpsl".into())]), &[]);
if (isTpsl.as_bool() == Some(true)) {
let mut tpslResponse: Value = self.cancel_orders(Value::from(vec![id]), &[symbol, params]).await;
let mut first: Value = self.safe_dict(tpslResponse, Value::Int(0), &[]);
return first;
} else if (isTrigger.as_bool() == Some(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, "data", &[]);
return self.parse_order(triggerData, &[market.clone()]);
}
let __ws_arg_10 = self.extend(request, &[query]);
let mut response: Value = self.private_post_trade_cancel_order(&[__ws_arg_10]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut order: Value = self.safe_dict(data, Value::Int(0), &[]);
return self.parse_order(order, &[market]);
Value::Null
}
/*
* @method
* @name 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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut ordersRequests: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_445: bool = true;
while { if !__for_first_445 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_445 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = orders.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut 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, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut extendedParams: Value = self.extend(orderParams, &[params.clone()]); // the request does not accept extra params since it's a list, so we're extending each order with the common params
let mut orderRequest: Value = self.create_order_request(marketId, type_var, side, amount, &[price, extendedParams]);
append_to_array(&mut ordersRequests, orderRequest);
}
}
let mut response: Value = self.private_post_trade_batch_orders(&[ordersRequests]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[]);
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 (self.markets.clone() == 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".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchOpenOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100, max 100
}
let mut isTrigger: Value = self.safe_bool_n(params.clone(), Value::from(vec![Value::Str("stop".into()), Value::Str("trigger".into())]), &[Value::Bool(false)]);
let mut isTpSl: Value = self.safe_bool2(params.clone(), Value::Str("tpsl".into()), Value::Str("TPSL".into()), &[Value::Bool(false)]);
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchOpenOrders".into()), Value::Str("method".into()), &[Value::Str("privateGetTradeOrdersPending".into())]); method = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut query: Value = self.omit(params, Value::from(vec![Value::Str("method".into()), Value::Str("stop".into()), Value::Str("trigger".into()), Value::Str("tpsl".into()), Value::Str("TPSL".into())]), &[]);
let mut response: Value = Value::Null;
if (isTpSl.as_bool() == Some(true)) || (method.as_str() == Some("privateGetTradeOrdersTpslPending")) {
let __ws_arg_11 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_trade_orders_tpsl_pending(&[__ws_arg_11]).await;
} else if (isTrigger.as_bool() == Some(true)) || (method.as_str() == Some("privateGetTradeOrdersAlgoPending")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderType".into(), Value::Str("trigger".into())); }
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, &[query]);
response = self.private_get_trade_orders_pending(&[__ws_arg_13]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name 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 (self.markets.clone() == 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".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchMyTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
{ let __destr_tmp = self.handle_until_option(Value::Str("end".into()), request.clone(), params.clone(), &[]); request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100, max 100
}
let mut type_var: Value = Value::Str("swap".into());
{ let __destr_tmp = self.handle_market_type_and_params(Value::Str("fetchMyTrades".into()), &[market.clone(), params.clone(), type_var.clone()]); type_var = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut response: Value = Value::Null;
if (type_var.as_str() == Some("spot")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instType".into(), Value::Str("SPOT".into())); }
//
// {
// "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, &[params]);
response = self.private_get_trade_fills_history(&[__ws_arg_15]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_trades(data, &[market, since, limit]);
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 (self.markets.clone() == 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".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchDeposits".into()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("currency".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), crate::runtime::Math::max(&(match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &Value::Int(0))); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100, max 100
}
{ let __destr_tmp = self.handle_until_option(Value::Str("after".into()), request.clone(), params.clone(), &[]); request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let __ws_arg_16 = self.extend(request, &[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, "data", &[Value::from(vec![])]);
return self.parse_transactions(data, &[currency, since, limit, params]);
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 (self.markets.clone() == 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".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchWithdrawals".into()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("currency".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("before".into(), crate::runtime::Math::max(&(match (&(since), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }), &Value::Int(0))); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100, max 100
}
{ let __destr_tmp = self.handle_until_option(Value::Str("after".into()), request.clone(), params.clone(), &[]); request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let __ws_arg_17 = self.extend(request, &[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, "data", &[Value::from(vec![])]);
return self.parse_transactions(data, &[currency, since, limit, params]);
Value::Null
}
pub fn network_code_to_chain_id(&self, mut networkCode: Value) -> Option<String> {
// the live venue identifies chains by display names; the suffix
// family is built here as prefix + space + parenthesized suffix
// because such literals are not transpiler-safe in source
let mut networks: Value = self.safe_dict_k(self.options.clone(), "networks", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut direct: Value = self.safe_string(networks, networkCode.clone(), &[]);
if (direct != Value::Null) {
return direct.as_str().map(str::to_owned);
}
let mut prefixes: Value = self.safe_dict_k(self.options.clone(), "networkPrefixes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut prefix: Value = self.safe_string(prefixes, networkCode.clone(), &[]);
if (prefix != Value::Null) {
let mut suffixes: Value = self.safe_dict_k(self.options.clone(), "networkSuffixes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut suffix: Value = self.safe_string(suffixes, networkCode.clone(), &[networkCode.clone()]);
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", prefix, Value::Str(" ".into())).into()), Value::Str("(".into())).into()), suffix).into()), Value::Str(")".into())).into()).as_str().map(str::to_owned);
}
return networkCode.as_str().map(str::to_owned);
}
pub fn chain_id_to_network_code(&self, mut chainId: Value) -> Option<String> {
// live history rows and the currencies registry carry display-name
// chain ids like Tron with a parenthesized TRC20 suffix (verified
// live 2026-09-15), while the doc examples still show short forms -
// parse the suffix when present, fall back to the id maps otherwise
if (chainId == Value::Null) {
return None;
}
if Value::Int(chainId.as_str().and_then(|__s| __s.find("(")).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) > ((-1i64) as f64) {
// php-safe suffix extraction: split instead of index arithmetic,
// because a stored strpos result and a two-argument slice do not
// survive the php conversion (false-vs-int compare; length arg)
let mut parts: Value = split(&chainId, &Value::Str("(".into()));
let mut tail: Value = self.safe_string(parts, Value::Int(1), &[Value::Str("".into())]);
let mut tailParts: Value = split(&tail, &Value::Str(")".into()));
let mut suffix: Value = self.safe_string(tailParts, Value::Int(0), &[]);
let mut bySuffix: Value = self.safe_dict_k(self.options.clone(), "networkCodesBySuffix", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_string(bySuffix, suffix.clone(), &[suffix.clone()]).as_str().map(str::to_owned);
}
return self.network_id_to_code(&[chainId]).as_str().map(str::to_owned);
}
/*
* @method
* @name blofin#withdraw
* @description make a withdrawal
* @see https://docs.blofin.com/index.html#withdrawal
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw, the withdrawal fee is not included and must be reserved on top
* @param {string} address the address to withdraw to, or a UID / email / phone number for an internal transfer
* @param {string} tag additional identifier (memo / payment id) required by certain networks
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network] the unified network code for on-chain withdrawals, mapped to the exchange's chain name
* @param {string} [params.dest] 'onchain' (default) or 'internal' for an internal transfer
* @param {string} [params.addrType] address type, 1: wallet address, 2: UID, 3: email, 4: mobile phone
* @param {string} [params.areaCode] area code for the phone number, required when address is a phone number
* @param {string} [params.clientId] a client-supplied id of up to 32 case-sensitive alphanumerics
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut tag = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// LIVE API vs DOCS quirks, verified against the venue 2026-09-14:
// - addrType is documented optional but the live venue rejects
// on-chain withdrawals without it: 152001 "Parameter addrType
// cannot be empty" - defaulted to 1 below
// - the chain identifiers accepted here are the DISPLAY NAMES from
// GET /asset/currencies ("Tron (TRC20)", "Ethereum (ERC20)", ...);
// the short forms shown in the doc examples ("TRC20") are rejected
// with 152002 "Invalid parameter" - see options["networks"]
// - 152002 responses omit the offending field name even though the
// error table documents the message as "Parameter {} error"
{ let __destr_tmp = self.handle_withdraw_tag_and_params(tag.clone(), params.clone()); tag = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
self.load_markets(&[]).await;
let mut currency: Value = self.currency(code);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("address".to_string(), address.clone());
m.insert("amount".to_string(), self.number_to_string(amount));
m
});
let mut dest: Value = self.safe_string_k(params.clone(), "dest", &[Value::Str("onchain".into())]);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("dest".into(), dest.clone()); }
params = self.omit(params.clone(), Value::Str("dest".into()), &[]);
if (dest.as_str() == Some("onchain")) {
self.check_address(&[address]);
// the doc's Request Parameters table marks addrType "Required:
// No", but the live venue rejects on-chain withdrawals without
// it (152001 "Parameter addrType cannot be empty") - default to
// 1 = wallet address, callers can override for other kinds
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("addrType".into(), self.safe_string_k(params.clone(), "addrType", &[Value::Str("1".into())])); }
params = self.omit(params.clone(), Value::Str("addrType".into()), &[]);
}
if (tag != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("tag".into(), tag); }
}
// consume the unified network key unconditionally so it never leaks
// onto the wire; an explicit raw params['chain'] takes precedence
let mut networkCode: Value = Value::Null;
{ let __destr_tmp = self.handle_network_code_and_params(params.clone()); networkCode = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut chain: Option<String> = self.safe_string_k(params.clone(), "chain", &[]).as_str().map(str::to_owned);
if (chain.is_none()) {
if (networkCode != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("chain".into(), self.network_code_to_chain_id(networkCode).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null)); }
} else if (dest.as_str() == Some("onchain")) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" withdraw() requires a params[\"network\"] or params[\"chain\"] for on-chain withdrawals".into()))));
}
}
let __ws_arg_18 = self.extend(request.clone(), &[params]);
let mut response: Value = self.private_post_asset_withdrawal_apply(&[__ws_arg_18]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": {
// "withdrawId": "a1b2c3d4e5",
// "clientId": "broker-20260706-0001"
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_19 = self.extend(request, &[data]);
return self.parse_transaction(__ws_arg_19, &[currency]);
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 (self.markets.clone() == 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".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchLedger".into()), &[code.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("currency".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
{ let __destr_tmp = self.handle_until_option(Value::Str("end".into()), request.clone(), params.clone(), &[]); request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let __ws_arg_20 = self.extend(request, &[params]);
let mut response: Value = self.private_get_asset_bills(&[__ws_arg_20]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_ledger(data, &[currency, since, limit]);
Value::Null
}
pub fn parse_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 (withdrawalId != Value::Null) {
type_var = Value::Str("withdrawal".into());
id = withdrawalId;
status = self.parse_transaction_withdrawal_status(self.safe_string_k(transaction.clone(), "state", &[]));
} else {
id = depositId;
type_var = Value::Str("deposit".into());
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, &[]);
let mut amount: Value = self.safe_number_k(transaction.clone(), "amount", &[]);
// live history rows carry the DISPLAY-NAME chain identifiers
// ('Tron (TRC20)', verified live 2026-09-15) even though the doc
// examples show short forms ('TRC20') - chainIdToNetworkCode parses
// the parenthesized suffix for the display-name family, and the
// paren-free ids resolve through the base networkIdToCode with
// options['networksById']. note the history
// amount is NET of the fee: a 30 USDT withdrawal-apply lands as
// amount 29 + fee 1
let mut networkId: Value = self.safe_string_k(transaction.clone(), "chain", &[]);
let mut networkCode: Value = self.chain_id_to_network_code(networkId).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
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, &[]);
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);
m.insert("id".to_string(), id);
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), amount);
m.insert("network".to_string(), networkCode);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("addressTo".to_string(), addressTo);
m.insert("address".to_string(), address);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("tagTo".to_string(), tagTo.clone());
m.insert("tag".to_string(), tagTo);
m.insert("status".to_string(), status);
m.insert("type".to_string(), type_var);
m.insert("updated".to_string(), Value::Null);
m.insert("txid".to_string(), txid);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("internal".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), feeCode);
m.insert("cost".to_string(), feeCost);
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".into()));
m.insert("2".to_string(), Value::Str("failed".into()));
m.insert("3".to_string(), Value::Str("ok".into()));
m.insert("4".to_string(), Value::Str("failed".into()));
m.insert("6".to_string(), Value::Str("pending".into()));
m.insert("7".to_string(), Value::Str("pending".into()));
m
});
return self.safe_string(statuses, 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".into()));
m.insert("1".to_string(), Value::Str("ok".into()));
m.insert("2".to_string(), Value::Str("failed".into()));
m.insert("3".to_string(), Value::Str("pending".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1".to_string(), Value::Str("transfer".into()));
m.insert("2".to_string(), Value::Str("trade".into()));
m.insert("3".to_string(), Value::Str("trade".into()));
m.insert("4".to_string(), Value::Str("rebate".into()));
m.insert("5".to_string(), Value::Str("trade".into()));
m.insert("6".to_string(), Value::Str("transfer".into()));
m.insert("7".to_string(), Value::Str("trade".into()));
m.insert("8".to_string(), Value::Str("fee".into()));
m.insert("9".to_string(), Value::Str("trade".into()));
m.insert("10".to_string(), Value::Str("trade".into()));
m.insert("11".to_string(), Value::Str("trade".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
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, &[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", &[])).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), self.safe_number_k(item, "amount", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), Value::Null);
m.insert("status".to_string(), Value::Str("ok".into()));
m.insert("fee".to_string(), Value::Null);
m
}), &[currency]);
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 matches!(&ids, Value::Str(_)) {
return split(&ids, &Value::Str(",".into()));
} 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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::from(vec![]);
let mut method: Value = self.handle_option(Value::Str("cancelOrders".into()), Value::Str("method".into()), &[Value::Str("privatePostTradeCancelBatchOrders".into())]);
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::from(vec![Value::Str("stop".into()), Value::Str("trigger".into()), Value::Str("tpsl".into())]), &[]);
if (trigger.as_bool() == Some(true)) {
method = Value::Str("privatePostTradeCancelTpsl".into());
}
if (clientOrderIds == Value::Null) {
ids = self.parse_ids(ids.clone());
if (tpslIds != Value::Null) {
{
let mut i: Value = Value::Int(0);
let mut __for_first_446: bool = true;
while { if !__for_first_446 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_446 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&tpslIds).as_f64().unwrap_or(f64::NAN) } {
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(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
}
}
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_447: bool = true;
while { if !__for_first_447 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_447 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
if (trigger.as_bool() == Some(true)) {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tpslId".to_string(), ids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
} else {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), ids.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
}));
}
}
}
} else {
{
let mut i: Value = Value::Int(0);
let mut __for_first_448: bool = true;
while { if !__for_first_448 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_448 = false; i.as_f64().unwrap_or(f64::NAN) < get_array_length(&clientOrderIds).as_f64().unwrap_or(f64::NAN) } {
append_to_array(&mut request, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("clientOrderId".to_string(), get_value(&clientOrderIds, &i));
m
}));
}
}
}
let mut response: Value = Value::Null;
if (method.as_str() == Some("privatePostTradeCancelTpsl")) {
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]).await; // * dont extend with params, otherwise ARRAY will be turned into OBJECT
}
let mut ordersData: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(ordersData, &[market, Value::Null, Value::Null, params]);
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut currency: Value = self.currency(code.clone());
let mut accountsByType: Value = self.safe_dict_k(self.options.clone(), "accountsByType", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fromId: Value = self.safe_string(accountsByType.clone(), fromAccount.clone(), &[fromAccount.clone()]);
let mut toId: Value = self.safe_string(accountsByType, toAccount.clone(), &[toAccount.clone()]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("amount".to_string(), self.currency_to_precision(code, amount, &[]));
m.insert("fromAccount".to_string(), fromId);
m.insert("toAccount".to_string(), toId);
m
});
let __ws_arg_21 = self.extend(request, &[params]);
let mut response: Value = self.private_post_asset_transfer(&[__ws_arg_21]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_transfer(data, &[currency]);
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
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);
m.insert("id".to_string(), id);
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_22 = self.extend(request, &[params]);
let mut response: Value = self.private_get_account_positions(&[__ws_arg_22]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut position: Value = self.safe_dict(data, Value::Int(0), &[]);
if (position == Value::Null) {
panic!("{}", crate::exchange_errors::null_response(format!("{}{}", self.id.clone(), Value::Str(" fetchPosition() returned empty position".into()))));
}
return self.parse_position(position, &[market]);
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut response: Value = self.private_get_account_positions(&[params]).await;
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut result: Value = self.parse_positions(data, &[]);
return self.filter_by_array_positions(result, Value::Str("symbol".into()), &[symbols, 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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbols != Value::Null) {
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
if (symbolsLength == 0.0) {
market = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(100))); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("begin".into(), since.clone()); }
}
{ let __destr_tmp = self.handle_until_option(Value::Str("end".into()), request.clone(), params.clone(), &[]); request = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let __ws_arg_23 = self.extend(request, &[params.clone()]);
let mut response: Value = self.private_get_account_positions_history(&[__ws_arg_23]).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, "data", &[Value::from(vec![])]);
let mut positions: Value = self.parse_positions(data, &[symbols, params]);
return self.filter_by_since_limit(positions, &[since, limit]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// 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, market.clone()]);
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
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(side.as_str() != Some("net"));
let mut contracts: Value = self.parse_number(contractsAbs.clone(), &[]);
if (pos != Value::Null) {
if (side.as_str() == Some("net")) {
if is_true(&crate::precise::Precise::stringGt(&pos, &Value::Str("0".into()))) {
side = Value::Str("long".into());
} else if is_true(&crate::precise::Precise::stringLt(&pos, &Value::Str("0".into()))) {
side = Value::Str("short".into());
} else {
side = Value::Null;
}
}
}
let mut contractSize: Value = self.safe_number_k(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 (market.as_map().and_then(|__m| __m.get("inverse")).cloned().unwrap_or(Value::Null).as_bool() == Some(true)) {
notionalString = crate::precise::Precise::stringDiv(&crate::precise::Precise::stringMul(&contractsAbs, &contractSizeString), &markPriceString);
}
let mut notional: Value = self.parse_number(notionalString.clone(), &[]);
let mut marginMode: Value = self.safe_string_k(position.clone(), "marginMode", &[]);
let mut initialMarginString: Value = Value::Null;
let mut entryPriceString: Value = self.safe_string2(position.clone(), Value::Str("averagePrice".into()), Value::Str("openAveragePrice".into()), &[]);
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 (marginMode.as_str() == Some("cross")) {
initialMarginString = self.safe_string_k(position.clone(), "initialMargin", &[]);
collateralString = crate::precise::Precise::stringAdd(&initialMarginString, &unrealizedPnlString);
} else if (marginMode.as_str() == Some("isolated")) {
initialMarginPercentage = crate::precise::Precise::stringDiv(&Value::Str("1".into()), &leverageString);
collateralString = self.safe_string_k(position.clone(), "margin", &[]);
}
let mut maintenanceMarginString: Value = self.safe_string_k(position.clone(), "maintenanceMargin", &[]);
let mut maintenanceMargin: Value = self.parse_number(maintenanceMarginString.clone(), &[]);
let mut maintenanceMarginPercentageString: Value = crate::precise::Precise::stringDiv(&maintenanceMarginString, ¬ionalString);
if (initialMarginPercentage == Value::Null) {
initialMarginPercentage = self.parse_number(crate::precise::Precise::stringDivPrec(&initialMarginString, ¬ionalString, &Value::Int(4)), &[]);
} else if (initialMarginString == Value::Null) {
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".into()); // round to closest 0.01%
let mut maintenanceMarginPercentage: Value = self.parse_number(crate::precise::Precise::stringDivPrec(&crate::precise::Precise::stringAdd(&maintenanceMarginPercentageString, &rounder), &Value::Str("1".into()), &Value::Int(4)), &[]);
let mut liquidationPrice: Value = self.safe_number_k(position.clone(), "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".into())), &[]);
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);
m.insert("notional".to_string(), notional);
m.insert("marginMode".to_string(), marginMode);
m.insert("liquidationPrice".to_string(), liquidationPrice);
m.insert("entryPrice".to_string(), self.parse_number(entryPriceString, &[]));
m.insert("exitPrice".to_string(), self.safe_number_k(position.clone(), "closeAveragePrice", &[]));
m.insert("unrealizedPnl".to_string(), self.parse_number(unrealizedPnlString, &[]));
m.insert("realizedPnl".to_string(), self.safe_number_k(position, "realizedPnl", &[]));
m.insert("percentage".to_string(), percentage);
m.insert("contracts".to_string(), contracts);
m.insert("contractSize".to_string(), contractSize);
m.insert("markPrice".to_string(), self.parse_number(markPriceString, &[]));
m.insert("lastPrice".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("hedged".to_string(), hedged);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastUpdateTimestamp".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), maintenanceMargin);
m.insert("maintenanceMarginPercentage".to_string(), maintenanceMarginPercentage);
m.insert("collateral".to_string(), self.parse_number(collateralString, &[]));
m.insert("initialMargin".to_string(), self.parse_number(initialMarginString, &[]));
m.insert("initialMarginPercentage".to_string(), self.parse_number(initialMarginPercentage, &[]));
m.insert("leverage".to_string(), self.parse_number(leverageString, &[]));
m.insert("marginRatio".to_string(), marginRatio);
m.insert("stopLossPrice".to_string(), Value::Null);
m.insert("takeProfitPrice".to_string(), Value::Null);
m
}));
Value::Null
}
/*
* @method
* @name 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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbols == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchLeverages() requires a symbols argument".into()))));
}
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("fetchLeverages".into()), &[params.clone()]); marginMode = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (marginMode == Value::Null) {
marginMode = self.safe_string_k(params.clone(), "marginMode", &[Value::Str("cross".into())]); // cross as default marginMode
}
if (marginMode.as_str() != Some("cross")) && (marginMode.as_str() != Some("isolated")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchLeverages() requires a marginMode parameter that must be either cross or isolated".into()))));
}
symbols = self.market_symbols(&[symbols.clone()]);
let mut symbolsList: Value = symbols.clone();
let mut instIds: Value = Value::Str("".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_449: bool = true;
while { if !__for_first_449 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }); } __for_first_449 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbolsList.len() as i64) as f64) } {
let mut entry: Value = symbolsList.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut entryMarket: Value = self.market(entry);
if i.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
instIds = Value::Str(format!("{}{}", Value::Str(format!("{}{}", instIds, Value::Str(",".into())).into()), entryMarket.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
} else {
instIds = Value::Str(format!("{}{}", instIds, entryMarket.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)).into());
}
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), instIds);
m.insert("marginMode".to_string(), marginMode);
m
});
let __ws_arg_24 = self.extend(request, &[params]);
let mut response: Value = self.private_get_account_batch_leverage_info(&[__ws_arg_24]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": [
// {
// "leverage": "3",
// "marginMode": "cross",
// "instId": "BTC-USDT"
// },
// ]
// }
//
let mut leverages: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_leverages(leverages, &[symbols, Value::Str("instId".into())]);
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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("fetchLeverage".into()), &[params.clone()]); marginMode = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (marginMode == Value::Null) {
marginMode = self.safe_string_k(params.clone(), "marginMode", &[Value::Str("cross".into())]); // cross as default marginMode
}
if (marginMode.as_str() != Some("cross")) && (marginMode.as_str() != Some("isolated")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" fetchLeverage() requires a marginMode parameter that must be either cross or isolated".into()))));
}
let mut market: Value = self.market(symbol);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("marginMode".to_string(), marginMode);
m
});
let __ws_arg_25 = self.extend(request, &[params]);
let mut response: Value = self.private_get_account_leverage_info(&[__ws_arg_25]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": {
// "leverage": "3",
// "marginMode": "cross",
// "instId": "BTC-USDT"
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_leverage(data, &[market]);
Value::Null
}
pub fn parse_leverage(&self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: 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, &[market]));
m.insert("marginMode".to_string(), self.safe_string_lower_k(leverage, "marginMode", &[]));
m.insert("longLeverage".to_string(), leverageValue.clone());
m.insert("shortLeverage".to_string(), leverageValue);
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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a symbol argument".into()))));
}
// WARNING: THIS WILL INCREASE LIQUIDATION PRICE FOR OPEN ISOLATED LONG POSITIONS
// AND DECREASE LIQUIDATION PRICE FOR OPEN ISOLATED SHORT POSITIONS
if (leverage.as_f64().unwrap_or(f64::NAN) < ((1i64) as f64)) || (leverage.as_f64().unwrap_or(f64::NAN) > ((125i64) as f64)) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() leverage should be between 1 and 125".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("setLeverage".into()), &[params.clone(), Value::Str("cross".into())]); marginMode = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if (marginMode.as_str() != Some("cross")) && (marginMode.as_str() != Some("isolated")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a marginMode parameter that must be either cross or isolated".into()))));
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), leverage);
m.insert("marginMode".to_string(), marginMode);
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_26 = self.extend(request, &[params]);
let mut response: Value = self.private_post_account_set_leverage(&[__ws_arg_26]).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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut clientOrderId: Value = self.safe_string_k(params.clone(), "clientOrderId", &[]);
let mut marginMode: Value = Value::Null;
{ let __destr_tmp = self.handle_margin_mode_and_params(Value::Str("closePosition".into()), &[params.clone(), Value::Str("cross".into())]); marginMode = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("instId".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("marginMode".to_string(), marginMode);
m
});
if (clientOrderId != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("clientOrderId".into(), clientOrderId); }
}
let __ws_arg_27 = self.extend(request, &[params]);
let mut response: Value = self.private_post_trade_close_position(&[__ws_arg_27]).await;
return self.safe_dict_k(response, "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 (self.markets.clone() == 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".into()), Value::Str("paginate".into()), &[]); paginate = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
if is_true(&paginate) {
return self.fetch_paginated_call_dynamic(Value::Str("fetchClosedOrders".into()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("instId".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }; // default 100, max 100
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("begin".into(), since.clone()); }
}
let mut isTrigger: Value = self.safe_bool_n(params.clone(), Value::from(vec![Value::Str("stop".into()), Value::Str("trigger".into()), Value::Str("tpsl".into()), Value::Str("TPSL".into())]), &[Value::Bool(false)]);
let mut method: Value = Value::Null;
{ let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("fetchClosedOrders".into()), Value::Str("method".into()), &[Value::Str("privateGetTradeOrdersHistory".into())]); method = __destr_tmp.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null); params = __destr_tmp.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null); }
let mut query: Value = self.omit(params, Value::from(vec![Value::Str("method".into()), Value::Str("stop".into()), Value::Str("trigger".into()), Value::Str("tpsl".into()), Value::Str("TPSL".into())]), &[]);
let mut response: Value = Value::Null;
if (isTrigger.as_bool() == Some(true)) || (method.as_str() == Some("privateGetTradeOrdersTpslHistory")) {
let __ws_arg_28 = self.extend(request.clone(), &[query.clone()]);
response = self.private_get_trade_orders_tpsl_history(&[__ws_arg_28]).await;
} else {
let __ws_arg_29 = self.extend(request, &[query]);
response = self.private_get_trade_orders_history(&[__ws_arg_29]).await;
}
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
Value::Null
}
/*
* @method
* @name 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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut response: Value = self.private_get_account_margin_mode(&[params]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": {
// "marginMode": "cross"
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_mode(data, &[market]);
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, "symbol", &[]));
m.insert("marginMode".to_string(), self.safe_string_k(marginMode, "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".into()), marginMode.clone(), Value::Str("marginMode".into()), &[Value::from(vec![Value::Str("cross".into()), Value::Str("isolated".into())])]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), marginMode);
m
});
let __ws_arg_30 = self.extend(request, &[params]);
let mut response: Value = self.private_post_account_set_margin_mode(&[__ws_arg_30]).await;
//
// {
// "code": "0",
// "msg": "success",
// "data": {
// "marginMode": "isolated"
// }
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_margin_mode(data, &[market]);
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]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut positionMode: Option<String> = self.safe_string_k(data.clone(), "positionMode", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data);
m.insert("hedged".to_string(), Value::Bool(positionMode.as_deref() == Some("long_short_mode")));
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(), (if is_true(&hedged) { Value::Str("long_short_mode".into()) } else { Value::Str("net_mode".into()) }));
m
});
let __ws_arg_31 = self.extend(request, &[params]);
return self.private_post_account_set_position_mode(&[__ws_arg_31]).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 (self.markets.clone() == 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]).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, "data", &[Value::from(vec![])]);
return self.parse_adl_ranks(data, &[symbols]);
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".into()), &[]);
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, &[market, Value::Null, Value::Str("contract".into())]));
m.insert("rank".to_string(), self.safe_integer_k(info, "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));
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 (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 = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
if (code != Value::Null) && (code.as_str() != Some("0")) {
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), message.clone(), feedback.clone());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), code, feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message, feedback.clone());
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, "data", &[]);
let mut first: Value = self.safe_dict(data, Value::Int(0), &[]);
let mut insideMsg: Value = self.safe_string_k(first.clone(), "msg", &[]);
let mut insideCode: Value = self.safe_string_k(first, "code", &[]);
if (insideCode != Value::Null) && (insideCode.as_str() != Some("0")) {
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), insideCode, feedback.clone());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), insideMsg.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), insideMsg, feedback);
}
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".into()));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut headers = get_arg(optional_args, 3, Value::Null);
let mut body = get_arg(optional_args, 4, Value::Null);
let mut request: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("/api/".into()), self.version.clone()).into()), Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
let mut query: Value = self.omit(params, self.extract_params(path), &[]);
let mut url: Value = add(&self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("rest")).cloned().unwrap_or(Value::Null), &request);
// const type = this.getPathAuthenticationType (path);
if (api.as_str() == Some("public")) {
if !(self.is_empty(query.clone()).as_bool() == Some(true)) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
}
} else if (api.as_str() == Some("private")) {
self.check_required_credentials(&[]);
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("".into());
if (method.as_str() == Some("GET")) {
if !(self.is_empty(query.clone()).as_bool() == Some(true)) {
let mut urlencodedQuery: Value = Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into());
url = Value::Str(format!("{}{}", url, urlencodedQuery).into());
request = Value::Str(format!("{}{}", request, urlencodedQuery).into());
}
} else {
if !(self.is_empty(query.clone()).as_bool() == Some(true)) {
body = json_stringify(&query);
sign_body = body.clone();
}
if let Value::Dict(__d) = &mut headers { std::sync::Arc::make_mut(__d).insert("Content-Type".into(), Value::Str("application/json".into())); }
}
let mut auth: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", add(&request, &method), timestamp).into()), timestamp).into()), sign_body).into());
let mut signature: Value = self.string_to_base64(self.hmac(self.encode(auth), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[]), &[]);
if let Value::Dict(__d) = &mut headers { std::sync::Arc::make_mut(__d).insert("ACCESS-SIGN".into(), signature); }
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), body);
m.insert("headers".to_string(), headers);
m
});
Value::Null
}
}