// 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 HibachiCore {
pub exchange: crate::exchange::Exchange,
}
impl HibachiCore {
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 = HibachiCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for HibachiCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_balance(&self, response: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::parse_balance(self, response)
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::parse_position(self, position, &[market])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::parse_transaction(self, transaction, &[currency])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on HibachiCore.
HibachiCore::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 HibachiCore.
HibachiCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for HibachiCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_order_request" => self.cancel_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_order_request" => self.edit_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]),
"edit_orders" => self.edit_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"encode_withdraw_message" => self.encode_withdraw_message(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)),
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_deposit_address" => self.fetch_deposit_address(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_deposits_withdrawals" => self.fetch_deposits_withdrawals(&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_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_settlement_history" => self.fetch_my_settlement_history(&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_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders_by_status" => self.fetch_orders_by_status(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trading_fees" => self.fetch_trading_fees(&args[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"get_account_id" => self.get_account_id(),
"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)),
"hardcoded_currencies" => self.hardcoded_currencies(),
"nonce" => self.nonce(),
"order_message" => self.order_message(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[6.min(args.len())..]),
"parse_balance" => self.parse_balance(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_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_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_settlement" => self.parse_settlement(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_settlements" => self.parse_settlements(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_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction_status" => self.parse_transaction_status(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"sign_message" => self.sign_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"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 HibachiCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for HibachiCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl HibachiCore {
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("hibachi".into()));
m.insert("name".to_string(), Value::Str("Hibachi".into()));
m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
m.insert("rateLimit".to_string(), Value::Int(100));
m.insert("userAgent".to_string(), self.userAgents.as_map().and_then(|__m| __m.get("chrome")).cloned().unwrap_or(Value::Null));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(false));
m.insert("dex".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("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("cancelWithdraw".to_string(), Value::Bool(false));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createConvertTrade".to_string(), Value::Bool(false));
m.insert("createDepositAddress".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketOrder".to_string(), Value::Bool(false));
m.insert("createMarketOrderWithCost".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(false));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(false));
m.insert("createStopLimitOrder".to_string(), Value::Bool(false));
m.insert("createStopLossOrder".to_string(), Value::Bool(false));
m.insert("createStopMarketOrder".to_string(), Value::Bool(false));
m.insert("createStopOrder".to_string(), Value::Bool(false));
m.insert("createTakeProfitOrder".to_string(), Value::Bool(false));
m.insert("createTrailingAmountOrder".to_string(), Value::Bool(false));
m.insert("createTrailingPercentOrder".to_string(), Value::Bool(false));
m.insert("createTriggerOrder".to_string(), Value::Bool(false));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("editOrders".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(true));
m.insert("fetchClosedOrder".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchConvertCurrencies".to_string(), Value::Bool(false));
m.insert("fetchConvertQuote".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchDepositAddress".to_string(), Value::Bool(true));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositsWithdrawals".to_string(), Value::Bool(true));
m.insert("fetchFundingHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingInterval".to_string(), Value::Bool(false));
m.insert("fetchFundingIntervals".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(false));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLeverage".to_string(), Value::Bool(false));
m.insert("fetchMarginAdjustmentHistory".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMySettlementHistory".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
m.insert("fetchOpenOrder".to_string(), Value::Bool(false));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(false));
m.insert("fetchOrdersByStatus".to_string(), Value::Bool(true));
m.insert("fetchOrderTrades".to_string(), Value::Bool(false));
m.insert("fetchPosition".to_string(), Value::Bool(false));
m.insert("fetchPositionMode".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPremiumIndexOHLCV".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(false));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(false));
m.insert("fetchTradingFees".to_string(), Value::Bool(true));
m.insert("fetchTradingLimits".to_string(), Value::Bool(false));
m.insert("fetchTransactions".to_string(), Value::Str("emulated".into()));
m.insert("fetchTransfers".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(false));
m.insert("setLeverage".to_string(), Value::Bool(false));
m.insert("setMargin".to_string(), Value::Bool(false));
m.insert("setPositionMode".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(false));
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("1min".into()));
m.insert("5m".to_string(), Value::Str("5min".into()));
m.insert("15m".to_string(), Value::Str("15min".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("1w".to_string(), Value::Str("1w".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/f267bf5b-5c6c-45e2-9ce4-fb0af8a9d9ab".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://data-api.hibachi.xyz".into()));
m.insert("private".to_string(), Value::Str("https://api.hibachi.xyz".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://www.hibachi.xyz/".into()));
m.insert("doc".to_string(), Value::Str("https://api-doc.hibachi.xyz/".into()));
m.insert("referral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str("https://hibachi.xyz/r/ZBL2YFWIHU".into()));
m
}));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("market/exchange-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/inventory".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/data/prices".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/data/stats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/data/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/data/klines".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/data/open-interest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/data/orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("market/data/funding-rates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("exchange/utc-timestamp".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("capital/balance".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capital/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capital/deposit-info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/account/info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/account/trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/account/trading_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/account/settlements_history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("put".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("delete".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trade/order".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capital/withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("capital/transfer".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trade/account/leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
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(false));
m.insert("accountId".to_string(), Value::Bool(true));
m.insert("privateKey".to_string(), Value::Bool(true));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.00015".into()), &[]));
m.insert("taker".to_string(), self.parse_number(Value::Str("0.00045".into()), &[]));
m
}));
m
}));
m.insert("currencies".to_string(), self.hardcoded_currencies());
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("triggerDirection".to_string(), Value::Null);
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("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(false));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Null);
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Null);
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(false));
m
}));
m.insert("fetchOrders".to_string(), Value::Null);
m.insert("fetchClosedOrders".to_string(), Value::Null);
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Null);
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m.insert("inverse".to_string(), Value::Null);
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m.insert("inverse".to_string(), Value::Null);
m
}));
m
}));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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("2".to_string(), Value::Str("BadRequest".into()).clone());
m.insert("3".to_string(), Value::Str("OrderNotFound".into()).clone());
m.insert("4".to_string(), Value::Str("BadRequest".into()).clone());
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m
})]);
Value::Null
}
pub fn get_account_id(&self) -> Value {
self.check_required_credentials(&[]);
let mut id: Value = self.parse_to_int(self.accountId.clone());
return id;
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
let mut marketId: Value = self.safe_string_k(market.clone(), "symbol", &[]);
let mut numericId: Value = self.safe_number_k(market.clone(), "id", &[]);
let mut marketType: Value = Value::Str("swap".into());
let mut baseId: Value = self.safe_string_k(market.clone(), "underlyingSymbol", &[]);
let mut quoteId: Value = self.safe_string_k(market.clone(), "settlementSymbol", &[]);
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (base == Value::Null) || (quote == Value::Null) {
return Value::Null;
}
let mut settleId: Value = self.safe_string_k(market.clone(), "settlementSymbol", &[]);
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into()), Value::Str(":".into())).into()), settle).into());
let mut created: Value = self.safe_integer_product_k(market.clone(), "marketCreationTimestamp", Value::Int(1000), &[]);
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId);
m.insert("numericId".to_string(), numericId);
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId);
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), marketType);
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("active".to_string(), Value::Bool(self.safe_string_k(market.clone(), "status", &[]).as_str() == Some("LIVE")));
m.insert("contract".to_string(), Value::Bool(true));
m.insert("linear".to_string(), Value::Bool(true));
m.insert("inverse".to_string(), Value::Bool(false));
m.insert("contractSize".to_string(), self.parse_number(Value::Str("1".into()), &[]));
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(self.parse_precision(&[self.safe_string_k(market.clone(), "underlyingDecimals", &[])]), &[]));
m.insert("price".to_string(), (match ((self.parse_number(self.safe_value(self.safe_list_k(market.clone(), "orderbookGranularities", &[Value::from(vec![])]), Value::Int(0), &[]), &[])).as_f64(), (Value::Int(10000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.safe_number_k(market.clone(), "minNotional", &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), created);
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
/*
* @method
* @name hibachi#fetchMarkets
* @description retrieves data on all markets for hibachi
* @see https://api-doc.hibachi.xyz/#183981da-8df5-40a0-a155-da15015dd536
* @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_exchange_info(&[params]).await;
// {
// "displayName": "ETH/USDT Perps",
// "id": 1,
// "maintenanceFactorForPositions": "0.030000",
// "marketCloseTimestamp": null,
// "marketOpenTimestamp": null,
// "minNotional": "1",
// "minOrderSize": "0.000000001",
// "orderbookGranularities": [
// "0.01",
// "0.1",
// "1",
// "10"
// ],
// "riskFactorForOrders": "0.066667",
// "riskFactorForPositions": "0.030000",
// "settlementDecimals": 6,
// "settlementSymbol": "USDT",
// "status": "LIVE",
// "stepSize": "0.000000001",
// "symbol": "ETH/USDT-P",
// "tickSize": "0.000001",
// "underlyingDecimals": 9,
// "underlyingSymbol": "ETH"
// },
let mut rows: Value = self.safe_list_k(response, "futureContracts", &[]);
return self.parse_markets(rows);
Value::Null
}
pub fn hardcoded_currencies(&self) -> Value {
// Hibachi only supports USDT on Arbitrum at this time
// We don't have an API endpoint to expose this information yet
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut networks: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut networkId: Value = Value::Str("ARBITRUM".into());
if let Value::Dict(__d) = &mut networks { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&networkId), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), networkId.clone());
m.insert("network".to_string(), networkId.clone());
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), Value::Null);
m.insert("withdraw".to_string(), Value::Null);
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
})); }
let mut code: Value = self.safe_currency_code(Value::Str("USDT".into()), &[]);
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("USDT".into()));
m.insert("name".to_string(), Value::Str("USDT".into()));
m.insert("type".to_string(), Value::Str("fiat".into()));
m.insert("code".to_string(), code.clone());
m.insert("precision".to_string(), self.parse_number(Value::Str("0.000001".into()), &[]));
m.insert("active".to_string(), Value::Bool(true));
m.insert("fee".to_string(), Value::Null);
m.insert("networks".to_string(), networks);
m.insert("deposit".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}))); }
}
return result;
Value::Null
}
pub fn parse_balance(&self, mut response: Value) -> Value {
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
// Hibachi only supports USDT on Arbitrum at this time
let mut code: Value = self.safe_currency_code(Value::Str("USDT".into()), &[]);
let mut account: Value = self.account();
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("total".into(), self.safe_string_k(response.clone(), "balance", &[])); }
if let Value::Dict(__d) = &mut account { std::sync::Arc::make_mut(__d).insert("free".into(), self.safe_string_k(response, "maximalWithdraw", &[])); }
if (code != Value::Null) {
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&code), account); }
}
return self.safe_balance(result);
Value::Null
}
/*
* @method
* @name hibachi#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://api-doc.hibachi.xyz/#69aafedb-8274-4e21-bbaf-91dace8b8f31
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
*/
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m
});
let __ws_arg_0 = self.extend(request, &[params]);
let mut response: Value = self.private_get_trade_account_info(&[__ws_arg_0]).await;
return self.parse_balance(response);
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut prices: Value = self.safe_dict_k(ticker.clone(), "prices", &[]);
let mut stats: Value = self.safe_dict_k(ticker.clone(), "stats", &[]);
let mut bid: Value = self.safe_number_k(prices.clone(), "bidPrice", &[]);
let mut ask: Value = self.safe_number_k(prices.clone(), "askPrice", &[]);
let mut last: Value = self.safe_number_k(prices, "tradePrice", &[]);
let mut high: Value = self.safe_number_k(stats.clone(), "high24h", &[]);
let mut low: Value = self.safe_number_k(stats.clone(), "low24h", &[]);
let mut volume: Value = self.safe_number_k(stats, "volume24h", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("bid".to_string(), bid);
m.insert("ask".to_string(), ask);
m.insert("last".to_string(), last.clone());
m.insert("high".to_string(), high);
m.insert("low".to_string(), low);
m.insert("bidVolume".to_string(), Value::Null);
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".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(), Value::Null);
m.insert("quoteVolume".to_string(), volume);
m.insert("info".to_string(), ticker);
m
}), &[market]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
// public fetchTrades:
// {
// "price": "3512.431902",
// "quantity": "1.414780098",
// "takerSide": "Buy",
// "timestamp": 1712692147
// }
//
// private fetchMyTrades:
// {
// "askAccountId": 221,
// "askOrderId": 589168494921909200,
// "bidAccountId": 132,
// "bidOrderId": 589168494829895700,
// "fee": "0.000477",
// "id": 199511136,
// "orderType": "MARKET",
// "price": "119257.90000",
// "quantity": "0.0000200000",
// "realizedPnl": "-0.000352",
// "side": "Sell",
// "symbol": "BTC/USDT-P",
// "timestamp": 1752543391
// }
let mut marketId: Value = self.safe_string_k(trade.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut id: Value = self.safe_string_k(trade.clone(), "id", &[]);
let mut price: Value = self.safe_string_k(trade.clone(), "price", &[]);
let mut amount: Value = self.safe_string_k(trade.clone(), "quantity", &[]);
let mut timestamp: Value = self.safe_integer_product_k(trade.clone(), "timestamp", Value::Int(1000), &[]);
let mut cost: Value = crate::precise::Precise::stringMul(&price, &amount);
let mut side: Value = Value::Null;
let mut fee: Value = Value::Null;
let mut orderType: Value = Value::Null;
let mut orderId: Value = Value::Null;
let mut takerOrMaker: Value = Value::Null;
if (id == Value::Null) {
// public trades
side = self.safe_string_lower_k(trade.clone(), "takerSide", &[]);
takerOrMaker = Value::Str("taker".into());
} else {
// private trades
side = self.safe_string_lower_k(trade.clone(), "side", &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), self.safe_string_k(trade.clone(), "fee", &[]));
m.insert("currency".to_string(), Value::Str("USDT".into()));
m
});
orderType = self.safe_string_lower_k(trade.clone(), "orderType", &[]);
if (side.as_str() == Some("buy")) {
orderId = self.safe_string_k(trade.clone(), "bidOrderId", &[]);
} else {
orderId = self.safe_string_k(trade.clone(), "askOrderId", &[]);
}
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("symbol".to_string(), symbol);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("cost".to_string(), cost);
m.insert("order".to_string(), orderId);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("type".to_string(), orderType);
m.insert("fee".to_string(), fee);
m.insert("info".to_string(), trade);
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name hibachi#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://api-doc.hibachi.xyz/#86a53bc1-d3bb-4b93-8a11-7034d4698caa
* @param {string} symbol unified market symbol
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch (maximum value is 100)
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of recent [trade structures]
*/
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut 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_1 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_data_trades(&[__ws_arg_1]).await;
//
// {
// "trades": [
// {
// "price": "111091.38352",
// "quantity": "0.0090090093",
// "takerSide": "Buy",
// "timestamp": 1752095479
// },
// ]
// }
//
let mut trades: Value = self.safe_list_k(response, "trades", &[Value::from(vec![])]);
let mut tradesList: Value = Value::from(vec![]);
if (trades != Value::Null) {
tradesList = trades;
}
return self.parse_trades(tradesList, &[market]);
Value::Null
}
/*
* @method
* @name hibachi#fetchTicker
* @see https://api-doc.hibachi.xyz/#bca696ca-b9b2-4072-8864-5d6b8c09807e
* @see https://api-doc.hibachi.xyz/#0064ca53-a2d0-41b9-8ade-6b2abf4ccb12
* @description fetches a price ticker and the related information for the past 24h
* @param {string} symbol unified symbol of the market
* @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("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.clone(), &[params.clone()]);
let mut rawPromises: Value = Value::from(vec![self.public_get_market_data_prices(&[__ws_arg_2]).await, self.public_get_market_data_stats(&[self.extend(request, &[params])]).await]);
let mut promises: Value = promise_all(&rawPromises).await;
let mut pricesResponse: Value = promises.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
// {
// "askPrice": "3514.650296",
// "bidPrice": "3513.596112",
// "fundingRateEstimation": {
// "estimatedFundingRate": "0.000001",
// "nextFundingTimestamp": 1712707200
// },
// "markPrice": "3514.288858",
// "spotPrice": "3514.715000",
// "symbol": "ETH/USDT-P",
// "tradePrice": "2372.746570"
// }
let mut statsResponse: Value = promises.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
// {
// "high24h": "3819.507827",
// "low24h": "3754.474162",
// "symbol": "ETH/USDT-P",
// "volume24h": "23554.858590416"
// }
let mut ticker: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("prices".to_string(), pricesResponse);
m.insert("stats".to_string(), statsResponse);
m
});
return self.parse_ticker(ticker, &[market]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
let mut uppercaseStatus: Value = (if (status == Value::Null) { Value::Null } else { to_upper(&status) });
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("PENDING".to_string(), Value::Str("open".into()));
m.insert("CHILD_PENDING".to_string(), Value::Str("open".into()));
m.insert("SCHEDULED_TWAP".to_string(), Value::Str("open".into()));
m.insert("PLACED".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("CANCELLED".to_string(), Value::Str("canceled".into()));
m.insert("PARTIAL_CANCELLED".to_string(), Value::Str("canceled".into()));
m.insert("REJECTED".to_string(), Value::Str("rejected".into()));
m
});
return self.safe_string(statuses, uppercaseStatus, &[status]).as_str().map(str::to_owned);
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Value = self.safe_string_k(order.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut status: Value = self.safe_string_k(order.clone(), "status", &[]);
let mut type_var: Value = self.safe_string_lower_k(order.clone(), "orderType", &[]);
let mut price: Value = self.safe_string2(order.clone(), Value::Str("price".into()), Value::Str("avgFillPrice".into()), &[]);
let mut rawSide: Option<String> = self.safe_string_k(order.clone(), "side", &[]).as_str().map(str::to_owned);
let mut side: Value = Value::Null;
if (rawSide.as_deref() == Some("BID")) {
side = Value::Str("buy".into());
} else if (rawSide.as_deref() == Some("ASK")) {
side = Value::Str("sell".into());
}
let mut amount: Value = self.safe_string_k(order.clone(), "totalQuantity", &[]);
let mut remaining: Value = self.safe_string_k(order.clone(), "availableQuantity", &[]);
let mut totalQuantity: Value = self.safe_string_k(order.clone(), "totalQuantity", &[]);
let mut availableQuantity: Value = self.safe_string_k(order.clone(), "availableQuantity", &[]);
let mut filled: Value = self.safe_string_k(order.clone(), "filledQuantity", &[]);
if (totalQuantity != Value::Null) && (availableQuantity != Value::Null) {
filled = crate::precise::Precise::stringSub(&totalQuantity, &availableQuantity);
}
let mut remainingString: Value = remaining;
if (remainingString == Value::Null) && (totalQuantity != Value::Null) && (filled != Value::Null) {
remainingString = crate::precise::Precise::stringSub(&totalQuantity, &filled);
}
let mut timeInForce: Value = Value::Str("GTC".into());
let mut orderFlags: Option<String> = self.safe_string_k(order.clone(), "orderFlags", &[]).as_str().map(str::to_owned);
let mut postOnly: Value = Value::Bool(false);
let mut reduceOnly: Value = Value::Bool(false);
if (orderFlags.as_deref() == Some("POST_ONLY")) {
timeInForce = Value::Str("PO".into());
postOnly = Value::Bool(true);
} else if (orderFlags.as_deref() == Some("IOC")) {
timeInForce = Value::Str("IOC".into());
} else if (orderFlags.as_deref() == Some("REDUCE_ONLY")) {
reduceOnly = Value::Bool(true);
}
let mut timestamp: Value = self.safe_integer_k(order.clone(), "createdAt", &[]);
if (timestamp == Value::Null) {
timestamp = self.safe_integer_product_k(order.clone(), "creationTime", Value::Int(1000), &[]);
}
let mut lastUpdateTimestamp: Value = self.safe_integer_k(order.clone(), "closedAt", &[]);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string_k(order.clone(), "orderId", &[]));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
m.insert("timestamp".to_string(), timestamp);
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), lastUpdateTimestamp);
m.insert("status".to_string(), self.parse_order_status(status).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), type_var);
m.insert("timeInForce".to_string(), timeInForce);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("average".to_string(), self.safe_string_k(order.clone(), "avgFillPrice", &[]));
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), remainingString);
m.insert("cost".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), reduceOnly);
m.insert("postOnly".to_string(), postOnly);
m.insert("triggerPrice".to_string(), self.safe_number_k(order, "triggerPrice", &[]));
m
}), &[marketResolved]);
Value::Null
}
/*
* @method
* @name hibachi#fetchOrder
* @description fetches information on an order made by the user
* @see https://api-doc.hibachi.xyz/#096a8854-b918-4de8-8731-b2a28d26b96d
* @param {string} id the 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
* @returns {object} An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut 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("orderId".to_string(), id);
m.insert("accountId".to_string(), self.get_account_id());
m
});
let __ws_arg_3 = self.extend(request, &[params]);
let mut response: Value = self.private_get_trade_order(&[__ws_arg_3]).await;
return self.parse_order(response, &[market]);
Value::Null
}
/*
* @method
* @name hibachi#fetchTradingFees
* @description fetch the trading fee
* @see https://api-doc.hibachi.xyz/#69aafedb-8274-4e21-bbaf-91dace8b8f31
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a map of market symbols to [fee structures]{@link https://docs.ccxt.com/?id=fee-structure}
*/
pub async fn fetch_trading_fees(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m
});
let __ws_arg_4 = self.extend(request, &[params]);
let mut response: Value = self.private_get_trade_account_info(&[__ws_arg_4]).await;
// {
// "tradeMakerFeeRate": "0.00000000",
// "tradeTakerFeeRate": "0.00020000"
// },
let mut makerFeeRate: Value = self.safe_number_k(response.clone(), "tradeMakerFeeRate", &[]);
let mut takerFeeRate: Value = self.safe_number_k(response.clone(), "tradeTakerFeeRate", &[]);
let mut result: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut symbols: Value = self.symbols.clone();
{
let mut i: Value = Value::Int(0);
let mut __for_first_734: bool = true;
while { if !__for_first_734 { 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_734 = false; i.as_f64().unwrap_or(f64::NAN) < ((symbols.len() as i64) as f64) } {
let mut symbol: Value = symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut result { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&symbol), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("maker".to_string(), makerFeeRate.clone());
m.insert("taker".to_string(), takerFeeRate.clone());
m.insert("percentage".to_string(), Value::Bool(true));
m
})); }
}
}
return result;
Value::Null
}
pub fn order_message(&self, mut market: Value, mut nonce: Value, mut feeRate: 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);
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 sideInternal: Value = Value::Int(0);
if (side.as_str() == Some("sell")) {
sideInternal = Value::Int(0);
} else if (side.as_str() == Some("buy")) {
sideInternal = Value::Int(1);
}
// Converting them to internal representation:
// - Quantity: Internal = External * (10^underlyingDecimals)
// - Price: Internal = External * (2^32) * (10^(settlementDecimals-underlyingDecimals))
// - FeeRate: Internal = External * (10^8)
let mut amountStr: Value = self.amount_to_precision(self.safe_string_k(market.clone(), "symbol", &[]), amount);
let mut feeRateStr: Value = self.number_to_string(feeRate);
let mut info: Value = self.safe_dict_k(market.clone(), "info", &[]);
let mut underlying: Value = Value::Str(format!("{}{}", Value::Str("1e".into()), self.safe_string_k(info.clone(), "underlyingDecimals", &[])).into());
let mut settlement: Value = Value::Str(format!("{}{}", Value::Str("1e".into()), self.safe_string_k(info, "settlementDecimals", &[])).into());
let mut one: Value = Value::Str("1".into());
let mut feeRateFactor: Value = Value::Str("100000000".into()); // 10^8
let mut priceFactor: Value = Value::Str("4294967296".into()); // 2^32
let mut quantityInternal: Value = crate::precise::Precise::stringDivPrec(&crate::precise::Precise::stringMul(&amountStr, &underlying), &one, &Value::Int(0));
let mut feeRateInternal: Value = crate::precise::Precise::stringDivPrec(&crate::precise::Precise::stringMul(&feeRateStr, &feeRateFactor), &one, &Value::Int(0));
// Encoding
let mut nonce16: Value = self.int_to_base16(nonce, &[]);
let mut noncePadded: Value = pad_start(&nonce16, &Value::Int(16), &Value::Str("0".into()));
let mut encodedNonce: Value = self.base16_to_binary(noncePadded, &[]);
let mut numericId: Value = self.int_to_base16(self.safe_integer_k(market.clone(), "numericId", &[]), &[]);
let mut numericIdPadded: Value = pad_start(&numericId, &Value::Int(8), &Value::Str("0".into()));
let mut encodedMarketId: Value = self.base16_to_binary(numericIdPadded, &[]);
let mut quantity16: Value = self.int_to_base16(self.parse_to_int(quantityInternal), &[]);
let mut quantityPadded: Value = pad_start(&quantity16, &Value::Int(16), &Value::Str("0".into()));
let mut encodedQuantity: Value = self.base16_to_binary(quantityPadded, &[]);
let mut sideInternal16: Value = self.int_to_base16(sideInternal, &[]);
let mut sidePadded: Value = pad_start(&sideInternal16, &Value::Int(8), &Value::Str("0".into()));
let mut encodedSide: Value = self.base16_to_binary(sidePadded, &[]);
let mut feeRateInternal16: Value = self.int_to_base16(self.parse_to_int(feeRateInternal), &[]);
let mut feeRatePadded: Value = pad_start(&feeRateInternal16, &Value::Int(16), &Value::Str("0".into()));
let mut encodedFeeRate: Value = self.base16_to_binary(feeRatePadded, &[]);
let mut encodedPrice: Value = self.binary_concat(Value::Null, &[]);
if (type_var.as_str() == Some("limit")) {
let mut priceStr: Value = self.price_to_precision(self.safe_string_k(market, "symbol", &[]), price);
let mut priceInternal: Value = crate::precise::Precise::stringDivPrec(&crate::precise::Precise::stringDiv(&crate::precise::Precise::stringMul(&crate::precise::Precise::stringMul(&priceStr, &priceFactor), &settlement), &underlying), &one, &Value::Int(0));
let mut price16: Value = self.int_to_base16(self.parse_to_int(priceInternal), &[]);
let mut pricePadded: Value = pad_start(&price16, &Value::Int(16), &Value::Str("0".into()));
// @ts-expect-error
encodedPrice = self.base16_to_binary(pricePadded, &[]);
}
let mut message: Value = self.binary_concat(encodedNonce, &[encodedMarketId, encodedQuantity, encodedSide, encodedPrice, encodedFeeRate]);
return message;
Value::Null
}
pub fn create_order_request(&self, mut nonce: Value, 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 takerFee: Value = self.safe_number_k(market.clone(), "taker", &[self.safe_number(self.options.clone(), Value::Str("defaultTakerFee".into()), &[Value::Float(0.00045)])]);
let mut makerFee: Value = self.safe_number_k(market.clone(), "maker", &[self.safe_number(self.options.clone(), Value::Str("defaultMakerFee".into()), &[Value::Float(0.00015)])]);
let mut takerFeeValue: Value = (if (takerFee == Value::Null) { Value::Int(0) } else { takerFee });
let mut makerFeeValue: Value = (if (makerFee == Value::Null) { Value::Int(0) } else { makerFee });
let mut feeRate: Value = crate::runtime::Math::max(&takerFeeValue, &makerFeeValue);
let mut sideInternal: Value = Value::Str("".into());
if (side.as_str() == Some("sell")) {
sideInternal = Value::Str("ASK".into());
} else if (side.as_str() == Some("buy")) {
sideInternal = Value::Str("BID".into());
}
let mut priceInternal: Value = Value::Str("".into());
if (price != Value::Null) && (price.as_f64() != Some(0.0)) {
priceInternal = self.price_to_precision(symbol.clone(), price.clone());
}
let mut message: Value = self.order_message(market.clone(), nonce.clone(), feeRate.clone(), type_var.clone(), side, amount.clone(), &[price]);
let mut signature: Value = self.sign_message(message, self.privateKey.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_string_k(market, "id", &[]));
m.insert("nonce".to_string(), nonce);
m.insert("side".to_string(), sideInternal);
m.insert("orderType".to_string(), to_upper(&type_var));
m.insert("quantity".to_string(), self.amount_to_precision(symbol, amount));
m.insert("price".to_string(), priceInternal);
m.insert("signature".to_string(), signature);
m.insert("maxFeesPercent".to_string(), self.number_to_string(feeRate));
m
});
let mut postOnly: Value = self.is_post_only(Value::Bool(to_upper(&type_var).as_str() == Some("MARKET")), Value::Null, &[params.clone()]);
let mut reduceOnly: Value = self.safe_bool2(params.clone(), Value::Str("reduceOnly".into()), Value::Str("reduce_only".into()), &[]);
let mut timeInForce: Option<String> = self.safe_string_lower_k(params.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
let mut triggerPrice: Value = self.safe_string2(params.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
if is_true(&postOnly) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderFlags".into(), Value::Str("POST_ONLY".into())); }
} else if (timeInForce.as_deref() == Some("ioc")) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderFlags".into(), Value::Str("IOC".into())); }
} else if (reduceOnly.as_bool() == Some(true)) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("orderFlags".into(), Value::Str("REDUCE_ONLY".into())); }
}
if (triggerPrice != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("triggerPrice".into(), triggerPrice); }
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("reduceOnly".into()), Value::Str("reduce_only".into()), Value::Str("postOnly".into()), Value::Str("timeInForce".into()), Value::Str("stopPrice".into()), Value::Str("triggerPrice".into())]), &[]);
return self.extend(request, &[paramsOmitted]);
Value::Null
}
/*
* @method
* @name hibachi#createOrder
* @description create a trade order
* @see https://api-doc.hibachi.xyz/#00f6d5ad-5275-41cb-a1a8-19ed5d142124
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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 nonce: Value = self.incrementing_nonce();
let mut request: Value = self.create_order_request(nonce, symbol, type_var, side, amount, &[price, params]);
add_element_to_object(&mut request, &Value::Str("accountId".into()), self.get_account_id());
let mut response: Value = self.private_post_trade_order(&[request]).await;
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(response, "orderId", &[]));
m.insert("status".to_string(), Value::Str("pending".into()));
m
}), &[]);
Value::Null
}
/*
* @method
* @name hibachi#createOrders
* @description *contract only* create a list of trade orders
* @see https://api-doc.hibachi.xyz/#c2840b9b-f02c-44ed-937d-dc2819f135b4
* @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 nonce: Value = self.incrementing_nonce();
let mut requestOrders: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_735: bool = true;
while { if !__for_first_735 { 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_735 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut symbol: 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_number_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_number_k(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderRequest: Value = self.create_order_request((match (&(nonce), &(i)) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }), symbol, type_var, side, amount, &[price, orderParams]);
add_element_to_object(&mut orderRequest, &Value::Str("action".into()), Value::Str("place".into()));
append_to_array(&mut requestOrders, orderRequest);
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m.insert("orders".to_string(), requestOrders);
m
});
let __ws_arg_5 = self.extend(request, &[params]);
let mut response: Value = self.private_post_trade_orders(&[__ws_arg_5]).await;
//
// { "orders": [ { nonce: '1754349993908', orderId: '589642085255349248' } ] }
//
let mut ret: Value = Value::from(vec![]);
let mut responseOrders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_736: bool = true;
while { if !__for_first_736 { 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_736 = false; i.as_f64().unwrap_or(f64::NAN) < ((responseOrders.len() as i64) as f64) } {
let mut responseOrder: Value = responseOrders.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);
append_to_array(&mut ret, self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), responseOrder.clone());
m.insert("id".to_string(), self.safe_string_k(responseOrder, "orderId", &[]));
m.insert("status".to_string(), Value::Str("pending".into()));
m
}), &[]));
}
}
return ret;
Value::Null
}
pub fn edit_order_request(&self, mut nonce: Value, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (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 takerFee: Value = self.safe_number_k(market.clone(), "taker", &[Value::Int(0)]);
let mut makerFee: Value = self.safe_number_k(market.clone(), "maker", &[Value::Int(0)]);
let mut takerFeeValue: Value = (if (takerFee == Value::Null) { Value::Int(0) } else { takerFee });
let mut makerFeeValue: Value = (if (makerFee == Value::Null) { Value::Int(0) } else { makerFee });
let mut feeRate: Value = crate::runtime::Math::max(&takerFeeValue, &makerFeeValue);
let mut message: Value = self.order_message(market, nonce.clone(), feeRate.clone(), type_var, side, amount.clone(), &[price.clone()]);
let mut signature: Value = self.sign_message(message, self.privateKey.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id);
m.insert("nonce".to_string(), nonce);
m.insert("updatedQuantity".to_string(), self.amount_to_precision(symbol.clone(), amount));
m.insert("updatedPrice".to_string(), self.price_to_precision(symbol, price));
m.insert("maxFeesPercent".to_string(), self.number_to_string(feeRate));
m.insert("signature".to_string(), signature);
m
});
return self.extend(request, &[params]);
Value::Null
}
/*
* @method
* @name hibachi#editOrder
* @description edit a limit order that is not matched
* @see https://api-doc.hibachi.xyz/#94d2cdaf-1c71-440f-a981-da1112824810
* @param {string} id order id
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type must be 'limit'
* @param {string} side 'buy' or 'sell', should stay the same with original side
* @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
* @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 edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut nonce: Value = self.incrementing_nonce();
let mut request: Value = self.edit_order_request(nonce, id.clone(), symbol, type_var, side, &[amount, price, params]);
add_element_to_object(&mut request, &Value::Str("accountId".into()), self.get_account_id());
self.private_put_trade_order(&[request]).await;
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id);
m.insert("status".to_string(), Value::Str("pending".into()));
m
}), &[]);
Value::Null
}
/*
* @method
* @name hibachi#editOrders
* @description edit a list of trade orders
* @see https://api-doc.hibachi.xyz/#c2840b9b-f02c-44ed-937d-dc2819f135b4
* @param {Array} orders list of orders to edit, each object should contain the parameters required by editOrder, namely id, 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 edit_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 nonce: Value = self.incrementing_nonce();
let mut requestOrders: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_737: bool = true;
while { if !__for_first_737 { 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_737 = false; i.as_f64().unwrap_or(f64::NAN) < ((orders.len() as i64) as f64) } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut id: Value = self.safe_string_k(rawOrder.clone(), "id", &[]);
let mut symbol: 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_number_k(rawOrder.clone(), "amount", &[]);
let mut price: Value = self.safe_number_k(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderRequest: Value = self.edit_order_request((match (&(nonce), &(i)) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }), id, symbol, type_var, side, &[amount, price, orderParams]);
add_element_to_object(&mut orderRequest, &Value::Str("action".into()), Value::Str("modify".into()));
append_to_array(&mut requestOrders, orderRequest);
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m.insert("orders".to_string(), requestOrders);
m
});
let __ws_arg_6 = self.extend(request, &[params]);
let mut response: Value = self.private_post_trade_orders(&[__ws_arg_6]).await;
//
// { "orders": [ { "orderId": "589636801329628160" } ] }
//
let mut ret: Value = Value::from(vec![]);
let mut responseOrders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_738: bool = true;
while { if !__for_first_738 { 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_738 = false; i.as_f64().unwrap_or(f64::NAN) < ((responseOrders.len() as i64) as f64) } {
let mut responseOrder: Value = responseOrders.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);
append_to_array(&mut ret, self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), responseOrder.clone());
m.insert("id".to_string(), self.safe_string_k(responseOrder, "orderId", &[]));
m.insert("status".to_string(), Value::Str("pending".into()));
m
}), &[]));
}
}
return ret;
Value::Null
}
pub fn cancel_order_request(&self, mut id: Value) -> Value {
let mut bigid: Value = self.convert_to_big_int(id.clone());
let mut idbase16: Value = self.int_to_base16(bigid, &[]);
let mut idPadded: Value = pad_start(&idbase16, &Value::Int(16), &Value::Str("0".into()));
let mut message: Value = self.base16_to_binary(idPadded, &[]);
let mut signature: Value = self.sign_message(message, self.privateKey.clone());
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderId".to_string(), id);
m.insert("signature".to_string(), signature);
m
});
Value::Null
}
/*
* @method
* @name hibachi#cancelOrder
* @see https://api-doc.hibachi.xyz/#e99c4f48-e610-4b7c-b7f6-1b4bb7af0271
* @description cancels an open order
* @param {string} id order id
* @param {string} symbol is unused
* @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 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
}));
let mut request: Value = self.cancel_order_request(id.clone());
add_element_to_object(&mut request, &Value::Str("accountId".into()), self.get_account_id());
let __ws_arg_7 = self.extend(request, &[params]);
let mut response: Value = self.private_delete_trade_order(&[__ws_arg_7]).await;
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m.insert("id".to_string(), id);
m.insert("status".to_string(), Value::Str("canceled".into()));
m
}), &[]);
Value::Null
}
/*
* @method
* @name hibachi#cancelOrders
* @description cancel multiple orders
* @see https://api-doc.hibachi.xyz/#c2840b9b-f02c-44ed-937d-dc2819f135b4
* @param {string[]} ids order ids
* @param {string} [symbol] unified market symbol, unused
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut orders: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_739: bool = true;
while { if !__for_first_739 { 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_739 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
let mut orderRequest: Value = self.cancel_order_request(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));
add_element_to_object(&mut orderRequest, &Value::Str("action".into()), Value::Str("cancel".into()));
append_to_array(&mut orders, orderRequest);
}
}
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m.insert("orders".to_string(), orders);
m
});
let __ws_arg_8 = self.extend(request, &[params]);
let mut response: Value = self.private_post_trade_orders(&[__ws_arg_8]).await;
//
// { "orders": [ { "orderId": "589636801329628160" } ] }
//
let mut ret: Value = Value::from(vec![]);
let mut responseOrders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_740: bool = true;
while { if !__for_first_740 { 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_740 = false; i.as_f64().unwrap_or(f64::NAN) < ((responseOrders.len() as i64) as f64) } {
let mut responseOrder: Value = responseOrders.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);
append_to_array(&mut ret, self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), responseOrder.clone());
m.insert("id".to_string(), self.safe_string_k(responseOrder, "orderId", &[]));
m.insert("status".to_string(), Value::Str("canceled".into()));
m
}), &[]));
}
}
return ret;
Value::Null
}
/*
* @method
* @name hibachi#cancelAllOrders
* @see https://api-doc.hibachi.xyz/#8ed24695-016e-49b2-a72d-7511ca921fee
* @description cancel all open orders in a market
* @param {string} [symbol] unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut nonce: Value = self.incrementing_nonce();
let mut nonce16: Value = self.int_to_base16(nonce.clone(), &[]);
let mut noncePadded: Value = pad_start(&nonce16, &Value::Int(16), &Value::Str("0".into()));
let mut message: Value = self.base16_to_binary(noncePadded, &[]);
let mut signature: Value = self.sign_message(message, self.privateKey.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (symbol != Value::Null) {
let mut market: Value = self.market(symbol);
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("contractId".into(), self.safe_integer_k(market, "numericId", &[])); }
}
let __ws_arg_9 = self.extend(request, &[params]);
let mut response: Value = self.private_delete_trade_orders(&[__ws_arg_9]).await;
return Value::from(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[])]);
Value::Null
}
pub fn encode_withdraw_message(&self, mut amount: Value, mut maxFees: Value, mut address: Value) -> Value {
// Converting them to internal representation:
// - Quantity: Internal = External * (10^6)
// - maxFees: Internal = External * (10^6)
// We only have USDT as our currency as this time
let mut USDTAssetId: Value = Value::Int(1);
let mut USDTFactor: Value = Value::Str("1000000".into());
let mut amountStr: Value = self.number_to_string(amount);
let mut maxFeesStr: Value = self.number_to_string(maxFees);
let mut one: Value = Value::Str("1".into());
let mut quantityInternal: Value = crate::precise::Precise::stringDivPrec(&crate::precise::Precise::stringMul(&amountStr, &USDTFactor), &one, &Value::Int(0));
let mut maxFeesInternal: Value = crate::precise::Precise::stringDivPrec(&crate::precise::Precise::stringMul(&maxFeesStr, &USDTFactor), &one, &Value::Int(0));
// Encoding
let mut usdtAsset16: Value = self.int_to_base16(USDTAssetId, &[]);
let mut usdtAssetPadded: Value = pad_start(&usdtAsset16, &Value::Int(8), &Value::Str("0".into()));
let mut encodedAssetId: Value = self.base16_to_binary(usdtAssetPadded, &[]);
let mut quantity16: Value = self.int_to_base16(self.parse_to_int(quantityInternal), &[]);
let mut quantityPadded: Value = pad_start(&quantity16, &Value::Int(16), &Value::Str("0".into()));
let mut encodedQuantity: Value = self.base16_to_binary(quantityPadded, &[]);
let mut maxFees16: Value = self.int_to_base16(self.parse_to_int(maxFeesInternal), &[]);
let mut maxFeesPadded: Value = pad_start(&maxFees16, &Value::Int(16), &Value::Str("0".into()));
let mut encodedMaxFees: Value = self.base16_to_binary(maxFeesPadded, &[]);
let mut encodedAddress: Value = self.base16_to_binary(address, &[]);
let mut message: Value = self.binary_concat(encodedAssetId, &[encodedQuantity, encodedMaxFees, encodedAddress]);
return message;
Value::Null
}
/*
* @method
* @name hibachi#withdraw
* @description make a withdrawal
* @see https://api-doc.hibachi.xyz/#6421625d-3e45-45fa-be9b-d2a0e780c090
* @param {string} code unified currency code, only support USDT
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.tag] memo / destination tag, required for currencies in options['withdrawTagRequiredCurrencies']
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut withdrawAddress: Value = address.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 40).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
// Get the withdraw fees
let mut exchangeInfo: Value = self.public_get_market_exchange_info(&[params.clone()]).await;
// {
// "feeConfig": {
// "depositFees": "0.004518",
// "tradeMakerFeeRate": "0.00000000",
// "tradeTakerFeeRate": "0.00020000",
// "transferFeeRate": "0.00010000",
// "withdrawalFees": "0.012050"
// },
// }
let mut feeConfig: Value = self.safe_dict_k(exchangeInfo, "feeConfig", &[]);
let mut maxFees: Value = self.safe_number_k(feeConfig, "withdrawalFees", &[]);
// Generate the signature
let mut message: Value = self.encode_withdraw_message(amount.clone(), maxFees.clone(), withdrawAddress.clone());
let mut signature: Value = self.sign_message(message, self.privateKey.clone());
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m.insert("coin".to_string(), Value::Str("USDT".into()));
m.insert("network".to_string(), Value::Str("ARBITRUM".into()));
m.insert("withdrawAddress".to_string(), withdrawAddress.clone());
m.insert("selfWithdrawal".to_string(), Value::Bool(false));
m.insert("quantity".to_string(), self.number_to_string(amount.clone()));
m.insert("maxFees".to_string(), self.number_to_string(maxFees.clone()));
m.insert("signature".to_string(), signature);
m
});
let __ws_arg_10 = self.extend(request, &[params]);
self.private_post_capital_withdraw(&[__ws_arg_10]).await;
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), Value::Null);
m.insert("id".to_string(), Value::Null);
m.insert("txid".to_string(), Value::Null);
m.insert("timestamp".to_string(), self.milliseconds());
m.insert("datetime".to_string(), Value::Null);
m.insert("address".to_string(), Value::Null);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("addressTo".to_string(), withdrawAddress);
m.insert("tag".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("withdrawal".into()));
m.insert("amount".to_string(), amount);
m.insert("currency".to_string(), code);
m.insert("status".to_string(), Value::Str("pending".into()));
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDT".into()));
m.insert("cost".to_string(), maxFees);
m
}));
m.insert("network".to_string(), Value::Str("ARBITRUM".into()));
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("internal".to_string(), Value::Null);
m
});
Value::Null
}
pub fn nonce(&self) -> Value {
return self.milliseconds();
Value::Null
}
pub fn sign_message(&self, mut message: Value, mut privateKey: Value) -> Value {
if (Value::Int(privateKey.len() as i64).as_f64() == Some(44.0)) {
return self.hmac(message.clone(), self.encode(privateKey.clone()), Value::Str("sha256".into()), &[Value::Str("hex".into())]);
} else {
// For Trustless account, the key length is 66 including '0x' and we use ECDSA to sign the message
let mut hash: Value = self.hash(message, Value::Str("sha256".into()), &[Value::Str("hex".into())]);
let mut signature: Value = ecdsa(hash.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null), privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null), Value::Str("secp256k1".into()), Value::Null);
let mut r: Value = signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null);
let mut s: Value = signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null);
let mut v: Value = self.int_to_base16(signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null), &[]);
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", pad_start(&r, &Value::Int(64), &Value::Str("0".into())), pad_start(&s, &Value::Int(64), &Value::Str("0".into()))).into()), pad_start(&v, &Value::Int(2), &Value::Str("0".into()))).into());
}
Value::Null
}
/*
* @method
* @name hibachi#fetchOrderBook
* @description fetches the state of the open orders on the orderbook
* @see https://api-doc.hibachi.xyz/#c7a64b0d-9e37-4009-93e5-2aa12e8d7e9b
* @param {string} symbol unified symbol of the market
* @param {int} [limit] currently unused
* @param {object} [params] extra parameters to be passed -- see documentation link above
* @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("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_11 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_data_orderbook(&[__ws_arg_11]).await;
let mut formattedResponse: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if let Value::Dict(__d) = &mut formattedResponse { std::sync::Arc::make_mut(__d).insert("ask".into(), self.safe_list(self.safe_dict_k(response.clone(), "ask", &[]), Value::Str("levels".into()), &[])); }
if let Value::Dict(__d) = &mut formattedResponse { std::sync::Arc::make_mut(__d).insert("bid".into(), self.safe_list(self.safe_dict_k(response, "bid", &[]), Value::Str("levels".into()), &[])); }
return self.parse_order_book(formattedResponse, symbol, &[self.milliseconds(), Value::Str("bid".into()), Value::Str("ask".into()), Value::Str("price".into()), Value::Str("quantity".into())]);
Value::Null
}
/*
* @method
* @name hibachi#fetchMyTrades
* @see https://api-doc.hibachi.xyz/#0adbf143-189f-40e0-afdc-88af4cba3c79
* @description fetch all trades made by the user
* @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
* @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 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("accountId".to_string(), self.get_account_id());
m
});
let __ws_arg_12 = self.extend(request, &[params.clone()]);
let mut response: Value = self.private_get_trade_account_trades(&[__ws_arg_12]).await;
//
// {
// "trades": [
// {
// "askAccountId": 221,
// "askOrderId": 589168494921909200,
// "bidAccountId": 132,
// "bidOrderId": 589168494829895700,
// "fee": "0.000477",
// "id": 199511136,
// "orderType": "MARKET",
// "price": "119257.90000",
// "quantity": "0.0000200000",
// "realizedPnl": "-0.000352",
// "side": "Sell",
// "symbol": "BTC/USDT-P",
// "timestamp": 1752543391
// }
// ]
// }
//
let mut trades: Value = self.safe_list_k(response, "trades", &[]);
let mut tradesList: Value = Value::from(vec![]);
if (trades != Value::Null) {
tradesList = trades;
}
return self.parse_trades(tradesList, &[market, since, limit, params]);
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_product_k(ohlcv.clone(), "timestamp", Value::Int(1000), &[]), self.safe_number_k(ohlcv.clone(), "open", &[]), self.safe_number_k(ohlcv.clone(), "high", &[]), self.safe_number_k(ohlcv.clone(), "low", &[]), self.safe_number_k(ohlcv.clone(), "close", &[]), self.safe_number_k(ohlcv, "volumeNotional", &[])]);
Value::Null
}
/*
* @method
* @name hibachi#fetchOpenOrders
* @description fetches all current open orders
* @see https://api-doc.hibachi.xyz/#3243f8a0-086c-44c5-ab8a-71bbb7bab403
* @param {string} [symbol] unified market symbol to filter by
* @param {int} [since] millisecond timestamp of the earliest order
* @param {int} [limit] the maximum number of open orders to return
* @param {object} [params] extra parameters
* @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 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("accountId".to_string(), self.get_account_id());
m
});
let __ws_arg_13 = self.extend(request, &[params]);
let mut response: Value = self.private_get_trade_orders(&[__ws_arg_13]).await;
return self.parse_orders(response, &[market, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name hibachi#fetchOrdersByStatus
* @description fetch orders filtered by terminal status
* @see https://api-doc.hibachi.xyz/#0ca35e79-a80e-4a91-bd32-de3fc2b0b1fa
* @param {string} status exchange specific terminal status
* @param {string} [symbol] unified market symbol to filter by
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters
* @param {int} [params.until] timestamp in ms of the latest order
* @param {string} [params.cursorOrderId] pagination cursor, returns orders with orderId strictly less than this value
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_orders_by_status(&mut self, mut status: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m
});
if (symbol != Value::Null) {
market = self.market(symbol.clone());
}
if (status != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("status".into(), status); }
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), since.clone()); }
}
let mut untilparamsUntilVariable = self.handle_option_integer_and_params(params, Value::Str("fetchOrdersByStatus".into()), Value::Str("until".into()), &[]);
let mut until: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), until); }
}
let __ws_arg_14 = self.extend(request, &[paramsUntil]);
let mut response: Value = self.private_get_trade_orders_history(&[__ws_arg_14]).await;
//
// {
// "hasMore": false,
// "orders": [
// {
// "accountId": 128,
// "avgFillPrice": "2900.000000",
// "closedAt": 1777811627000,
// "createdAt": 1777811620000,
// "filledQuantity": "1.200000000",
// "orderFlags": null,
// "orderId": "596002791293190100",
// "orderType": "MARKET",
// "parentOrderId": null,
// "price": null,
// "side": "BID",
// "sourceType": "regular",
// "status": "Filled",
// "symbol": "ETH/USDT-P",
// "totalQuantity": "1.200000000",
// "triggerDirection": null,
// "triggerPrice": null
// }
// ]
// }
//
let mut orders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
let mut parsedOrders: Value = self.parse_orders(orders, &[market]);
return self.filter_by_symbol_since_limit(parsedOrders, &[symbol, since, limit]);
Value::Null
}
/*
* @method
* @name hibachi#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://api-doc.hibachi.xyz/#0ca35e79-a80e-4a91-bd32-de3fc2b0b1fa
* @param {string} [symbol] unified market symbol of the orders
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of closed order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest order
* @param {string} [params.cursorOrderId] pagination cursor, returns orders with orderId strictly less than this value
* @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
}));
let mut orders: Value = self.fetch_orders_by_status(Value::Str("filled".into()), &[symbol, since.clone(), limit.clone(), params]).await;
let mut filtered: Value = self.filter_by(orders, Value::Str("status".into()), Value::Str("closed".into()), &[]);
return self.filter_by_since_limit(filtered, &[since, limit]);
Value::Null
}
/*
* @method
* @name hibachi#fetchCanceledOrders
* @description fetches information on multiple canceled orders made by the user
* @see https://api-doc.hibachi.xyz/#0ca35e79-a80e-4a91-bd32-de3fc2b0b1fa
* @param {string} [symbol] unified market symbol of the orders
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the maximum number of canceled order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest order
* @param {string} [params.cursorOrderId] pagination cursor, returns orders with orderId strictly less than this value
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
*/
pub async fn fetch_canceled_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut orders: Value = self.fetch_orders_by_status(Value::Null, &[symbol, since.clone(), limit.clone(), params]).await;
let mut filtered: Value = self.filter_by(orders, Value::Str("status".into()), Value::Str("canceled".into()), &[]);
return self.filter_by_since_limit(filtered, &[since, limit]);
Value::Null
}
/*
* @method
* @name hibachi#fetchOHLCV
* @see https://api-doc.hibachi.xyz/#4f0eacec-c61e-4d51-afb3-23c51c2c6bac
* @description fetches historical candlestick data containing the close, high, low, open prices, interval and the volumeNotional
* @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
* @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);
let mut timeframeValue: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
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.insert("interval".to_string(), timeframeValue.clone());
m
});
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("fromMs".into(), since.clone()); }
}
let mut untilparamsUntilVariable = self.handle_option_integer_and_params(params, Value::Str("fetchOHLCV".into()), Value::Str("until".into()), &[]);
let mut until: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("toMs".into(), until); }
}
let __ws_arg_15 = self.extend(request, &[paramsUntil]);
let mut response: Value = self.public_get_market_data_klines(&[__ws_arg_15]).await;
//
// [
// {
// "close": "3704.751036",
// "high": "3716.530378",
// "interval": "1h",
// "low": "3699.627883",
// "open": "3716.406894",
// "timestamp": 1712628000,
// "volumeNotional": "1637355.846362"
// }
// ]
//
let mut klines: Value = self.safe_list_k(response, "klines", &[Value::from(vec![])]);
return self.parse_ohlc_vs(klines, &[market, timeframeValue, since, limit]);
Value::Null
}
/*
* @method
* @name hibachi#fetchPositions
* @description fetch all open positions
* @see https://api-doc.hibachi.xyz/#69aafedb-8274-4e21-bbaf-91dace8b8f31
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/?id=position-structure}
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m
});
let __ws_arg_16 = self.extend(request, &[params]);
let mut response: Value = self.private_get_trade_account_info(&[__ws_arg_16]).await;
//
// {
// "assets": [
// {
// "quantity": "14.130626",
// "symbol": "USDT"
// }
// ],
// "balance": "14.186087",
// "maximalWithdraw": "4.152340",
// "numFreeTransfersRemaining": 96,
// "positions": [
// {
// "direction": "Short",
// "entryNotional": "10.302213",
// "notionalValue": "10.225008",
// "quantity": "0.004310550",
// "symbol": "ETH/USDT-P",
// "unrealizedFundingPnl": "0.000000",
// "unrealizedTradingPnl": "0.077204"
// },
// {
// "direction": "Short",
// "entryNotional": "2.000016",
// "notionalValue": "1.999390",
// "quantity": "0.0000328410",
// "symbol": "BTC/USDT-P",
// "unrealizedFundingPnl": "0.000000",
// "unrealizedTradingPnl": "0.000625"
// },
// {
// "direction": "Short",
// "entryNotional": "2.000015",
// "notionalValue": "2.022384",
// "quantity": "0.01470600",
// "symbol": "SOL/USDT-P",
// "unrealizedFundingPnl": "0.000000",
// "unrealizedTradingPnl": "-0.022369"
// }
// ],
// }
//
let mut data: Value = self.safe_list_k(response, "positions", &[Value::from(vec![])]);
return self.parse_positions(data, &[symbolsNormalized]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "direction": "Short",
// "entryNotional": "10.302213",
// "notionalValue": "10.225008",
// "quantity": "0.004310550",
// "symbol": "ETH/USDT-P",
// "unrealizedFundingPnl": "0.000000",
// "unrealizedTradingPnl": "0.077204"
// }
//
let mut marketId: Value = self.safe_string_k(position.clone(), "symbol", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut side: Value = self.safe_string_lower_k(position.clone(), "direction", &[]);
let mut quantity: Value = self.safe_string_k(position.clone(), "quantity", &[]);
let mut unrealizedFunding: Value = self.safe_string_k(position.clone(), "unrealizedFundingPnl", &[Value::Str("0".into())]);
let mut unrealizedTrading: Value = self.safe_string_k(position.clone(), "unrealizedTradingPnl", &[Value::Str("0".into())]);
let mut unrealizedPnl: Value = crate::precise::Precise::stringAdd(&unrealizedFunding, &unrealizedTrading);
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("entryPrice".to_string(), self.safe_string_k(position.clone(), "average_entry_price", &[]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("notional".to_string(), self.safe_string_k(position, "notionalValue", &[]));
m.insert("collateral".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), unrealizedPnl);
m.insert("side".to_string(), side);
m.insert("contracts".to_string(), self.parse_number(quantity, &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("hedged".to_string(), Value::Null);
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("leverage".to_string(), Value::Null);
m.insert("liquidationPrice".to_string(), Value::Null);
m.insert("marginRatio".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m
}));
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("public".into())]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiName: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut endpoint: Value = Value::Str(format!("{}{}", Value::Str("/".into()), self.implode_params(path.clone(), params.clone())).into());
let mut apiUrl: Value = self.safe_string(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), apiName.clone(), &[]);
if (apiUrl == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
let mut url: Value = Value::Str(format!("{}{}", apiUrl, endpoint).into());
let mut headersValue: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Hibachi-Client".to_string(), Value::Str("HibachiCCXT/unversioned".into()));
m
});
if (method.as_str() == Some("GET")) {
let mut request: Value = self.omit(params.clone(), self.extract_params(path), &[]);
let mut query: Value = self.urlencode(request, &[]);
if (Value::Int(query.len() as i64).as_f64() != Some(0.0)) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), query).into())).into());
}
}
let mut hasJsonBody: bool = (method.as_str() == Some("POST")) || (method.as_str() == Some("PUT")) || (method.as_str() == Some("DELETE"));
if hasJsonBody {
if let Value::Dict(__d) = &mut headersValue { std::sync::Arc::make_mut(__d).insert("Content-Type".into(), Value::Str("application/json".into())); }
}
let mut bodyResult: Value = Value::Null;
if hasJsonBody {
bodyResult = json_stringify(¶ms);
}
if (apiName.as_str() == Some("private")) {
self.check_required_credentials(&[]);
if let Value::Dict(__d) = &mut headersValue { std::sync::Arc::make_mut(__d).insert("Authorization".into(), self.apiKey.clone()); }
}
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(), bodyResult);
m.insert("headers".to_string(), headersValue);
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;
}
if (in_op(&response, &Value::Str("status".into()))) {
//
// {"errorCode":4,"message":"Invalid input: Invalid quantity: 0","status":"failed"}
//
let mut status: Option<String> = self.safe_string_k(response.clone(), "status", &[]).as_str().map(str::to_owned);
if (status.as_deref() == Some("failed")) {
let mut code: Value = self.safe_string_k(response.clone(), "errorCode", &[]);
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), body, 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());
let mut message: Value = self.safe_string_k(response.clone(), "message", &[]);
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), message, feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
}
return Value::Null;
Value::Null
}
pub fn parse_transaction_type(&self, mut type_var: Value) -> Option<String> {
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deposit".to_string(), Value::Str("transaction".into()));
m.insert("withdrawal".to_string(), Value::Str("transaction".into()));
m.insert("transfer-in".to_string(), Value::Str("transfer".into()));
m.insert("transfer-out".to_string(), Value::Str("transfer".into()));
m
});
return self.safe_string(types, type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn parse_transaction_status(&self, mut status: Value) -> Value {
let mut statuses: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("pending".to_string(), Value::Str("pending".into()));
m.insert("claimable".to_string(), Value::Str("pending".into()));
m.insert("completed".to_string(), Value::Str("ok".into()));
m.insert("failed".to_string(), Value::Str("canceled".into()));
m
});
return self.safe_string(statuses, status.clone(), &[status.clone()]);
Value::Null
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let mut transactionType: Value = self.safe_string_k(item.clone(), "transactionType", &[]);
let mut timestamp: Value = Value::Null;
let mut type_var: Value = Value::Null;
let mut direction: Value = Value::Null;
let mut amount: Value = Value::Null;
let mut fee: Value = Value::Null;
let mut referenceId: Value = Value::Null;
let mut referenceAccount: Value = Value::Null;
let mut status: Value = Value::Null;
if (transactionType == Value::Null) {
// response from TradeAccountTradingHistory
timestamp = self.safe_integer_product_k(item.clone(), "timestamp", Value::Int(1000), &[]);
type_var = Value::Str("trade".into());
let mut amountStr: Value = self.safe_string_k(item.clone(), "realizedPnl", &[]);
if is_true(&crate::precise::Precise::stringLt(&amountStr, &Value::Str("0".into()))) {
direction = Value::Str("out".into());
amountStr = crate::precise::Precise::stringNeg(&amountStr);
} else {
direction = Value::Str("in".into());
}
amount = self.parse_number(amountStr, &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDT".into()));
m.insert("cost".to_string(), self.safe_number_k(item.clone(), "fee", &[]));
m
});
status = Value::Str("ok".into());
} else {
// response from CapitalHistory
timestamp = self.safe_integer_product_k(item.clone(), "timestampSec", Value::Int(1000), &[]);
amount = self.safe_number_k(item.clone(), "quantity", &[]);
direction = (if ((transactionType.as_str() == Some("deposit")) || (transactionType.as_str() == Some("transfer-in"))) { Value::Str("in".into()) } else { Value::Str("out".into()) });
type_var = self.parse_transaction_type(transactionType.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
status = self.parse_transaction_status(self.safe_string_k(item.clone(), "status", &[]));
if (transactionType.as_str() == Some("transfer-in")) {
referenceAccount = self.safe_string_k(item.clone(), "srcAccountId", &[]);
} else if (transactionType.as_str() == Some("transfer-out")) {
referenceAccount = self.safe_string_k(item.clone(), "receivingAccountId", &[]);
}
referenceId = self.safe_string_k(item.clone(), "transactionHash", &[]);
}
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(item.clone(), "id", &[]));
m.insert("currency".to_string(), self.currency(Value::Str("USDT".into())));
m.insert("account".to_string(), self.number_to_string(self.accountId.clone()));
m.insert("referenceAccount".to_string(), referenceAccount);
m.insert("referenceId".to_string(), referenceId);
m.insert("status".to_string(), status);
m.insert("amount".to_string(), amount);
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m.insert("direction".to_string(), direction);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("type".to_string(), type_var);
m.insert("info".to_string(), item);
m
}), &[currency]);
Value::Null
}
/*
* @method
* @name hibachi#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
* @see https://api-doc.hibachi.xyz/#35125e3f-d154-4bfd-8276-a48bb1c62020
* @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
* @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 currency: Value = self.currency(Value::Str("USDT".into()));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m
});
let __ws_arg_17 = self.extend(request.clone(), &[params.clone()]);
let mut rawPromises: Value = Value::from(vec![self.private_get_capital_history(&[__ws_arg_17]).await, self.private_get_trade_account_trading_history(&[self.extend(request, &[params.clone()])]).await]);
let mut promises: Value = promise_all(&rawPromises).await;
let mut responseCapitalHistory: Value = self.safe_dict(promises.clone(), Value::Int(0), &[]);
//
// {
// "transactions": [
// {
// "assetId": 1,
// "blockNumber": 358396669,
// "chain": "Arbitrum",
// "etaTsSec": null,
// "id": 358396669,
// "quantity": "0.999500",
// "status": "pending",
// "timestampSec": 1752692872,
// "token": "USDT",
// "transactionHash": "0x408e48881e0ba77d8638e3fe57bc06bdec513ddaa8b672e0aefa7e22e2f18b4e",
// "transactionType": "deposit"
// },
// {
// "assetId": 1,
// "etaTsSec": null,
// "id": 13116,
// "instantWithdrawalChain": null,
// "instantWithdrawalToken": null,
// "isInstantWithdrawal": false,
// "quantity": "0.040000",
// "status": "completed",
// "timestampSec": 1752542708,
// "transactionHash": "0xe89cf90b2408d1a273dc9427654145def102d9449e5e2cfc10690ccffc3d7e28",
// "transactionType": "withdrawal",
// "withdrawalAddress": "0x23625d5fc6a6e32638d908eb4c3a3415e5121f76"
// },
// {
// "assetId": 1,
// "id": 167,
// "quantity": "10.000000",
// "srcAccountId": 175,
// "srcAddress": "0xc2f77ce029438a3fdfe68ddee25991a9fb985a86",
// "status": "completed",
// "timestampSec": 1732224729,
// "transactionType": "transfer-in"
// },
// {
// "assetId": 1,
// "id": 170,
// "quantity": "10.000000",
// "receivingAccountId": 175,
// "receivingAddress": "0xc2f77ce029438a3fdfe68ddee25991a9fb985a86",
// "status": "completed",
// "timestampSec": 1732225631,
// "transactionType": "transfer-out"
// },
// ]
// }
//
let mut rowsCapitalHistory: Value = self.safe_list_k(responseCapitalHistory, "transactions", &[Value::from(vec![])]);
let mut responseTradingHistory: Value = self.safe_dict(promises, Value::Int(1), &[]);
//
// {
// "tradingHistory": [
// {
// "eventType": "MARKET",
// "fee": "0.000008",
// "priceOrFundingRate": "119687.82481",
// "quantity": "0.0000003727",
// "realizedPnl": "0.004634",
// "side": "Sell",
// "symbol": "BTC/USDT-P",
// "timestamp": 1752522571
// },
// {
// "eventType": "FundingEvent",
// "fee": "0",
// "priceOrFundingRate": "0.000203",
// "quantity": "0.0000003727",
// "realizedPnl": "-0.000009067899008751979",
// "side": "Long",
// "symbol": "BTC/USDT-P",
// "timestamp": 1752508800
// },
// ]
// }
//
let mut rowsTradingHistory: Value = self.safe_list_k(responseTradingHistory, "tradingHistory", &[Value::from(vec![])]);
let mut rows: Value = self.array_concat(rowsCapitalHistory, rowsTradingHistory);
return self.parse_ledger(rows, &[currency, since, limit, params]);
Value::Null
}
/*
* @method
* @name hibachi#fetchDepositAddress
* @description fetch deposit address for given currency and chain. currently, we have a single EVM address across multiple EVM chains. Note: This method is currently only supported for trustless accounts
* @see https://api-doc.hibachi.xyz/#6fa35580-3d45-4b59-854d-c9326db06af5
* @param {string} code unified currency code
* @param {object} [params] extra parameters for API
* @param {string} [params.publicKey] your public key, you can get it from UI after creating API key
* @returns {object} an [address structure]{@link https://docs.ccxt.com/?id=address-structure}
*/
pub async fn fetch_deposit_address(&mut self, mut code: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("publicKey".to_string(), self.safe_string_k(params.clone(), "publicKey", &[]));
m.insert("accountId".to_string(), self.get_account_id());
m
});
let __ws_arg_18 = self.extend(request, &[params]);
let mut response: Value = self.private_get_capital_deposit_info(&[__ws_arg_18]).await;
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("currency".to_string(), Value::Str("USDT".into()));
m.insert("network".to_string(), Value::Str("ARBITRUM".into()));
m.insert("address".to_string(), self.safe_string_k(response, "depositAddressEvm", &[]));
m.insert("tag".to_string(), Value::Null);
m
});
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Value = self.safe_integer_product_k(transaction.clone(), "timestampSec", Value::Int(1000), &[]);
let mut address: Value = self.safe_string_k(transaction.clone(), "withdrawalAddress", &[]);
let mut transactionType: Value = self.safe_string_k(transaction.clone(), "transactionType", &[]);
if (transactionType.as_str() != Some("deposit")) && (transactionType.as_str() != Some("withdrawal")) {
transactionType = self.parse_transaction_type(transactionType.clone()).map(|__s| Value::Str(__s.into())).unwrap_or(Value::Null);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), self.safe_string_k(transaction.clone(), "id", &[]));
m.insert("txid".to_string(), self.safe_string_k(transaction.clone(), "transactionHash", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("network".to_string(), Value::Str("ARBITRUM".into()));
m.insert("address".to_string(), address.clone());
m.insert("addressTo".to_string(), address);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("tag".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), transactionType);
m.insert("amount".to_string(), self.safe_number_k(transaction.clone(), "quantity", &[]));
m.insert("currency".to_string(), Value::Str("USDT".into()));
m.insert("status".to_string(), self.parse_transaction_status(self.safe_string_k(transaction, "status", &[])));
m.insert("updated".to_string(), Value::Null);
m.insert("internal".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m
});
Value::Null
}
/*
* @method
* @name hibachi#fetchDepositsWithdrawals
* @description fetch deposit and withdrawal history for the account
* @see https://api-doc.hibachi.xyz/#35125e3f-d154-4bfd-8276-a48bb1c62020
* @param {string} [code] unified currency code
* @param {int} [since] timestamp in ms of the earliest transaction
* @param {int} [limit] the maximum number of transactions to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/?id=transaction-structure}
*/
pub async fn fetch_deposits_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
}));
let mut currency: Value = self.safe_currency(code, &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m
});
let __ws_arg_19 = self.extend(request, &[params.clone()]);
let mut response: Value = self.private_get_capital_history(&[__ws_arg_19]).await;
// {
// "transactions": [
// {
// "assetId": 1,
// "blockNumber": 0,
// "chain": null,
// "etaTsSec": 1752758789,
// "id": 42688,
// "quantity": "6.130000",
// "status": "completed",
// "timestampSec": 1752758788,
// "token": null,
// "transactionHash": "0x8dcd7bd1155b5624fb5e38a1365888f712ec633a57434340e05080c70b0e3bba",
// "transactionType": "deposit"
// },
// {
// "assetId": 1,
// "etaTsSec": null,
// "id": 12993,
// "instantWithdrawalChain": null,
// "instantWithdrawalToken": null,
// "isInstantWithdrawal": false,
// "quantity": "0.111930",
// "status": "completed",
// "timestampSec": 1752387891,
// "transactionHash": "0x32ab5fe5b90f6d753bab83523ebc8465eb9daef54580e13cb9ff031d400c5620",
// "transactionType": "withdrawal",
// "withdrawalAddress": "0x43f15ef2ef2ab5e61e987ee3d652a5872aea8a6c"
// },
// ]
// }
let mut transactions: Value = self.safe_list_k(response, "transactions", &[Value::from(vec![])]);
return self.parse_transactions(transactions, &[currency, since, limit, params]);
Value::Null
}
/*
* @method
* @name hibachi#fetchDeposits
* @description fetch deposits made to account
* @see https://api-doc.hibachi.xyz/#35125e3f-d154-4bfd-8276-a48bb1c62020
* @param {string} [code] unified currency code
* @param {int} [since] filter by earliest timestamp (ms)
* @param {int} [limit] maximum number of deposits to be returned
* @param {object} [params] extra parameters to be passed to API
* @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
}));
let mut transactions: Value = self.fetch_deposits_withdrawals(&[code, since.clone(), Value::Null, params]).await;
let mut deposits: Value = self.filter_by(transactions, Value::Str("type".into()), Value::Str("deposit".into()), &[]);
return self.filter_by_since_limit(deposits, &[since, limit, Value::Str("timestamp".into())]);
Value::Null
}
/*
* @method
* @name hibachi#fetchWithdrawals
* @description fetch withdrawals made from account
* @see https://api-doc.hibachi.xyz/#35125e3f-d154-4bfd-8276-a48bb1c62020
* @param {string} [code] unified currency code
* @param {int} [since] filter by earliest timestamp (ms)
* @param {int} [limit] maximum number of deposits to be returned
* @param {object} [params] extra parameters to be passed to API
* @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
}));
let mut transactions: Value = self.fetch_deposits_withdrawals(&[code, since.clone(), Value::Null, params]).await;
let mut withdrawals: Value = self.filter_by(transactions, Value::Str("type".into()), Value::Str("withdrawal".into()), &[]);
return self.filter_by_since_limit(withdrawals, &[since, limit, Value::Str("timestamp".into())]);
Value::Null
}
pub fn parse_settlement(&self, mut settlement: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "direction": "Long",
// "indexPrice": "81.8781761",
// "quantity": "0.10000000",
// "settledAmount": "0.00005994405060281047",
// "symbol": "SOL/USDT-P",
// "timestamp": 1783389600,
// "timestampNsPartial": 0
// }
//
let mut timestamp: Value = self.safe_timestamp_k(settlement.clone(), "timestamp", &[]);
let mut marketId: Value = self.safe_string_k(settlement.clone(), "symbol", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), settlement.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[market]));
m.insert("price".to_string(), self.safe_number_k(settlement, "indexPrice", &[]));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m
});
Value::Null
}
pub fn parse_settlements(&self, mut settlements: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut result: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_741: bool = true;
while { if !__for_first_741 { 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_741 = false; i.as_f64().unwrap_or(f64::NAN) < ((settlements.len() as i64) as f64) } {
append_to_array(&mut result, self.parse_settlement(settlements.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), &[market.clone()]));
}
}
return result;
Value::Null
}
/*
* @method
* @name hibachi#fetchMySettlementHistory
* @description fetches historical settlement records of the user
* @see https://api-doc.hibachi.xyz/#28185336-04b7-4480-bcc8-a33516ad458b
* @param {string} [symbol] unified market symbol of the settlement history
* @param {int} [since] timestamp in ms of the earliest settlement
* @param {int} [limit] the maximum number of settlements to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest settlement
* @returns {object[]} a list of [settlement history objects]{@link https://docs.ccxt.com/#/?id=settlement-history-structure}
*/
pub async fn fetch_my_settlement_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = Value::Null;
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountId".to_string(), self.get_account_id());
m
});
let mut symbolResolved: 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("contractId".into(), market.as_map().and_then(|__m| __m.get("numericId")).cloned().unwrap_or(Value::Null)); }
symbolResolved = self.safe_string_k(market.clone(), "symbol", &[]);
}
if (since != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("startTime".into(), self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))); }
}
if (limit != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("limit".into(), limit.clone()); }
}
let mut untilparamsUntilVariable = self.handle_option_integer_and_params(params, Value::Str("fetchMySettlementHistory".into()), Value::Str("until".into()), &[]);
let mut until: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.as_array().and_then(|__arr| __arr.get(1)).cloned().unwrap_or(Value::Null);
if (until != Value::Null) {
if let Value::Dict(__d) = &mut request { std::sync::Arc::make_mut(__d).insert("endTime".into(), self.parse_to_int((match ((until).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))); }
}
let __ws_arg_20 = self.extend(request, &[paramsUntil]);
let mut response: Value = self.private_get_trade_account_settlements_history(&[__ws_arg_20]).await;
//
// {
// "settlements": [
// {
// "direction": "Long",
// "indexPrice": "81.8781761",
// "quantity": "0.10000000",
// "settledAmount": "0.00005994405060281047",
// "symbol": "SOL/USDT-P",
// "timestamp": 1783389600,
// "timestampNsPartial": 0
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "settlements", &[Value::from(vec![])]);
let mut settlements: Value = self.parse_settlements(data, &[market]);
let mut sorted: Value = self.sort_by(settlements, Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[symbolResolved, since, limit]);
Value::Null
}
/*
* @method
* @name hibachi#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://api-doc.hibachi.xyz/#3277e546-4cb0-4d30-a832-717af0de9b20
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the exchange server
*/
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut response: Value = self.public_get_exchange_utc_timestamp(&[params]).await;
return self.safe_integer_k(response, "timestampMs", &[]);
Value::Null
}
/*
* @method
* @name hibachi#fetchOpenInterest
* @description retrieves the open interest of a contract trading pair
* @see https://api-doc.hibachi.xyz/#bc34e8ae-e094-4802-8d56-3efe3a7bad49
* @param {string} symbol unified CCXT market symbol
* @param {object} [params] exchange specific parameters
* @returns {object} an open interest structure{@link https://docs.ccxt.com/?id=open-interest-structure}
*/
pub async fn fetch_open_interest(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
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_21 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_data_open_interest(&[__ws_arg_21]).await;
//
// { "totalQuantity" : "2.3299770166" }
//
let mut timestamp: Value = self.milliseconds();
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("openInterestAmount".to_string(), self.safe_string_k(response.clone(), "totalQuantity", &[]));
m.insert("openInterestValue".to_string(), Value::Null);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("info".to_string(), response);
m
}), &[market]);
Value::Null
}
/*
* @method
* @name hibachi#fetchFundingRate
* @description fetch the current funding rate
* @see https://api-doc.hibachi.xyz/#bca696ca-b9b2-4072-8864-5d6b8c09807e
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/?id=funding-rate-structure}
*/
pub async fn fetch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut 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_22 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_data_prices(&[__ws_arg_22]).await;
//
// {
// "askPrice": "3514.650296",
// "bidPrice": "3513.596112",
// "fundingRateEstimation": {
// "estimatedFundingRate": "0.000001",
// "nextFundingTimestamp": 1712707200
// },
// "markPrice": "3514.288858",
// "spotPrice": "3514.715000",
// "symbol": "ETH/USDT-P",
// "tradePrice": "2372.746570"
// }
//
let mut funding: Value = self.safe_dict_k(response, "fundingRateEstimation", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Value = self.milliseconds();
let mut nextFundingTimestamp: Value = self.safe_integer_product_k(funding.clone(), "nextFundingTimestamp", Value::Int(1000), &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), funding.clone());
m.insert("symbol".to_string(), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
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(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("fundingRate".to_string(), self.safe_number_k(funding, "estimatedFundingRate", &[]));
m.insert("fundingTimestamp".to_string(), nextFundingTimestamp.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(nextFundingTimestamp));
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::Str("8h".into()));
m
});
Value::Null
}
/*
* @method
* @name hibachi#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://api-doc.hibachi.xyz/#079586af-0d94-41ea-99bb-7afcd93bf438
* @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
* @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 (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("symbol".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_23 = self.extend(request, &[params]);
let mut response: Value = self.public_get_market_data_funding_rates(&[__ws_arg_23]).await;
//
// {
// "data": [
// {
// "contractId": 2,
// "fundingTimestamp": 1753488000,
// "fundingRate": "0.000137",
// "indexPrice": "117623.65010"
// }
// ]
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut rates: Value = Value::from(vec![]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_742: bool = true;
while { if !__for_first_742 { 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_742 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
let mut entry: Value = data.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut timestamp: Value = self.safe_integer_product_k(entry.clone(), "fundingTimestamp", Value::Int(1000), &[]);
append_to_array(&mut rates, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("symbol".to_string(), symbol.clone());
m.insert("fundingRate".to_string(), self.safe_number_k(entry, "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, &[symbol, since, limit]);
Value::Null
}
}