ccxt-go/bingx.go
zhangkun9038@dingtalk.com 1a2ce7046a first add
2025-02-28 10:33:20 +08:00

6754 lines
292 KiB
Go

package ccxt
// 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
type bingx struct {
Exchange
}
func NewBingxCore() bingx {
p := bingx{}
setDefaults(&p)
return p
}
func (this *bingx) Describe() interface{} {
return this.DeepExtend(this.Exchange.Describe(), map[string]interface{} {
"id": "bingx",
"name": "BingX",
"countries": []interface{}{"US"},
"rateLimit": 100,
"version": "v1",
"certified": true,
"pro": true,
"has": map[string]interface{} {
"CORS": nil,
"spot": true,
"margin": false,
"swap": true,
"future": false,
"option": false,
"addMargin": true,
"cancelAllOrders": true,
"cancelAllOrdersAfter": true,
"cancelOrder": true,
"cancelOrders": true,
"closeAllPositions": true,
"closePosition": true,
"createMarketBuyOrderWithCost": true,
"createMarketOrderWithCost": true,
"createMarketSellOrderWithCost": true,
"createOrder": true,
"createOrders": true,
"createOrderWithTakeProfitAndStopLoss": true,
"createStopLossOrder": true,
"createStopOrder": true,
"createTakeProfitOrder": true,
"createTrailingAmountOrder": true,
"createTrailingPercentOrder": true,
"createTriggerOrder": true,
"editOrder": true,
"fetchBalance": true,
"fetchCanceledOrders": true,
"fetchClosedOrders": true,
"fetchCurrencies": true,
"fetchDepositAddress": true,
"fetchDepositAddresses": false,
"fetchDepositAddressesByNetwork": true,
"fetchDeposits": true,
"fetchDepositWithdrawFee": "emulated",
"fetchDepositWithdrawFees": true,
"fetchFundingRate": true,
"fetchFundingRateHistory": true,
"fetchFundingRates": true,
"fetchLeverage": true,
"fetchLiquidations": false,
"fetchMarginAdjustmentHistory": false,
"fetchMarginMode": true,
"fetchMarkets": true,
"fetchMarkOHLCV": true,
"fetchMarkPrice": true,
"fetchMarkPrices": true,
"fetchMyLiquidations": true,
"fetchMyTrades": true,
"fetchOHLCV": true,
"fetchOpenInterest": true,
"fetchOpenOrders": true,
"fetchOrder": true,
"fetchOrderBook": true,
"fetchOrders": true,
"fetchPosition": true,
"fetchPositionHistory": false,
"fetchPositionMode": true,
"fetchPositions": true,
"fetchPositionsHistory": true,
"fetchTicker": true,
"fetchTickers": true,
"fetchTime": true,
"fetchTrades": true,
"fetchTradingFee": true,
"fetchTransfers": true,
"fetchWithdrawals": true,
"reduceMargin": true,
"sandbox": true,
"setLeverage": true,
"setMargin": true,
"setMarginMode": true,
"setPositionMode": true,
"transfer": true,
},
"hostname": "bingx.com",
"urls": map[string]interface{} {
"logo": "https://github-production-user-asset-6210df.s3.amazonaws.com/1294454/253675376-6983b72e-4999-4549-b177-33b374c195e3.jpg",
"api": map[string]interface{} {
"spot": "https://open-api.{hostname}/openApi",
"swap": "https://open-api.{hostname}/openApi",
"contract": "https://open-api.{hostname}/openApi",
"wallets": "https://open-api.{hostname}/openApi",
"user": "https://open-api.{hostname}/openApi",
"subAccount": "https://open-api.{hostname}/openApi",
"account": "https://open-api.{hostname}/openApi",
"copyTrading": "https://open-api.{hostname}/openApi",
"cswap": "https://open-api.{hostname}/openApi",
},
"test": map[string]interface{} {
"swap": "https://open-api-vst.{hostname}/openApi",
},
"www": "https://bingx.com/",
"doc": "https://bingx-api.github.io/docs/",
"referral": "https://bingx.com/invite/OHETOM",
},
"fees": map[string]interface{} {
"tierBased": true,
"spot": map[string]interface{} {
"feeSide": "get",
"maker": this.ParseNumber("0.001"),
"taker": this.ParseNumber("0.001"),
},
"swap": map[string]interface{} {
"feeSide": "quote",
"maker": this.ParseNumber("0.0002"),
"taker": this.ParseNumber("0.0005"),
},
},
"requiredCredentials": map[string]interface{} {
"apiKey": true,
"secret": true,
},
"api": map[string]interface{} {
"spot": map[string]interface{} {
"v1": map[string]interface{} {
"public": map[string]interface{} {
"get": map[string]interface{} {
"server/time": 1,
"common/symbols": 1,
"market/trades": 1,
"market/depth": 1,
"market/kline": 1,
"ticker/24hr": 1,
"ticker/price": 1,
"ticker/bookTicker": 1,
},
},
"private": map[string]interface{} {
"get": map[string]interface{} {
"trade/query": 1,
"trade/openOrders": 1,
"trade/historyOrders": 1,
"trade/myTrades": 2,
"user/commissionRate": 5,
"account/balance": 2,
},
"post": map[string]interface{} {
"trade/order": 2,
"trade/cancel": 2,
"trade/batchOrders": 5,
"trade/order/cancelReplace": 5,
"trade/cancelOrders": 5,
"trade/cancelOpenOrders": 5,
"trade/cancelAllAfter": 5,
},
},
},
"v2": map[string]interface{} {
"public": map[string]interface{} {
"get": map[string]interface{} {
"market/depth": 1,
"market/kline": 1,
},
},
},
"v3": map[string]interface{} {
"private": map[string]interface{} {
"get": map[string]interface{} {
"get/asset/transfer": 1,
"asset/transfer": 1,
"capital/deposit/hisrec": 1,
"capital/withdraw/history": 1,
},
"post": map[string]interface{} {
"post/asset/transfer": 5,
},
},
},
},
"swap": map[string]interface{} {
"v1": map[string]interface{} {
"public": map[string]interface{} {
"get": map[string]interface{} {
"ticker/price": 1,
"market/historicalTrades": 1,
"market/markPriceKlines": 1,
"trade/multiAssetsRules": 1,
},
},
"private": map[string]interface{} {
"get": map[string]interface{} {
"positionSide/dual": 5,
"trade/batchCancelReplace": 5,
"trade/fullOrder": 2,
"maintMarginRatio": 2,
"trade/positionHistory": 2,
"positionMargin/history": 2,
"twap/openOrders": 5,
"twap/historyOrders": 5,
"twap/orderDetail": 5,
"trade/assetMode": 5,
"user/marginAssets": 5,
},
"post": map[string]interface{} {
"trade/cancelReplace": 2,
"positionSide/dual": 5,
"trade/batchCancelReplace": 5,
"trade/closePosition": 2,
"trade/getVst": 5,
"twap/order": 5,
"twap/cancelOrder": 5,
"trade/assetMode": 5,
},
},
},
"v2": map[string]interface{} {
"public": map[string]interface{} {
"get": map[string]interface{} {
"server/time": 1,
"quote/contracts": 1,
"quote/price": 1,
"quote/depth": 1,
"quote/trades": 1,
"quote/premiumIndex": 1,
"quote/fundingRate": 1,
"quote/klines": 1,
"quote/openInterest": 1,
"quote/ticker": 1,
"quote/bookTicker": 1,
},
},
"private": map[string]interface{} {
"get": map[string]interface{} {
"user/balance": 2,
"user/positions": 2,
"user/income": 2,
"trade/openOrders": 2,
"trade/openOrder": 2,
"trade/order": 2,
"trade/marginType": 5,
"trade/leverage": 2,
"trade/forceOrders": 1,
"trade/allOrders": 2,
"trade/allFillOrders": 2,
"trade/fillHistory": 2,
"user/income/export": 2,
"user/commissionRate": 2,
"quote/bookTicker": 1,
},
"post": map[string]interface{} {
"trade/order": 2,
"trade/batchOrders": 2,
"trade/closeAllPositions": 2,
"trade/cancelAllAfter": 5,
"trade/marginType": 5,
"trade/leverage": 5,
"trade/positionMargin": 5,
"trade/order/test": 2,
},
"delete": map[string]interface{} {
"trade/order": 2,
"trade/batchOrders": 2,
"trade/allOpenOrders": 2,
},
},
},
"v3": map[string]interface{} {
"public": map[string]interface{} {
"get": map[string]interface{} {
"quote/klines": 1,
},
},
},
},
"cswap": map[string]interface{} {
"v1": map[string]interface{} {
"public": map[string]interface{} {
"get": map[string]interface{} {
"market/contracts": 1,
"market/premiumIndex": 1,
"market/openInterest": 1,
"market/klines": 1,
"market/depth": 1,
"market/ticker": 1,
},
},
"private": map[string]interface{} {
"get": map[string]interface{} {
"trade/leverage": 2,
"trade/forceOrders": 2,
"trade/allFillOrders": 2,
"trade/openOrders": 2,
"trade/orderDetail": 2,
"trade/orderHistory": 2,
"trade/marginType": 2,
"user/commissionRate": 2,
"user/positions": 2,
"user/balance": 2,
},
"post": map[string]interface{} {
"trade/order": 2,
"trade/leverage": 2,
"trade/allOpenOrders": 2,
"trade/closeAllPositions": 2,
"trade/marginType": 2,
"trade/positionMargin": 2,
},
"delete": map[string]interface{} {
"trade/allOpenOrders": 2,
"trade/cancelOrder": 2,
},
},
},
},
"contract": map[string]interface{} {
"v1": map[string]interface{} {
"private": map[string]interface{} {
"get": map[string]interface{} {
"allPosition": 2,
"allOrders": 2,
"balance": 2,
},
},
},
},
"wallets": map[string]interface{} {
"v1": map[string]interface{} {
"private": map[string]interface{} {
"get": map[string]interface{} {
"capital/config/getall": 5,
"capital/deposit/address": 5,
"capital/innerTransfer/records": 1,
"capital/subAccount/deposit/address": 5,
"capital/deposit/subHisrec": 2,
"capital/subAccount/innerTransfer/records": 1,
"capital/deposit/riskRecords": 5,
},
"post": map[string]interface{} {
"capital/withdraw/apply": 5,
"capital/innerTransfer/apply": 5,
"capital/subAccountInnerTransfer/apply": 2,
"capital/deposit/createSubAddress": 2,
},
},
},
},
"subAccount": map[string]interface{} {
"v1": map[string]interface{} {
"private": map[string]interface{} {
"get": map[string]interface{} {
"list": 10,
"assets": 2,
"allAccountBalance": 2,
},
"post": map[string]interface{} {
"create": 10,
"apiKey/create": 2,
"apiKey/edit": 2,
"apiKey/del": 2,
"updateStatus": 10,
},
},
},
},
"account": map[string]interface{} {
"v1": map[string]interface{} {
"private": map[string]interface{} {
"get": map[string]interface{} {
"uid": 1,
"apiKey/query": 2,
"account/apiPermissions": 5,
},
"post": map[string]interface{} {
"innerTransfer/authorizeSubAccount": 1,
},
},
},
"transfer": map[string]interface{} {
"v1": map[string]interface{} {
"private": map[string]interface{} {
"get": map[string]interface{} {
"subAccount/asset/transferHistory": 1,
},
"post": map[string]interface{} {
"subAccount/transferAsset/supportCoins": 1,
"subAccount/transferAsset": 1,
},
},
},
},
},
"user": map[string]interface{} {
"auth": map[string]interface{} {
"private": map[string]interface{} {
"post": map[string]interface{} {
"userDataStream": 2,
},
"put": map[string]interface{} {
"userDataStream": 2,
},
"delete": map[string]interface{} {
"userDataStream": 2,
},
},
},
},
"copyTrading": map[string]interface{} {
"v1": map[string]interface{} {
"private": map[string]interface{} {
"get": map[string]interface{} {
"swap/trace/currentTrack": 2,
},
"post": map[string]interface{} {
"swap/trace/closeTrackOrder": 2,
"swap/trace/setTPSL": 2,
"spot/trader/sellOrder": 10,
},
},
},
},
"api": map[string]interface{} {
"v3": map[string]interface{} {
"private": map[string]interface{} {
"get": map[string]interface{} {
"asset/transfer": 1,
"capital/deposit/hisrec": 1,
"capital/withdraw/history": 1,
},
"post": map[string]interface{} {
"post/asset/transfer": 1,
},
},
},
},
},
"timeframes": map[string]interface{} {
"1m": "1m",
"3m": "3m",
"5m": "5m",
"15m": "15m",
"30m": "30m",
"1h": "1h",
"2h": "2h",
"4h": "4h",
"6h": "6h",
"12h": "12h",
"1d": "1d",
"3d": "3d",
"1w": "1w",
"1M": "1M",
},
"precisionMode": TICK_SIZE,
"exceptions": map[string]interface{} {
"exact": map[string]interface{} {
"400": BadRequest,
"401": AuthenticationError,
"403": PermissionDenied,
"404": BadRequest,
"429": DDoSProtection,
"418": PermissionDenied,
"500": ExchangeError,
"504": ExchangeError,
"100001": AuthenticationError,
"100412": AuthenticationError,
"100202": InsufficientFunds,
"100204": BadRequest,
"100400": BadRequest,
"100410": OperationFailed,
"100421": BadSymbol,
"100440": ExchangeError,
"100500": OperationFailed,
"100503": ExchangeError,
"80001": BadRequest,
"80012": InsufficientFunds,
"80014": BadRequest,
"80016": OrderNotFound,
"80017": OrderNotFound,
"100414": AccountSuspended,
"100419": PermissionDenied,
"100437": BadRequest,
"101204": InsufficientFunds,
"110425": InvalidOrder,
},
"broad": map[string]interface{} {},
},
"commonCurrencies": map[string]interface{} {
"SNOW": "Snowman",
"OMNI": "OmniCat",
"NAP": "$NAP",
"TRUMP": "TRUMPMAGA",
"TRUMPSOL": "TRUMP",
},
"options": map[string]interface{} {
"defaultType": "spot",
"accountsByType": map[string]interface{} {
"spot": "FUND",
"swap": "PFUTURES",
"future": "SFUTURES",
},
"accountsById": map[string]interface{} {
"FUND": "spot",
"PFUTURES": "swap",
"SFUTURES": "future",
},
"recvWindow": Multiply(5, 1000),
"broker": "CCXT",
"defaultNetworks": map[string]interface{} {
"ETH": "ETH",
"USDT": "ERC20",
"USDC": "ERC20",
"BTC": "BTC",
"LTC": "LTC",
},
"networks": map[string]interface{} {
"ARB": "ARBITRUM",
"MATIC": "POLYGON",
},
},
"features": map[string]interface{} {
"defaultForLinear": map[string]interface{} {
"sandbox": true,
"createOrder": map[string]interface{} {
"marginMode": false,
"triggerPrice": true,
"triggerPriceType": map[string]interface{} {
"last": true,
"mark": true,
"index": true,
},
"triggerDirection": false,
"stopLossPrice": true,
"takeProfitPrice": true,
"attachedStopLossTakeProfit": map[string]interface{} {
"triggerPriceType": map[string]interface{} {
"last": true,
"mark": true,
"index": true,
},
"price": true,
},
"timeInForce": map[string]interface{} {
"IOC": true,
"FOK": true,
"PO": true,
"GTD": false,
},
"hedged": true,
"trailing": true,
"leverage": false,
"marketBuyRequiresPrice": false,
"marketBuyByCost": true,
"selfTradePrevention": false,
"iceberg": false,
},
"createOrders": map[string]interface{} {
"max": 5,
},
"fetchMyTrades": map[string]interface{} {
"marginMode": false,
"limit": 512,
"daysBack": 30,
"untilDays": 30,
"symbolRequired": true,
},
"fetchOrder": map[string]interface{} {
"marginMode": false,
"trigger": false,
"trailing": false,
"symbolRequired": true,
},
"fetchOpenOrders": map[string]interface{} {
"marginMode": false,
"limit": nil,
"trigger": false,
"trailing": false,
"symbolRequired": false,
},
"fetchOrders": map[string]interface{} {
"marginMode": false,
"limit": 1000,
"daysBack": 20000,
"untilDays": 7,
"trigger": false,
"trailing": false,
"symbolRequired": true,
},
"fetchClosedOrders": map[string]interface{} {
"marginMode": false,
"limit": 1000,
"daysBack": nil,
"daysBackCanceled": nil,
"untilDays": 7,
"trigger": false,
"trailing": false,
"symbolRequired": true,
},
"fetchOHLCV": map[string]interface{} {
"limit": 1440,
},
},
"defaultForInverse": map[string]interface{} {
"extends": "defaultForLinear",
"fetchMyTrades": map[string]interface{} {
"limit": 1000,
"daysBack": nil,
"untilDays": nil,
},
"fetchOrders": nil,
},
"spot": map[string]interface{} {
"extends": "defaultForLinear",
"createOrder": map[string]interface{} {
"triggerPriceType": nil,
"attachedStopLossTakeProfit": nil,
"trailing": false,
},
"fetchMyTrades": map[string]interface{} {
"limit": 1000,
"daysBack": 1,
"untilDays": 1,
},
"fetchOrders": nil,
"fetchClosedOrders": map[string]interface{} {
"limit": 100,
"untilDays": nil,
},
},
"swap": map[string]interface{} {
"linear": map[string]interface{} {
"extends": "defaultForLinear",
},
"inverse": map[string]interface{} {
"extends": "defaultForInverse",
},
},
"defaultForFuture": map[string]interface{} {
"extends": "defaultForLinear",
"fetchOrders": nil,
},
"future": map[string]interface{} {
"linear": map[string]interface{} {
"extends": "defaultForFuture",
},
"inverse": map[string]interface{} {
"extends": "defaultForFuture",
},
},
},
})
}
/**
* @method
* @name bingx#fetchTime
* @description fetches the current integer timestamp in milliseconds from the bingx server
* @see https://bingx-api.github.io/docs/#/swapV2/base-info.html#Get%20Server%20Time
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {int} the current integer timestamp in milliseconds from the bingx server
*/
func (this *bingx) FetchTime(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
response:= (<-this.SwapV2PublicGetServerTime(params))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "serverTime": 1675319535362
// }
// }
//
var data interface{} = this.SafeDict(response, "data")
ch <- this.SafeInteger(data, "serverTime")
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://bingx-api.github.io/docs/#/common/account-api.html#All%20Coins
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
func (this *bingx) FetchCurrencies(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
if !IsTrue(this.CheckRequiredCredentials(false)) {
return nil
}
var isSandbox interface{} = this.SafeBool(this.Options, "sandboxMode", false)
if IsTrue(isSandbox) {
return nil
}
response:= (<-this.WalletsV1PrivateGetCapitalConfigGetall(params))
PanicOnError(response)
//
// {
// "code": 0,
// "timestamp": 1702623271477,
// "data": [
// {
// "coin": "BTC",
// "name": "BTC",
// "networkList": [
// {
// "name": "BTC",
// "network": "BTC",
// "isDefault": true,
// "minConfirm": 2,
// "withdrawEnable": true,
// "depositEnable": true,
// "withdrawFee": "0.0006",
// "withdrawMax": "1.17522",
// "withdrawMin": "0.0005",
// "depositMin": "0.0002"
// },
// {
// "name": "BTC",
// "network": "BEP20",
// "isDefault": false,
// "minConfirm": 15,
// "withdrawEnable": true,
// "depositEnable": true,
// "withdrawFee": "0.0000066",
// "withdrawMax": "1.17522",
// "withdrawMin": "0.0000066",
// "depositMin": "0.0002"
// }
// ]
// }
// ]
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
var result interface{} = map[string]interface{} {}
for i := 0; IsLessThan(i, GetArrayLength(data)); i++ {
var entry interface{} = GetValue(data, i)
var currencyId interface{} = this.SafeString(entry, "coin")
var code interface{} = this.SafeCurrencyCode(currencyId)
var name interface{} = this.SafeString(entry, "name")
var networkList interface{} = this.SafeList(entry, "networkList")
var networks interface{} = map[string]interface{} {}
var fee interface{} = nil
var depositEnabled interface{} = false
var withdrawEnabled interface{} = false
var defaultLimits interface{} = map[string]interface{} {}
for j := 0; IsLessThan(j, GetArrayLength(networkList)); j++ {
var rawNetwork interface{} = GetValue(networkList, j)
var network interface{} = this.SafeString(rawNetwork, "network")
var networkCode interface{} = this.NetworkIdToCode(network)
var isDefault interface{} = this.SafeBool(rawNetwork, "isDefault")
var networkDepositEnabled interface{} = this.SafeBool(rawNetwork, "depositEnable")
if IsTrue(networkDepositEnabled) {
depositEnabled = true
}
var networkWithdrawEnabled interface{} = this.SafeBool(rawNetwork, "withdrawEnable")
if IsTrue(networkWithdrawEnabled) {
withdrawEnabled = true
}
var limits interface{} = map[string]interface{} {
"withdraw": map[string]interface{} {
"min": this.SafeNumber(rawNetwork, "withdrawMin"),
"max": this.SafeNumber(rawNetwork, "withdrawMax"),
},
}
fee = this.SafeNumber(rawNetwork, "withdrawFee")
if IsTrue(isDefault) {
defaultLimits = limits
}
var precision interface{} = this.SafeNumber(rawNetwork, "withdrawPrecision")
var networkActive interface{} = IsTrue(networkDepositEnabled) || IsTrue(networkWithdrawEnabled)
AddElementToObject(networks, networkCode, map[string]interface{} {
"info": rawNetwork,
"id": network,
"network": networkCode,
"fee": fee,
"active": networkActive,
"deposit": networkDepositEnabled,
"withdraw": networkWithdrawEnabled,
"precision": precision,
"limits": limits,
})
}
var active interface{} = IsTrue(depositEnabled) || IsTrue(withdrawEnabled)
AddElementToObject(result, code, map[string]interface{} {
"info": entry,
"code": code,
"id": currencyId,
"precision": nil,
"name": name,
"active": active,
"deposit": depositEnabled,
"withdraw": withdrawEnabled,
"networks": networks,
"fee": fee,
"limits": defaultLimits,
})
}
ch <- result
return nil
}()
return ch
}
func (this *bingx) FetchSpotMarkets(params interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
response:= (<-this.SpotV1PublicGetCommonSymbols(params))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "debugMsg": "",
// "data": {
// "symbols": [
// {
// "symbol": "GEAR-USDT",
// "minQty": 735, // deprecated
// "maxQty": 2941177, // deprecated
// "minNotional": 5,
// "maxNotional": 20000,
// "status": 1,
// "tickSize": 0.000001,
// "stepSize": 1,
// "apiStateSell": true,
// "apiStateBuy": true,
// "timeOnline": 0,
// "offTime": 0,
// "maintainTime": 0
// },
// ...
// ]
// }
// }
//
var data interface{} = this.SafeDict(response, "data")
var markets interface{} = this.SafeList(data, "symbols", []interface{}{})
ch <- this.ParseMarkets(markets)
return nil
}()
return ch
}
func (this *bingx) FetchSwapMarkets(params interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
response:= (<-this.SwapV2PublicGetQuoteContracts(params))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "data": [
// {
// "contractId": "100",
// "symbol": "BTC-USDT",
// "size": "0.0001",
// "quantityPrecision": "4",
// "pricePrecision": "1",
// "feeRate": "0.0005",
// "makerFeeRate": "0.0002",
// "takerFeeRate": "0.0005",
// "tradeMinLimit": "0",
// "tradeMinQuantity": "0.0001",
// "tradeMinUSDT": "2",
// "maxLongLeverage": "125",
// "maxShortLeverage": "125",
// "currency": "USDT",
// "asset": "BTC",
// "status": "1",
// "apiStateOpen": "true",
// "apiStateClose": "true",
// "ensureTrigger": true,
// "triggerFeeRate": "0.00020000"
// },
// ...
// ]
// }
//
var markets interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseMarkets(markets)
return nil
}()
return ch
}
func (this *bingx) FetchInverseSwapMarkets(params interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
response:= (<-this.CswapV1PublicGetMarketContracts(params))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720074487610,
// "data": [
// {
// "symbol": "BNB-USD",
// "pricePrecision": 2,
// "minTickSize": "10",
// "minTradeValue": "10",
// "minQty": "1.00000000",
// "status": 1,
// "timeOnline": 1713175200000
// },
// ]
// }
//
var markets interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseMarkets(markets)
return nil
}()
return ch
}
func (this *bingx) ParseMarket(market interface{}) interface{} {
var id interface{} = this.SafeString(market, "symbol")
var symbolParts interface{} = Split(id, "-")
var baseId interface{} = GetValue(symbolParts, 0)
var quoteId interface{} = GetValue(symbolParts, 1)
var base interface{} = this.SafeCurrencyCode(baseId)
var quote interface{} = this.SafeCurrencyCode(quoteId)
var currency interface{} = this.SafeString(market, "currency")
var checkIsInverse interface{} = false
var checkIsLinear interface{} = true
var minTickSize interface{} = this.SafeNumber(market, "minTickSize")
if IsTrue(!IsEqual(minTickSize, nil)) {
// inverse swap market
currency = baseId
checkIsInverse = true
checkIsLinear = false
}
var settle interface{} = this.SafeCurrencyCode(currency)
var pricePrecision interface{} = this.SafeNumber(market, "tickSize")
if IsTrue(IsEqual(pricePrecision, nil)) {
pricePrecision = this.ParseNumber(this.ParsePrecision(this.SafeString(market, "pricePrecision")))
}
var quantityPrecision interface{} = this.SafeNumber(market, "stepSize")
if IsTrue(IsEqual(quantityPrecision, nil)) {
quantityPrecision = this.ParseNumber(this.ParsePrecision(this.SafeString(market, "quantityPrecision")))
}
var typeVar interface{} = Ternary(IsTrue((!IsEqual(settle, nil))), "swap", "spot")
var spot interface{} = IsEqual(typeVar, "spot")
var swap interface{} = IsEqual(typeVar, "swap")
var symbol interface{} = Add(Add(base, "/"), quote)
if IsTrue(!IsEqual(settle, nil)) {
symbol = Add(symbol, Add(":", settle))
}
var fees interface{} = this.SafeDict(this.Fees, typeVar, map[string]interface{} {})
var contractSize interface{} = Ternary(IsTrue((swap)), this.ParseNumber("1"), nil)
var isActive interface{} = false
if IsTrue(IsTrue((IsEqual(this.SafeString(market, "apiStateOpen"), "true"))) && IsTrue((IsEqual(this.SafeString(market, "apiStateClose"), "true")))) {
isActive = true // swap active
} else if IsTrue(IsTrue(IsTrue(this.SafeBool(market, "apiStateSell")) && IsTrue(this.SafeBool(market, "apiStateBuy"))) && IsTrue((IsEqual(this.SafeString(market, "status"), "1")))) {
isActive = true // spot active
}
var isInverse interface{} = Ternary(IsTrue((spot)), nil, checkIsInverse)
var isLinear interface{} = Ternary(IsTrue((spot)), nil, checkIsLinear)
var minAmount interface{} = nil
if !IsTrue(spot) {
minAmount = this.SafeNumber2(market, "minQty", "tradeMinQuantity")
}
var timeOnline interface{} = this.SafeInteger(market, "timeOnline")
if IsTrue(IsEqual(timeOnline, 0)) {
timeOnline = nil
}
return this.SafeMarketStructure(map[string]interface{} {
"id": id,
"symbol": symbol,
"base": base,
"quote": quote,
"settle": settle,
"baseId": baseId,
"quoteId": quoteId,
"settleId": currency,
"type": typeVar,
"spot": spot,
"margin": false,
"swap": swap,
"future": false,
"option": false,
"active": isActive,
"contract": swap,
"linear": isLinear,
"inverse": isInverse,
"taker": this.SafeNumber(fees, "taker"),
"maker": this.SafeNumber(fees, "maker"),
"feeSide": this.SafeString(fees, "feeSide"),
"contractSize": contractSize,
"expiry": nil,
"expiryDatetime": nil,
"strike": nil,
"optionType": nil,
"precision": map[string]interface{} {
"amount": quantityPrecision,
"price": pricePrecision,
},
"limits": map[string]interface{} {
"leverage": map[string]interface{} {
"min": nil,
"max": nil,
},
"amount": map[string]interface{} {
"min": minAmount,
"max": nil,
},
"price": map[string]interface{} {
"min": minTickSize,
"max": nil,
},
"cost": map[string]interface{} {
"min": this.SafeNumberN(market, []interface{}{"minNotional", "tradeMinUSDT", "minTradeValue"}),
"max": this.SafeNumber(market, "maxNotional"),
},
},
"created": timeOnline,
"info": market,
})
}
/**
* @method
* @name bingx#fetchMarkets
* @description retrieves data on all markets for bingx
* @see https://bingx-api.github.io/docs/#/spot/market-api.html#Query%20Symbols
* @see https://bingx-api.github.io/docs/#/swapV2/market-api.html#Contract%20Information
* @see https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Contract%20Information
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
func (this *bingx) FetchMarkets(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
var requests interface{} = []interface{}{this.FetchSwapMarkets(params)}
var isSandbox interface{} = this.SafeBool(this.Options, "sandboxMode", false)
if !IsTrue(isSandbox) {
AppendToArray(&requests,this.FetchInverseSwapMarkets(params))
AppendToArray(&requests,this.FetchSpotMarkets(params)) // sandbox is swap only
}
promises:= (<-promiseAll(requests))
PanicOnError(promises)
var linearSwapMarkets interface{} = this.SafeList(promises, 0, []interface{}{})
var inverseSwapMarkets interface{} = this.SafeList(promises, 1, []interface{}{})
var spotMarkets interface{} = this.SafeList(promises, 2, []interface{}{})
var swapMarkets interface{} = this.ArrayConcat(linearSwapMarkets, inverseSwapMarkets)
ch <- this.ArrayConcat(spotMarkets, swapMarkets)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://bingx-api.github.io/docs/#/swapV2/market-api.html#K-Line%20Data
* @see https://bingx-api.github.io/docs/#/spot/market-api.html#Candlestick%20chart%20data
* @see https://bingx-api.github.io/docs/#/swapV2/market-api.html#%20K-Line%20Data
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Mark%20Price%20Kline/Candlestick%20Data
* @see https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Get%20K-line%20Data
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest candle to fetch
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
func (this *bingx) FetchOHLCV(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
timeframe := GetArg(optionalArgs, 0, "1m")
_ = timeframe
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes10608 := (<-this.LoadMarkets())
PanicOnError(retRes10608)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOHLCV", "paginate", false);
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes106419 := (<-this.FetchPaginatedCallDeterministic("fetchOHLCV", symbol, since, limit, timeframe, params, 1440))
PanicOnError(retRes106419)
ch <- retRes106419
return nil
}
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
AddElementToObject(request, "interval", this.SafeString(this.Timeframes, timeframe, timeframe))
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startTime", mathMax(Subtract(since, 1), 0))
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "limit", limit)
}
var until interface{} = this.SafeInteger2(params, "until", "endTime")
if IsTrue(!IsEqual(until, nil)) {
params = this.Omit(params, []interface{}{"until"})
AddElementToObject(request, "endTime", until)
}
var response interface{} = nil
if IsTrue(GetValue(market, "spot")) {
response = (<-this.SpotV1PublicGetMarketKline(this.Extend(request, params)))
PanicOnError(response)
} else {
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PublicGetMarketKlines(this.Extend(request, params)))
PanicOnError(response)
} else {
var price interface{} = this.SafeString(params, "price")
params = this.Omit(params, "price")
if IsTrue(IsEqual(price, "mark")) {
response = (<-this.SwapV1PublicGetMarketMarkPriceKlines(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV3PublicGetQuoteKlines(this.Extend(request, params)))
PanicOnError(response)
}
}
}
//
// {
// "code": 0,
// "msg": "",
// "data": [
// {
// "open": "19396.8",
// "close": "19394.4",
// "high": "19397.5",
// "low": "19385.7",
// "volume": "110.05",
// "time": 1666583700000
// },
// ...
// ]
// }
//
// fetchMarkOHLCV
//
// {
// "code": 0,
// "msg": "",
// "data": [
// {
// "open": "42191.7",
// "close": "42189.5",
// "high": "42196.5",
// "low": "42189.5",
// "volume": "0.00",
// "openTime": 1706508840000,
// "closeTime": 1706508840000
// }
// ]
// }
//
var ohlcvs interface{} = this.SafeValue(response, "data", []interface{}{})
if !IsTrue(IsArray(ohlcvs)) {
ohlcvs = []interface{}{ohlcvs}
}
ch <- this.ParseOHLCVs(ohlcvs, market, timeframe, since, limit)
return nil
}()
return ch
}
func (this *bingx) ParseOHLCV(ohlcv interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "open": "19394.4",
// "close": "19379.0",
// "high": "19394.4",
// "low": "19368.3",
// "volume": "167.44",
// "time": 1666584000000
// }
//
// fetchMarkOHLCV
//
// {
// "open": "42191.7",
// "close": "42189.5",
// "high": "42196.5",
// "low": "42189.5",
// "volume": "0.00",
// "openTime": 1706508840000,
// "closeTime": 1706508840000
// }
// spot
// [
// 1691402580000,
// 29093.61,
// 29093.93,
// 29087.73,
// 29093.24,
// 0.59,
// 1691402639999,
// 17221.07
// ]
//
market := GetArg(optionalArgs, 0, nil)
_ = market
if IsTrue(IsArray(ohlcv)) {
return []interface{}{this.SafeInteger(ohlcv, 0), this.SafeNumber(ohlcv, 1), this.SafeNumber(ohlcv, 2), this.SafeNumber(ohlcv, 3), this.SafeNumber(ohlcv, 4), this.SafeNumber(ohlcv, 5)}
}
return []interface{}{this.SafeInteger2(ohlcv, "time", "closeTime"), this.SafeNumber(ohlcv, "open"), this.SafeNumber(ohlcv, "high"), this.SafeNumber(ohlcv, "low"), this.SafeNumber(ohlcv, "close"), this.SafeNumber(ohlcv, "volume")}
}
/**
* @method
* @name bingx#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://bingx-api.github.io/docs/#/spot/market-api.html#Query%20transaction%20records
* @see https://bingx-api.github.io/docs/#/swapV2/market-api.html#The%20latest%20Trade%20of%20a%20Trading%20Pair
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades}
*/
func (this *bingx) FetchTrades(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
since := GetArg(optionalArgs, 0, nil)
_ = since
limit := GetArg(optionalArgs, 1, nil)
_ = limit
params := GetArg(optionalArgs, 2, map[string]interface{} {})
_ = params
retRes12078 := (<-this.LoadMarkets())
PanicOnError(retRes12078)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "limit", mathMin(limit, 100)) // avoid API exception "limit should less than 100"
}
var response interface{} = nil
var marketType interface{} = nil
marketTypeparamsVariable := this.HandleMarketTypeAndParams("fetchTrades", market, params);
marketType = GetValue(marketTypeparamsVariable,0);
params = GetValue(marketTypeparamsVariable,1)
if IsTrue(IsEqual(marketType, "spot")) {
response = (<-this.SpotV1PublicGetMarketTrades(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PublicGetQuoteTrades(this.Extend(request, params)))
PanicOnError(response)
}
//
// spot
//
// {
// "code": 0,
// "data": [
// {
// "id": 43148253,
// "price": 25714.71,
// "qty": 1.674571,
// "time": 1655085975589,
// "buyerMaker": false
// }
// ]
// }
//
// swap
//
// {
// "code":0,
// "msg":"",
// "data":[
// {
// "time": 1672025549368,
// "isBuyerMaker": true,
// "price": "16885.0",
// "qty": "3.3002",
// "quoteQty": "55723.87"
// },
// ...
// ]
// }
//
var trades interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseTrades(trades, market, since, limit)
return nil
}()
return ch
}
func (this *bingx) ParseTrade(trade interface{}, optionalArgs ...interface{}) interface{} {
//
// spot fetchTrades
//
// {
// "id": 43148253,
// "price": 25714.71,
// "qty": 1.674571,
// "time": 1655085975589,
// "buyerMaker": false
// }
//
// spot fetchMyTrades
//
// {
// "symbol": "LTC-USDT",
// "id": 36237072,
// "orderId": 1674069326895775744,
// "price": "85.891",
// "qty": "0.0582",
// "quoteQty": "4.9988562000000005",
// "commission": -0.00005820000000000001,
// "commissionAsset": "LTC",
// "time": 1687964205000,
// "isBuyer": true,
// "isMaker": false
// }
//
// swap fetchTrades
//
// {
// "time": 1672025549368,
// "isBuyerMaker": true,
// "price": "16885.0",
// "qty": "3.3002",
// "quoteQty": "55723.87"
// }
//
// swap fetchMyTrades
//
// {
// "volume": "0.1",
// "price": "106.75",
// "amount": "10.6750",
// "commission": "-0.0053",
// "currency": "USDT",
// "orderId": "1676213270274379776",
// "liquidatedPrice": "0.00",
// "liquidatedMarginRatio": "0.00",
// "filledTime": "2023-07-04T20:56:01.000+0800"
// }
//
// ws spot
//
// {
// "E": 1690214529432,
// "T": 1690214529386,
// "e": "trade",
// "m": true,
// "p": "29110.19",
// "q": "0.1868",
// "s": "BTC-USDT",
// "t": "57903921"
// }
//
// ws linear swap
//
// {
// "q": "0.0421",
// "p": "29023.5",
// "T": 1690221401344,
// "m": false,
// "s": "BTC-USDT"
// }
//
// ws inverse swap
//
// {
// "e": "trade",
// "E": 1722920589665,
// "s": "BTC-USD",
// "t": "39125001",
// "p": "55360.0",
// "q": "1",
// "T": 1722920589582,
// "m": false
// }
//
// inverse swap fetchMyTrades
//
// {
// "orderId": "1817441228670648320",
// "symbol": "SOL-USD",
// "type": "MARKET",
// "side": "BUY",
// "positionSide": "LONG",
// "tradeId": "97244554",
// "volume": "2",
// "tradePrice": "182.652",
// "amount": "20.00000000",
// "realizedPnl": "0.00000000",
// "commission": "-0.00005475",
// "currency": "SOL",
// "buyer": true,
// "maker": false,
// "tradeTime": 1722146730000
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var time interface{} = this.SafeIntegerN(trade, []interface{}{"time", "filledTm", "T", "tradeTime"})
var datetimeId interface{} = this.SafeString(trade, "filledTm")
if IsTrue(!IsEqual(datetimeId, nil)) {
time = this.Parse8601(datetimeId)
}
if IsTrue(IsEqual(time, 0)) {
time = nil
}
var cost interface{} = this.SafeString(trade, "quoteQty")
// const type = (cost === undefined) ? 'spot' : 'swap'; this is not reliable
var currencyId interface{} = this.SafeStringN(trade, []interface{}{"currency", "N", "commissionAsset"})
var currencyCode interface{} = this.SafeCurrencyCode(currencyId)
var m interface{} = this.SafeBool(trade, "m")
var marketId interface{} = this.SafeString2(trade, "s", "symbol")
var isBuyerMaker interface{} = this.SafeBoolN(trade, []interface{}{"buyerMaker", "isBuyerMaker", "maker"})
var takeOrMaker interface{} = nil
if IsTrue(IsTrue((!IsEqual(isBuyerMaker, nil))) || IsTrue((!IsEqual(m, nil)))) {
takeOrMaker = Ternary(IsTrue((IsTrue(isBuyerMaker) || IsTrue(m))), "maker", "taker")
}
var side interface{} = this.SafeStringLower2(trade, "side", "S")
if IsTrue(IsEqual(side, nil)) {
if IsTrue(IsTrue((!IsEqual(isBuyerMaker, nil))) || IsTrue((!IsEqual(m, nil)))) {
side = Ternary(IsTrue((IsTrue(isBuyerMaker) || IsTrue(m))), "sell", "buy")
takeOrMaker = "taker"
}
}
var isBuyer interface{} = this.SafeBool(trade, "isBuyer")
if IsTrue(!IsEqual(isBuyer, nil)) {
side = Ternary(IsTrue(isBuyer), "buy", "sell")
}
var isMaker interface{} = this.SafeBool(trade, "isMaker")
if IsTrue(!IsEqual(isMaker, nil)) {
takeOrMaker = Ternary(IsTrue(isMaker), "maker", "taker")
}
var amount interface{} = this.SafeStringN(trade, []interface{}{"qty", "amount", "q"})
if IsTrue(IsTrue(IsTrue((!IsEqual(market, nil))) && IsTrue(GetValue(market, "swap"))) && IsTrue((InOp(trade, "volume")))) {
// private trade returns num of contracts instead of base currency (as the order-related methods do)
var contractSize interface{} = this.SafeString(GetValue(market, "info"), "tradeMinQuantity")
var volume interface{} = this.SafeString(trade, "volume")
amount = Precise.StringMul(volume, contractSize)
}
return this.SafeTrade(map[string]interface{} {
"id": this.SafeStringN(trade, []interface{}{"id", "t"}),
"info": trade,
"timestamp": time,
"datetime": this.Iso8601(time),
"symbol": this.SafeSymbol(marketId, market, "-"),
"order": this.SafeString2(trade, "orderId", "i"),
"type": this.SafeStringLower(trade, "o"),
"side": this.ParseOrderSide(side),
"takerOrMaker": takeOrMaker,
"price": this.SafeStringN(trade, []interface{}{"price", "p", "tradePrice"}),
"amount": amount,
"cost": cost,
"fee": map[string]interface{} {
"cost": this.ParseNumber(Precise.StringAbs(this.SafeString2(trade, "commission", "n"))),
"currency": currencyCode,
},
}, market)
}
/**
* @method
* @name bingx#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://bingx-api.github.io/docs/#/spot/market-api.html#Query%20depth%20information
* @see https://bingx-api.github.io/docs/#/swapV2/market-api.html#Get%20Market%20Depth
* @see https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Query%20Depth%20Data
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/#/?id=order-book-structure} indexed by market symbols
*/
func (this *bingx) FetchOrderBook(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
limit := GetArg(optionalArgs, 0, nil)
_ = limit
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes14428 := (<-this.LoadMarkets())
PanicOnError(retRes14428)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "limit", limit)
}
var response interface{} = nil
var marketType interface{} = nil
marketTypeparamsVariable := this.HandleMarketTypeAndParams("fetchOrderBook", market, params);
marketType = GetValue(marketTypeparamsVariable,0);
params = GetValue(marketTypeparamsVariable,1)
if IsTrue(IsEqual(marketType, "spot")) {
response = (<-this.SpotV1PublicGetMarketDepth(this.Extend(request, params)))
PanicOnError(response)
} else {
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PublicGetMarketDepth(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PublicGetQuoteDepth(this.Extend(request, params)))
PanicOnError(response)
}
}
//
// spot
//
// {
// "code": 0,
// "data": {
// "bids": [
// [
// "26324.73",
// "0.37655"
// ],
// [
// "26324.71",
// "0.31888"
// ],
// ],
// "asks": [
// [
// "26340.30",
// "6.45221"
// ],
// [
// "26340.15",
// "6.73261"
// ],
// ]}
// }
//
// swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "T": 1683914263304,
// "bids": [
// [
// "26300.90000000",
// "30408.00000000"
// ],
// [
// "26300.80000000",
// "50906.00000000"
// ],
// ],
// "asks": [
// [
// "26301.00000000",
// "43616.00000000"
// ],
// [
// "26301.10000000",
// "49402.00000000"
// ],
// ]}
// }
//
var orderbook interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var timestamp interface{} = this.SafeInteger2(orderbook, "T", "ts")
ch <- this.ParseOrderBook(orderbook, GetValue(market, "symbol"), timestamp, "bids", "asks", 0, 1)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchFundingRate
* @description fetch the current funding rate
* @see https://bingx-api.github.io/docs/#/swapV2/market-api.html#Current%20Funding%20Rate
* @see https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Price%20&%20Current%20Funding%20Rate
* @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}
*/
func (this *bingx) FetchFundingRate(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes15358 := (<-this.LoadMarkets())
PanicOnError(retRes15358)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var response interface{} = nil
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PublicGetMarketPremiumIndex(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PublicGetQuotePremiumIndex(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// "code":0,
// "msg":"",
// "data":[
// {
// "symbol": "BTC-USDT",
// "markPrice": "16884.5",
// "indexPrice": "16886.9",
// "lastFundingRate": "0.0001",
// "nextFundingTime": 1672041600000
// },
// ...
// ]
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseFundingRate(data, market)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchFundingRates
* @description fetch the current funding rate for multiple symbols
* @see https://bingx-api.github.io/docs/#/swapV2/market-api.html#Current%20Funding%20Rate
* @param {string[]} [symbols] list of unified market symbols
* @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-structure}
*/
func (this *bingx) FetchFundingRates(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbols := GetArg(optionalArgs, 0, nil)
_ = symbols
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes15768 := (<-this.LoadMarkets())
PanicOnError(retRes15768)
symbols = this.MarketSymbols(symbols, "swap", true)
response:= (<-this.SwapV2PublicGetQuotePremiumIndex(this.Extend(params)))
PanicOnError(response)
var data interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseFundingRates(data, symbols)
return nil
}()
return ch
}
func (this *bingx) ParseFundingRate(contract interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "symbol": "BTC-USDT",
// "markPrice": "16884.5",
// "indexPrice": "16886.9",
// "lastFundingRate": "0.0001",
// "nextFundingTime": 1672041600000
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(contract, "symbol")
var nextFundingTimestamp interface{} = this.SafeInteger(contract, "nextFundingTime")
return map[string]interface{} {
"info": contract,
"symbol": this.SafeSymbol(marketId, market, "-", "swap"),
"markPrice": this.SafeNumber(contract, "markPrice"),
"indexPrice": this.SafeNumber(contract, "indexPrice"),
"interestRate": nil,
"estimatedSettlePrice": nil,
"timestamp": nil,
"datetime": nil,
"fundingRate": this.SafeNumber(contract, "lastFundingRate"),
"fundingTimestamp": nil,
"fundingDatetime": nil,
"nextFundingRate": nil,
"nextFundingTimestamp": nextFundingTimestamp,
"nextFundingDatetime": this.Iso8601(nextFundingTimestamp),
"previousFundingRate": nil,
"previousFundingTimestamp": nil,
"previousFundingDatetime": nil,
"interval": nil,
}
}
/**
* @method
* @name bingx#fetchFundingRateHistory
* @description fetches historical funding rate prices
* @see https://bingx-api.github.io/docs/#/swapV2/market-api.html#Funding%20Rate%20History
* @param {string} symbol unified symbol of the market to fetch the funding rate history for
* @param {int} [since] timestamp in ms of the earliest funding rate to fetch
* @param {int} [limit] the maximum amount of [funding rate structures]{@link https://docs.ccxt.com/#/?id=funding-rate-history-structure} to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest funding rate to fetch
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/#/?id=funding-rate-history-structure}
*/
func (this *bingx) FetchFundingRateHistory(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchFundingRateHistory() requires a symbol argument")))
}
retRes16348 := (<-this.LoadMarkets())
PanicOnError(retRes16348)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchFundingRateHistory", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes163819 := (<-this.FetchPaginatedCallDeterministic("fetchFundingRateHistory", symbol, since, limit, "8h", params))
PanicOnError(retRes163819)
ch <- retRes163819
return nil
}
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startTime", since)
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "limit", limit)
}
var until interface{} = this.SafeInteger2(params, "until", "startTime")
if IsTrue(!IsEqual(until, nil)) {
params = this.Omit(params, []interface{}{"until"})
AddElementToObject(request, "startTime", until)
}
response:= (<-this.SwapV2PublicGetQuoteFundingRate(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code":0,
// "msg":"",
// "data":[
// {
// "symbol": "BTC-USDT",
// "fundingRate": "0.0001",
// "fundingTime": 1585684800000
// },
// ...
// ]
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseFundingRateHistories(data, market, since, limit)
return nil
}()
return ch
}
func (this *bingx) ParseFundingRateHistory(contract interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "symbol": "BTC-USDT",
// "fundingRate": "0.0001",
// "fundingTime": 1585684800000
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var timestamp interface{} = this.SafeInteger(contract, "fundingTime")
return map[string]interface{} {
"info": contract,
"symbol": this.SafeSymbol(this.SafeString(contract, "symbol"), market, "-", "swap"),
"fundingRate": this.SafeNumber(contract, "fundingRate"),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
}
}
/**
* @method
* @name bingx#fetchOpenInterest
* @description retrieves the open interest of a trading pair
* @see https://bingx-api.github.io/docs/#/swapV2/market-api.html#Get%20Swap%20Open%20Positions
* @see https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Get%20Swap%20Open%20Positions
* @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}
*/
func (this *bingx) FetchOpenInterest(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes17038 := (<-this.LoadMarkets())
PanicOnError(retRes17038)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var response interface{} = nil
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PublicGetMarketOpenInterest(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PublicGetQuoteOpenInterest(this.Extend(request, params)))
PanicOnError(response)
}
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "openInterest": "3289641547.10",
// "symbol": "BTC-USDT",
// "time": 1672026617364
// }
// }
//
// inverse swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720328247986,
// "data": [
// {
// "symbol": "BTC-USD",
// "openInterest": "749.1160",
// "timestamp": 1720310400000
// }
// ]
// }
//
var result interface{} = map[string]interface{} {}
if IsTrue(GetValue(market, "inverse")) {
var data interface{} = this.SafeList(response, "data", []interface{}{})
result = this.SafeDict(data, 0, map[string]interface{} {})
} else {
result = this.SafeDict(response, "data", map[string]interface{} {})
}
ch <- this.ParseOpenInterest(result, market)
return nil
}()
return ch
}
func (this *bingx) ParseOpenInterest(interest interface{}, optionalArgs ...interface{}) interface{} {
//
// linear swap
//
// {
// "openInterest": "3289641547.10",
// "symbol": "BTC-USDT",
// "time": 1672026617364
// }
//
// inverse swap
//
// {
// "symbol": "BTC-USD",
// "openInterest": "749.1160",
// "timestamp": 1720310400000
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var timestamp interface{} = this.SafeInteger2(interest, "time", "timestamp")
var id interface{} = this.SafeString(interest, "symbol")
var symbol interface{} = this.SafeSymbol(id, market, "-", "swap")
var openInterest interface{} = this.SafeNumber(interest, "openInterest")
return this.SafeOpenInterest(map[string]interface{} {
"symbol": symbol,
"baseVolume": nil,
"quoteVolume": nil,
"openInterestAmount": nil,
"openInterestValue": openInterest,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"info": interest,
}, market)
}
/**
* @method
* @name bingx#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Get%20Ticker
* @see https://bingx-api.github.io/docs/#/en-us/spot/market-api.html#24-hour%20price%20changes
* @see https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Query%2024-Hour%20Price%20Change
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *bingx) FetchTicker(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes17988 := (<-this.LoadMarkets())
PanicOnError(retRes17988)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var response interface{} = nil
if IsTrue(GetValue(market, "spot")) {
response = (<-this.SpotV1PublicGetTicker24hr(this.Extend(request, params)))
PanicOnError(response)
} else {
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PublicGetMarketTicker(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PublicGetQuoteTicker(this.Extend(request, params)))
PanicOnError(response)
}
}
//
// spot and swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720647285296,
// "data": [
// {
// "symbol": "SOL-USD",
// "priceChange": "-2.418",
// "priceChangePercent": "-1.6900%",
// "lastPrice": "140.574",
// "lastQty": "1",
// "highPrice": "146.190",
// "lowPrice": "138.586",
// "volume": "1464648.00",
// "quoteVolume": "102928.12",
// "openPrice": "142.994",
// "closeTime": "1720647284976",
// "bidPrice": "140.573",
// "bidQty": "372",
// "askPrice": "140.577",
// "askQty": "58"
// }
// ]
// }
//
var data interface{} = this.SafeList(response, "data")
if IsTrue(!IsEqual(data, nil)) {
var first interface{} = this.SafeDict(data, 0, map[string]interface{} {})
ch <- this.ParseTicker(first, market)
return nil
}
var dataDict interface{} = this.SafeDict(response, "data", map[string]interface{} {})
ch <- this.ParseTicker(dataDict, market)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Get%20Ticker
* @see https://bingx-api.github.io/docs/#/en-us/spot/market-api.html#24-hour%20price%20changes
* @see https://bingx-api.github.io/docs/#/en-us/cswap/market-api.html#Query%2024-Hour%20Price%20Change
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *bingx) FetchTickers(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbols := GetArg(optionalArgs, 0, nil)
_ = symbols
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes18628 := (<-this.LoadMarkets())
PanicOnError(retRes18628)
var market interface{} = nil
if IsTrue(!IsEqual(symbols, nil)) {
symbols = this.MarketSymbols(symbols)
var firstSymbol interface{} = this.SafeString(symbols, 0)
if IsTrue(!IsEqual(firstSymbol, nil)) {
market = this.Market(firstSymbol)
}
}
var typeVar interface{} = nil
typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchTickers", market, params);
typeVar = GetValue(typeVarparamsVariable,0);
params = GetValue(typeVarparamsVariable,1)
var subType interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchTickers", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
var response interface{} = nil
if IsTrue(IsEqual(typeVar, "spot")) {
response = (<-this.SpotV1PublicGetTicker24hr(params))
PanicOnError(response)
} else {
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PublicGetMarketTicker(params))
PanicOnError(response)
} else {
response = (<-this.SwapV2PublicGetQuoteTicker(params))
PanicOnError(response)
}
}
//
// spot and swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720647285296,
// "data": [
// {
// "symbol": "SOL-USD",
// "priceChange": "-2.418",
// "priceChangePercent": "-1.6900%",
// "lastPrice": "140.574",
// "lastQty": "1",
// "highPrice": "146.190",
// "lowPrice": "138.586",
// "volume": "1464648.00",
// "quoteVolume": "102928.12",
// "openPrice": "142.994",
// "closeTime": "1720647284976",
// "bidPrice": "140.573",
// "bidQty": "372",
// "askPrice": "140.577",
// "askQty": "58"
// },
// ...
// ]
// }
//
var tickers interface{} = this.SafeList(response, "data")
ch <- this.ParseTickers(tickers, symbols)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchMarkPrice
* @description fetches mark prices for the market
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Mark%20Price%20and%20Funding%20Rate
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *bingx) FetchMarkPrice(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes19288 := (<-this.LoadMarkets())
PanicOnError(retRes19288)
var market interface{} = this.Market(symbol)
var subType interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchMarkPrice", market, params, "linear");
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var response interface{} = nil
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PublicGetMarketPremiumIndex(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PublicGetQuotePremiumIndex(this.Extend(request, params)))
PanicOnError(response)
}
if IsTrue(IsArray(GetValue(response, "data"))) {
ch <- this.ParseTicker(this.SafeDict(GetValue(response, "data"), 0, map[string]interface{} {}), market)
return nil
}
ch <- this.ParseTicker(GetValue(response, "data"), market)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchMarkPrices
* @description fetches mark prices for multiple markets
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/market-api.html#Mark%20Price%20and%20Funding%20Rate
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *bingx) FetchMarkPrices(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbols := GetArg(optionalArgs, 0, nil)
_ = symbols
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes19868 := (<-this.LoadMarkets())
PanicOnError(retRes19868)
var market interface{} = nil
if IsTrue(!IsEqual(symbols, nil)) {
symbols = this.MarketSymbols(symbols)
var firstSymbol interface{} = this.SafeString(symbols, 0)
if IsTrue(!IsEqual(firstSymbol, nil)) {
market = this.Market(firstSymbol)
}
}
var subType interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchMarkPrices", market, params, "linear");
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
var response interface{} = nil
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PublicGetMarketPremiumIndex(params))
PanicOnError(response)
} else {
response = (<-this.SwapV2PublicGetQuotePremiumIndex(params))
PanicOnError(response)
}
//
// spot and swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1720647285296,
// "data": [
// {
// "symbol": "SOL-USD",
// "priceChange": "-2.418",
// "priceChangePercent": "-1.6900%",
// "lastPrice": "140.574",
// "lastQty": "1",
// "highPrice": "146.190",
// "lowPrice": "138.586",
// "volume": "1464648.00",
// "quoteVolume": "102928.12",
// "openPrice": "142.994",
// "closeTime": "1720647284976",
// "bidPrice": "140.573",
// "bidQty": "372",
// "askPrice": "140.577",
// "askQty": "58"
// },
// ...
// ]
// }
//
var tickers interface{} = this.SafeList(response, "data")
ch <- this.ParseTickers(tickers, symbols)
return nil
}()
return ch
}
func (this *bingx) ParseTicker(ticker interface{}, optionalArgs ...interface{}) interface{} {
//
// mark price
// {
// "symbol": "string",
// "lastFundingRate": "string",
// "markPrice": "string",
// "indexPrice": "string",
// "nextFundingTime": "int64"
// }
//
// spot
// {
// "symbol": "BTC-USDT",
// "openPrice": "26032.08",
// "highPrice": "26178.86",
// "lowPrice": "25968.18",
// "lastPrice": "26113.60",
// "volume": "1161.79",
// "quoteVolume": "30288466.44",
// "openTime": "1693081020762",
// "closeTime": "1693167420762",
// added 2023-11-10:
// "bidPrice": 16726.0,
// "bidQty": 0.05,
// "askPrice": 16726.0,
// "askQty": 0.05,
// }
// swap
//
// {
// "symbol": "BTC-USDT",
// "priceChange": "52.5",
// "priceChangePercent": "0.31%", // they started to add the percent sign in value
// "lastPrice": "16880.5",
// "lastQty": "2.2238", // only present in swap!
// "highPrice": "16897.5",
// "lowPrice": "16726.0",
// "volume": "245870.1692",
// "quoteVolume": "4151395117.73",
// "openPrice": "16832.0",
// "openTime": 1672026667803,
// "closeTime": 1672026648425,
// added 2023-11-10:
// "bidPrice": 16726.0,
// "bidQty": 0.05,
// "askPrice": 16726.0,
// "askQty": 0.05,
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(ticker, "symbol")
var lastQty interface{} = this.SafeString(ticker, "lastQty")
// in spot markets, lastQty is not present
// it's (bad, but) the only way we can check the tickers origin
var typeVar interface{} = Ternary(IsTrue((IsEqual(lastQty, nil))), "spot", "swap")
market = this.SafeMarket(marketId, market, nil, typeVar)
var symbol interface{} = GetValue(market, "symbol")
var open interface{} = this.SafeString(ticker, "openPrice")
var high interface{} = this.SafeString(ticker, "highPrice")
var low interface{} = this.SafeString(ticker, "lowPrice")
var close interface{} = this.SafeString(ticker, "lastPrice")
var quoteVolume interface{} = this.SafeString(ticker, "quoteVolume")
var baseVolume interface{} = this.SafeString(ticker, "volume")
var percentage interface{} = this.SafeString(ticker, "priceChangePercent")
if IsTrue(!IsEqual(percentage, nil)) {
percentage = Replace(percentage, "%", "")
}
var change interface{} = this.SafeString(ticker, "priceChange")
var ts interface{} = this.SafeInteger(ticker, "closeTime")
if IsTrue(IsEqual(ts, 0)) {
ts = nil
}
var datetime interface{} = this.Iso8601(ts)
var bid interface{} = this.SafeString(ticker, "bidPrice")
var bidVolume interface{} = this.SafeString(ticker, "bidQty")
var ask interface{} = this.SafeString(ticker, "askPrice")
var askVolume interface{} = this.SafeString(ticker, "askQty")
return this.SafeTicker(map[string]interface{} {
"symbol": symbol,
"timestamp": ts,
"datetime": datetime,
"high": high,
"low": low,
"bid": bid,
"bidVolume": bidVolume,
"ask": ask,
"askVolume": askVolume,
"vwap": nil,
"open": open,
"close": close,
"last": nil,
"previousClose": nil,
"change": change,
"percentage": percentage,
"average": nil,
"baseVolume": baseVolume,
"quoteVolume": quoteVolume,
"markPrice": this.SafeString(ticker, "markPrice"),
"indexPrice": this.SafeString(ticker, "indexPrice"),
"info": ticker,
}, market)
}
/**
* @method
* @name bingx#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://bingx-api.github.io/docs/#/spot/trade-api.html#Query%20Assets
* @see https://bingx-api.github.io/docs/#/swapV2/account-api.html#Get%20Perpetual%20Swap%20Account%20Asset%20Information
* @see https://bingx-api.github.io/docs/#/standard/contract-interface.html#Query%20standard%20contract%20balance
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Account%20Assets
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.standard] whether to fetch standard contract balances
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/#/?id=balance-structure}
*/
func (this *bingx) FetchBalance(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes21528 := (<-this.LoadMarkets())
PanicOnError(retRes21528)
var response interface{} = nil
var standard interface{} = nil
standardparamsVariable := this.HandleOptionAndParams(params, "fetchBalance", "standard", false);
standard = GetValue(standardparamsVariable,0);
params = GetValue(standardparamsVariable,1)
var subType interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchBalance", nil, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
marketTypemarketTypeQueryVariable := this.HandleMarketTypeAndParams("fetchBalance", nil, params);
marketType := GetValue(marketTypemarketTypeQueryVariable,0);
marketTypeQuery := GetValue(marketTypemarketTypeQueryVariable,1)
if IsTrue(standard) {
response = (<-this.ContractV1PrivateGetBalance(marketTypeQuery))
PanicOnError(response)
} else if IsTrue(IsEqual(marketType, "spot")) {
response = (<-this.SpotV1PrivateGetAccountBalance(marketTypeQuery))
PanicOnError(response)
} else {
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PrivateGetUserBalance(marketTypeQuery))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateGetUserBalance(marketTypeQuery))
PanicOnError(response)
}
}
ch <- this.ParseBalance(response)
return nil
}()
return ch
}
func (this *bingx) ParseBalance(response interface{}) interface{} {
//
// standard
//
// {
// "code": 0,
// "timestamp": 1721192833454,
// "data": [
// {
// "asset": "USDT",
// "balance": "4.72644300000000000000",
// "crossWalletBalance": "4.72644300000000000000",
// "crossUnPnl": "0",
// "availableBalance": "4.72644300000000000000",
// "maxWithdrawAmount": "4.72644300000000000000",
// "marginAvailable": false,
// "updateTime": 1721192833443
// },
// ]
// }
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "debugMsg": "",
// "data": {
// "balances": [
// {
// "asset": "USDT",
// "free": "45.733046995800514",
// "locked": "0"
// },
// ]
// }
// }
//
// inverse swap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1721191833813,
// "data": [
// {
// "asset": "SOL",
// "balance": "0.35707951",
// "equity": "0.35791051",
// "unrealizedProfit": "0.00083099",
// "availableMargin": "0.35160653",
// "usedMargin": "0.00630397",
// "freezedMargin": "0",
// "shortUid": "12851936"
// }
// ]
// }
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "balance": {
// "userId": "1177064765068660742",
// "asset": "USDT",
// "balance": "51.5198",
// "equity": "50.5349",
// "unrealizedProfit": "-0.9849",
// "realisedProfit": "-0.2134",
// "availableMargin": "49.1428",
// "usedMargin": "1.3922",
// "freezedMargin": "0.0000",
// "shortUid": "12851936"
// }
// }
// }
//
var result interface{} = map[string]interface{} {
"info": response,
}
var standardAndInverseBalances interface{} = this.SafeList(response, "data")
var firstStandardOrInverse interface{} = this.SafeDict(standardAndInverseBalances, 0)
var isStandardOrInverse interface{} = !IsEqual(firstStandardOrInverse, nil)
var spotData interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var spotBalances interface{} = this.SafeList(spotData, "balances")
var firstSpot interface{} = this.SafeDict(spotBalances, 0)
var isSpot interface{} = !IsEqual(firstSpot, nil)
if IsTrue(isStandardOrInverse) {
for i := 0; IsLessThan(i, GetArrayLength(standardAndInverseBalances)); i++ {
var balance interface{} = GetValue(standardAndInverseBalances, i)
var currencyId interface{} = this.SafeString(balance, "asset")
var code interface{} = this.SafeCurrencyCode(currencyId)
var account interface{} = this.Account()
AddElementToObject(account, "free", this.SafeString2(balance, "availableMargin", "availableBalance"))
AddElementToObject(account, "used", this.SafeString(balance, "usedMargin"))
AddElementToObject(account, "total", this.SafeString(balance, "maxWithdrawAmount"))
AddElementToObject(result, code, account)
}
} else if IsTrue(isSpot) {
for i := 0; IsLessThan(i, GetArrayLength(spotBalances)); i++ {
var balance interface{} = GetValue(spotBalances, i)
var currencyId interface{} = this.SafeString(balance, "asset")
var code interface{} = this.SafeCurrencyCode(currencyId)
var account interface{} = this.Account()
AddElementToObject(account, "free", this.SafeString(balance, "free"))
AddElementToObject(account, "used", this.SafeString(balance, "locked"))
AddElementToObject(result, code, account)
}
} else {
var linearSwapData interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var linearSwapBalance interface{} = this.SafeDict(linearSwapData, "balance")
if IsTrue(linearSwapBalance) {
var currencyId interface{} = this.SafeString(linearSwapBalance, "asset")
var code interface{} = this.SafeCurrencyCode(currencyId)
var account interface{} = this.Account()
AddElementToObject(account, "free", this.SafeString(linearSwapBalance, "availableMargin"))
AddElementToObject(account, "used", this.SafeString(linearSwapBalance, "usedMargin"))
AddElementToObject(result, code, account)
}
}
return this.SafeBalance(result)
}
/**
* @method
* @name bingx#fetchPositionHistory
* @description fetches historical positions
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Position%20History
* @param {string} symbol unified contract symbol
* @param {int} [since] the earliest time in ms to fetch positions for
* @param {int} [limit] the maximum amount of records to fetch
* @param {object} [params] extra parameters specific to the exchange api endpoint
* @param {int} [params.until] the latest time in ms to fetch positions for
* @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *bingx) FetchPositionHistory(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
since := GetArg(optionalArgs, 0, nil)
_ = since
limit := GetArg(optionalArgs, 1, nil)
_ = limit
params := GetArg(optionalArgs, 2, map[string]interface{} {})
_ = params
retRes23828 := (<-this.LoadMarkets())
PanicOnError(retRes23828)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "pageSize", limit)
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startTs", since)
}
requestparamsVariable := this.HandleUntilOption("endTs", request, params);
request = GetValue(requestparamsVariable,0);
params = GetValue(requestparamsVariable,1)
var response interface{} = nil
if IsTrue(GetValue(market, "linear")) {
response = (<-this.SwapV1PrivateGetTradePositionHistory(this.Extend(request, params)))
PanicOnError(response)
} else {
panic(NotSupported(Add(this.Id, " fetchPositionHistory() is not supported for inverse swap positions")))
}
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "positionHistory": [
// {
// "positionId": "1861675561156571136",
// "symbol": "LTC-USDT",
// "isolated": false,
// "positionSide": "LONG",
// "openTime": 1732693017000,
// "updateTime": 1733310292000,
// "avgPrice": "95.18",
// "avgClosePrice": "129.48",
// "realisedProfit": "102.89",
// "netProfit": "99.63",
// "positionAmt": "30.0",
// "closePositionAmt": "30.0",
// "leverage": 6,
// "closeAllPositions": true,
// "positionCommission": "-0.33699650000000003",
// "totalFunding": "-2.921461693902908"
// },
// ]
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var records interface{} = this.SafeList(data, "positionHistory", []interface{}{})
var positions interface{} = this.ParsePositions(records)
ch <- this.FilterBySymbolSinceLimit(positions, symbol, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchPositions
* @description fetch all open positions
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/account-api.html#Query%20position%20data
* @see https://bingx-api.github.io/docs/#/en-us/standard/contract-interface.html#position
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20warehouse
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.standard] whether to fetch standard contract positions
* @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *bingx) FetchPositions(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbols := GetArg(optionalArgs, 0, nil)
_ = symbols
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes24478 := (<-this.LoadMarkets())
PanicOnError(retRes24478)
symbols = this.MarketSymbols(symbols)
var standard interface{} = nil
standardparamsVariable := this.HandleOptionAndParams(params, "fetchPositions", "standard", false);
standard = GetValue(standardparamsVariable,0);
params = GetValue(standardparamsVariable,1)
var response interface{} = nil
if IsTrue(standard) {
response = (<-this.ContractV1PrivateGetAllPosition(params))
PanicOnError(response)
} else {
var market interface{} = nil
if IsTrue(!IsEqual(symbols, nil)) {
symbols = this.MarketSymbols(symbols)
var firstSymbol interface{} = this.SafeString(symbols, 0)
if IsTrue(!IsEqual(firstSymbol, nil)) {
market = this.Market(firstSymbol)
}
}
var subType interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchPositions", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PrivateGetUserPositions(params))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateGetUserPositions(params))
PanicOnError(response)
}
}
var positions interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParsePositions(positions, symbols)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchPosition
* @description fetch data on a single open contract trade position
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/account-api.html#Query%20position%20data
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20warehouse
* @param {string} symbol unified market symbol of the market the position is held in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [position structure]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *bingx) FetchPosition(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes25438 := (<-this.LoadMarkets())
PanicOnError(retRes25438)
var market interface{} = this.Market(symbol)
if !IsTrue(GetValue(market, "swap")) {
panic(BadRequest(Add(this.Id, " fetchPosition() supports swap markets only")))
}
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var response interface{} = nil
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PrivateGetUserPositions(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateGetUserPositions(this.Extend(request, params)))
PanicOnError(response)
}
var data interface{} = this.SafeList(response, "data", []interface{}{})
var first interface{} = this.SafeDict(data, 0, map[string]interface{} {})
ch <- this.ParsePosition(first, market)
return nil
}()
return ch
}
func (this *bingx) ParsePosition(position interface{}, optionalArgs ...interface{}) interface{} {
//
// inverse swap
//
// {
// "symbol": "SOL-USD",
// "positionId": "1813080351385337856",
// "positionSide": "LONG",
// "isolated": false,
// "positionAmt": "1",
// "availableAmt": "1",
// "unrealizedProfit": "-0.00009074",
// "initialMargin": "0.00630398",
// "liquidationPrice": 23.968303426677032,
// "avgPrice": "158.63",
// "leverage": 10,
// "markPrice": "158.402",
// "riskRate": "0.00123783",
// "maxMarginReduction": "0",
// "updateTime": 1721107015848
// }
//
// linear swap
//
// {
// "positionId": "1792480725958881280",
// "symbol": "LTC-USDT",
// "currency": "USDT",
// "positionAmt": "0.1",
// "availableAmt": "0.1",
// "positionSide": "LONG",
// "isolated": false,
// "avgPrice": "83.53",
// "initialMargin": "1.3922",
// "margin": "0.3528",
// "leverage": 6,
// "unrealizedProfit": "-1.0393",
// "realisedProfit": "-0.2119",
// "liquidationPrice": 0,
// "pnlRatio": "-0.7465",
// "maxMarginReduction": "0.0000",
// "riskRate": "0.0008",
// "markPrice": "73.14",
// "positionValue": "7.3136",
// "onlyOnePosition": true,
// "updateTime": 1721088016688
// }
//
// standard position
//
// {
// "currentPrice": "82.91",
// "symbol": "LTC/USDT",
// "initialMargin": "5.00000000000000000000",
// "unrealizedProfit": "-0.26464500",
// "leverage": "20.000000000",
// "isolated": true,
// "entryPrice": "83.13",
// "positionSide": "LONG",
// "positionAmt": "1.20365912",
// }
//
// linear swap fetchPositionHistory
//
// {
// "positionId": "1861675561156571136",
// "symbol": "LTC-USDT",
// "isolated": false,
// "positionSide": "LONG",
// "openTime": 1732693017000,
// "updateTime": 1733310292000,
// "avgPrice": "95.18",
// "avgClosePrice": "129.48",
// "realisedProfit": "102.89",
// "netProfit": "99.63",
// "positionAmt": "30.0",
// "closePositionAmt": "30.0",
// "leverage": 6,
// "closeAllPositions": true,
// "positionCommission": "-0.33699650000000003",
// "totalFunding": "-2.921461693902908"
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(position, "symbol", "")
marketId = Replace(marketId, "/", "-") // standard return different format
var isolated interface{} = this.SafeBool(position, "isolated")
var marginMode interface{} = nil
if IsTrue(!IsEqual(isolated, nil)) {
marginMode = Ternary(IsTrue(isolated), "isolated", "cross")
}
var timestamp interface{} = this.SafeInteger(position, "openTime")
return this.SafePosition(map[string]interface{} {
"info": position,
"id": this.SafeString(position, "positionId"),
"symbol": this.SafeSymbol(marketId, market, "-", "swap"),
"notional": this.SafeNumber(position, "positionValue"),
"marginMode": marginMode,
"liquidationPrice": nil,
"entryPrice": this.SafeNumber2(position, "avgPrice", "entryPrice"),
"unrealizedPnl": this.SafeNumber(position, "unrealizedProfit"),
"realizedPnl": this.SafeNumber(position, "realisedProfit"),
"percentage": nil,
"contracts": this.SafeNumber(position, "positionAmt"),
"contractSize": nil,
"markPrice": this.SafeNumber(position, "markPrice"),
"lastPrice": nil,
"side": this.SafeStringLower(position, "positionSide"),
"hedged": nil,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"lastUpdateTimestamp": this.SafeInteger(position, "updateTime"),
"maintenanceMargin": nil,
"maintenanceMarginPercentage": nil,
"collateral": nil,
"initialMargin": this.SafeNumber(position, "initialMargin"),
"initialMarginPercentage": nil,
"leverage": this.SafeNumber(position, "leverage"),
"marginRatio": nil,
"stopLossPrice": nil,
"takeProfitPrice": nil,
})
}
/**
* @method
* @name bingx#createMarketOrderWithCost
* @description create a market order by providing the symbol, side and cost
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} side 'buy' or 'sell'
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) CreateMarketOrderWithCost(symbol interface{}, side interface{}, cost interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
AddElementToObject(params, "quoteOrderQty", cost)
retRes275415 := (<-this.CreateOrder(symbol, "market", side, cost, nil, params))
PanicOnError(retRes275415)
ch <- retRes275415
return nil
}()
return ch
}
/**
* @method
* @name bingx#createMarketBuyOrderWithCost
* @description create a market buy order by providing the symbol and cost
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) CreateMarketBuyOrderWithCost(symbol interface{}, cost interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
AddElementToObject(params, "quoteOrderQty", cost)
retRes276815 := (<-this.CreateOrder(symbol, "market", "buy", cost, nil, params))
PanicOnError(retRes276815)
ch <- retRes276815
return nil
}()
return ch
}
/**
* @method
* @name bingx#createMarketSellOrderWithCost
* @description create a market sell order by providing the symbol and cost
* @param {string} symbol unified symbol of the market to create an order in
* @param {float} cost how much you want to trade in units of the quote currency
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) CreateMarketSellOrderWithCost(symbol interface{}, cost interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
AddElementToObject(params, "quoteOrderQty", cost)
retRes278215 := (<-this.CreateOrder(symbol, "market", "sell", cost, nil, params))
PanicOnError(retRes278215)
ch <- retRes278215
return nil
}()
return ch
}
func (this *bingx) CreateOrderRequest(symbol interface{}, typeVar interface{}, side interface{}, amount interface{}, optionalArgs ...interface{}) interface{} {
/**
* @method
* @ignore
* @name bingx#createOrderRequest
* @description helper function to build request
* @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 you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} request to be sent to the exchange
*/
price := GetArg(optionalArgs, 0, nil)
_ = price
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
var market interface{} = this.Market(symbol)
var postOnly interface{} = nil
var marketType interface{} = nil
marketTypeparamsVariable := this.HandleMarketTypeAndParams("createOrder", market, params);
marketType = GetValue(marketTypeparamsVariable,0);
params = GetValue(marketTypeparamsVariable,1)
typeVar = ToUpper(typeVar)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"type": typeVar,
"side": ToUpper(side),
}
var isMarketOrder interface{} = IsEqual(typeVar, "MARKET")
var isSpot interface{} = IsEqual(marketType, "spot")
var isTwapOrder interface{} = IsEqual(typeVar, "TWAP")
if IsTrue(IsTrue(isTwapOrder) && IsTrue(isSpot)) {
panic(BadSymbol(Add(this.Id, " createOrder() twap order supports swap contracts only")))
}
var stopLossPrice interface{} = this.SafeString(params, "stopLossPrice")
var takeProfitPrice interface{} = this.SafeString(params, "takeProfitPrice")
var triggerPrice interface{} = this.SafeString2(params, "stopPrice", "triggerPrice")
var isTriggerOrder interface{} = !IsEqual(triggerPrice, nil)
var isStopLossPriceOrder interface{} = !IsEqual(stopLossPrice, nil)
var isTakeProfitPriceOrder interface{} = !IsEqual(takeProfitPrice, nil)
var exchangeClientOrderId interface{} = Ternary(IsTrue(isSpot), "newClientOrderId", "clientOrderID")
var clientOrderId interface{} = this.SafeString2(params, exchangeClientOrderId, "clientOrderId")
if IsTrue(!IsEqual(clientOrderId, nil)) {
AddElementToObject(request, exchangeClientOrderId, clientOrderId)
}
var timeInForce interface{} = this.SafeStringUpper(params, "timeInForce")
postOnlyparamsVariable := this.HandlePostOnly(isMarketOrder, IsEqual(timeInForce, "PostOnly"), params);
postOnly = GetValue(postOnlyparamsVariable,0);
params = GetValue(postOnlyparamsVariable,1)
if IsTrue(IsTrue(postOnly) || IsTrue((IsEqual(timeInForce, "PostOnly")))) {
AddElementToObject(request, "timeInForce", "PostOnly")
} else if IsTrue(IsEqual(timeInForce, "IOC")) {
AddElementToObject(request, "timeInForce", "IOC")
} else if IsTrue(IsEqual(timeInForce, "GTC")) {
AddElementToObject(request, "timeInForce", "GTC")
}
if IsTrue(isSpot) {
var cost interface{} = this.SafeString2(params, "cost", "quoteOrderQty")
params = this.Omit(params, "cost")
if IsTrue(!IsEqual(cost, nil)) {
AddElementToObject(request, "quoteOrderQty", this.ParseToNumeric(this.CostToPrecision(symbol, cost)))
} else {
if IsTrue(IsTrue(isMarketOrder) && IsTrue((!IsEqual(price, nil)))) {
// keep the legacy behavior, to avoid breaking the old spot-market-buying code
var calculatedCost interface{} = Precise.StringMul(this.NumberToString(amount), this.NumberToString(price))
AddElementToObject(request, "quoteOrderQty", this.ParseToNumeric(calculatedCost))
} else {
AddElementToObject(request, "quantity", this.ParseToNumeric(this.AmountToPrecision(symbol, amount)))
}
}
if !IsTrue(isMarketOrder) {
AddElementToObject(request, "price", this.ParseToNumeric(this.PriceToPrecision(symbol, price)))
}
if IsTrue(!IsEqual(triggerPrice, nil)) {
if IsTrue(IsTrue(isMarketOrder) && IsTrue(IsEqual(this.SafeString(request, "quoteOrderQty"), nil))) {
panic(ArgumentsRequired(Add(this.Id, " createOrder() requires the cost parameter (or the amount + price) for placing spot market-buy trigger orders")))
}
AddElementToObject(request, "stopPrice", this.PriceToPrecision(symbol, triggerPrice))
if IsTrue(IsEqual(typeVar, "LIMIT")) {
AddElementToObject(request, "type", "TRIGGER_LIMIT")
} else if IsTrue(IsEqual(typeVar, "MARKET")) {
AddElementToObject(request, "type", "TRIGGER_MARKET")
}
} else if IsTrue(IsTrue((!IsEqual(stopLossPrice, nil))) || IsTrue((!IsEqual(takeProfitPrice, nil)))) {
var stopTakePrice interface{} = Ternary(IsTrue((!IsEqual(stopLossPrice, nil))), stopLossPrice, takeProfitPrice)
if IsTrue(IsEqual(typeVar, "LIMIT")) {
AddElementToObject(request, "type", "TAKE_STOP_LIMIT")
} else if IsTrue(IsEqual(typeVar, "MARKET")) {
AddElementToObject(request, "type", "TAKE_STOP_MARKET")
}
AddElementToObject(request, "stopPrice", this.ParseToNumeric(this.PriceToPrecision(symbol, stopTakePrice)))
}
} else {
if IsTrue(isTwapOrder) {
var twapRequest interface{} = map[string]interface{} {
"symbol": GetValue(request, "symbol"),
"side": GetValue(request, "side"),
"positionSide": Ternary(IsTrue((IsEqual(side, "buy"))), "LONG", "SHORT"),
"triggerPrice": this.ParseToNumeric(this.PriceToPrecision(symbol, triggerPrice)),
"totalAmount": this.ParseToNumeric(this.AmountToPrecision(symbol, amount)),
}
// {
// "symbol": "LTC-USDT",
// "side": "BUY",
// "positionSide": "LONG",
// "priceType": "constant",
// "priceVariance": "10",
// "triggerPrice": "120",
// "interval": 8,
// "amountPerOrder": "0.5",
// "totalAmount": "1"
// }
return this.Extend(twapRequest, params)
}
if IsTrue(IsEqual(timeInForce, "FOK")) {
AddElementToObject(request, "timeInForce", "FOK")
}
var trailingAmount interface{} = this.SafeString(params, "trailingAmount")
var trailingPercent interface{} = this.SafeString2(params, "trailingPercent", "priceRate")
var trailingType interface{} = this.SafeString(params, "trailingType", "TRAILING_STOP_MARKET")
var isTrailingAmountOrder interface{} = !IsEqual(trailingAmount, nil)
var isTrailingPercentOrder interface{} = !IsEqual(trailingPercent, nil)
var isTrailing interface{} = IsTrue(isTrailingAmountOrder) || IsTrue(isTrailingPercentOrder)
var stopLoss interface{} = this.SafeValue(params, "stopLoss")
var takeProfit interface{} = this.SafeValue(params, "takeProfit")
var isStopLoss interface{} = !IsEqual(stopLoss, nil)
var isTakeProfit interface{} = !IsEqual(takeProfit, nil)
if IsTrue(IsTrue((IsTrue(IsTrue(IsTrue((IsEqual(typeVar, "LIMIT"))) || IsTrue((IsEqual(typeVar, "TRIGGER_LIMIT")))) || IsTrue((IsEqual(typeVar, "STOP")))) || IsTrue((IsEqual(typeVar, "TAKE_PROFIT"))))) && !IsTrue(isTrailing)) {
AddElementToObject(request, "price", this.ParseToNumeric(this.PriceToPrecision(symbol, price)))
}
var reduceOnly interface{} = this.SafeBool(params, "reduceOnly", false)
if IsTrue(isTriggerOrder) {
AddElementToObject(request, "stopPrice", this.ParseToNumeric(this.PriceToPrecision(symbol, triggerPrice)))
if IsTrue(IsTrue(isMarketOrder) || IsTrue((IsEqual(typeVar, "TRIGGER_MARKET")))) {
AddElementToObject(request, "type", "TRIGGER_MARKET")
} else if IsTrue(IsTrue((IsEqual(typeVar, "LIMIT"))) || IsTrue((IsEqual(typeVar, "TRIGGER_LIMIT")))) {
AddElementToObject(request, "type", "TRIGGER_LIMIT")
}
} else if IsTrue(IsTrue(isStopLossPriceOrder) || IsTrue(isTakeProfitPriceOrder)) {
// This can be used to set the stop loss and take profit, but the position needs to be opened first
reduceOnly = true
if IsTrue(isStopLossPriceOrder) {
AddElementToObject(request, "stopPrice", this.ParseToNumeric(this.PriceToPrecision(symbol, stopLossPrice)))
if IsTrue(IsTrue(isMarketOrder) || IsTrue((IsEqual(typeVar, "STOP_MARKET")))) {
AddElementToObject(request, "type", "STOP_MARKET")
} else if IsTrue(IsTrue((IsEqual(typeVar, "LIMIT"))) || IsTrue((IsEqual(typeVar, "STOP")))) {
AddElementToObject(request, "type", "STOP")
}
} else if IsTrue(isTakeProfitPriceOrder) {
AddElementToObject(request, "stopPrice", this.ParseToNumeric(this.PriceToPrecision(symbol, takeProfitPrice)))
if IsTrue(IsTrue(isMarketOrder) || IsTrue((IsEqual(typeVar, "TAKE_PROFIT_MARKET")))) {
AddElementToObject(request, "type", "TAKE_PROFIT_MARKET")
} else if IsTrue(IsTrue((IsEqual(typeVar, "LIMIT"))) || IsTrue((IsEqual(typeVar, "TAKE_PROFIT")))) {
AddElementToObject(request, "type", "TAKE_PROFIT")
}
}
} else if IsTrue(isTrailing) {
AddElementToObject(request, "type", trailingType)
if IsTrue(isTrailingAmountOrder) {
AddElementToObject(request, "price", this.ParseToNumeric(trailingAmount))
} else if IsTrue(isTrailingPercentOrder) {
var requestTrailingPercent interface{} = Precise.StringDiv(trailingPercent, "100")
AddElementToObject(request, "priceRate", this.ParseToNumeric(requestTrailingPercent))
}
}
if IsTrue(IsTrue(isStopLoss) || IsTrue(isTakeProfit)) {
var stringifiedAmount interface{} = this.NumberToString(amount)
if IsTrue(isStopLoss) {
var slTriggerPrice interface{} = this.SafeString2(stopLoss, "triggerPrice", "stopPrice", stopLoss)
var slWorkingType interface{} = this.SafeString(stopLoss, "workingType", "MARK_PRICE")
var slType interface{} = this.SafeString(stopLoss, "type", "STOP_MARKET")
var slRequest interface{} = map[string]interface{} {
"stopPrice": this.ParseToNumeric(this.PriceToPrecision(symbol, slTriggerPrice)),
"workingType": slWorkingType,
"type": slType,
}
var slPrice interface{} = this.SafeString(stopLoss, "price")
if IsTrue(!IsEqual(slPrice, nil)) {
AddElementToObject(slRequest, "price", this.ParseToNumeric(this.PriceToPrecision(symbol, slPrice)))
}
var slQuantity interface{} = this.SafeString(stopLoss, "quantity", stringifiedAmount)
AddElementToObject(slRequest, "quantity", this.ParseToNumeric(this.AmountToPrecision(symbol, slQuantity)))
AddElementToObject(request, "stopLoss", this.Json(slRequest))
}
if IsTrue(isTakeProfit) {
var tkTriggerPrice interface{} = this.SafeString2(takeProfit, "triggerPrice", "stopPrice", takeProfit)
var tkWorkingType interface{} = this.SafeString(takeProfit, "workingType", "MARK_PRICE")
var tpType interface{} = this.SafeString(takeProfit, "type", "TAKE_PROFIT_MARKET")
var tpRequest interface{} = map[string]interface{} {
"stopPrice": this.ParseToNumeric(this.PriceToPrecision(symbol, tkTriggerPrice)),
"workingType": tkWorkingType,
"type": tpType,
}
var slPrice interface{} = this.SafeString(takeProfit, "price")
if IsTrue(!IsEqual(slPrice, nil)) {
AddElementToObject(tpRequest, "price", this.ParseToNumeric(this.PriceToPrecision(symbol, slPrice)))
}
var tkQuantity interface{} = this.SafeString(takeProfit, "quantity", stringifiedAmount)
AddElementToObject(tpRequest, "quantity", this.ParseToNumeric(this.AmountToPrecision(symbol, tkQuantity)))
AddElementToObject(request, "takeProfit", this.Json(tpRequest))
}
}
var positionSide interface{} = nil
var hedged interface{} = this.SafeBool(params, "hedged", false)
if IsTrue(hedged) {
params = this.Omit(params, "reduceOnly")
if IsTrue(reduceOnly) {
positionSide = Ternary(IsTrue((IsEqual(side, "buy"))), "SHORT", "LONG")
} else {
positionSide = Ternary(IsTrue((IsEqual(side, "buy"))), "LONG", "SHORT")
}
} else {
positionSide = "BOTH"
}
AddElementToObject(request, "positionSide", positionSide)
var amountReq interface{} = amount
if !IsTrue(GetValue(market, "inverse")) {
amountReq = this.ParseToNumeric(this.AmountToPrecision(symbol, amount))
}
AddElementToObject(request, "quantity", amountReq) // precision not available for inverse contracts
}
params = this.Omit(params, []interface{}{"hedged", "triggerPrice", "stopLossPrice", "takeProfitPrice", "trailingAmount", "trailingPercent", "trailingType", "takeProfit", "stopLoss", "clientOrderId"})
return this.Extend(request, params)
}
/**
* @method
* @name bingx#createOrder
* @description create a trade order
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Trade%20order
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Create%20an%20Order
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Trade%20order
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Place%20TWAP%20Order
* @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 you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] a unique id for the order
* @param {bool} [params.postOnly] true to place a post only order
* @param {string} [params.timeInForce] spot supports 'PO', 'GTC' and 'IOC', swap supports 'PO', 'GTC', 'IOC' and 'FOK'
* @param {bool} [params.reduceOnly] *swap only* true or false whether the order is reduce only
* @param {float} [params.triggerPrice] triggerPrice at which the attached take profit / stop loss order will be triggered
* @param {float} [params.stopLossPrice] stop loss trigger price
* @param {float} [params.takeProfitPrice] take profit trigger price
* @param {float} [params.cost] the quote quantity that can be used as an alternative for the amount
* @param {float} [params.trailingAmount] *swap only* the quote amount to trail away from the current market price
* @param {float} [params.trailingPercent] *swap only* the percent to trail away from the current market price
* @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
* @param {boolean} [params.test] *swap only* whether to use the test endpoint or not, default is false
* @param {string} [params.positionSide] *contracts only* "BOTH" for one way mode, "LONG" for buy side of hedged mode, "SHORT" for sell side of hedged mode
* @param {boolean} [params.hedged] *swap only* whether the order is in hedged mode or one way mode
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) CreateOrder(symbol interface{}, typeVar interface{}, side interface{}, amount interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
price := GetArg(optionalArgs, 0, nil)
_ = price
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes30388 := (<-this.LoadMarkets())
PanicOnError(retRes30388)
var market interface{} = this.Market(symbol)
var test interface{} = this.SafeBool(params, "test", false)
params = this.Omit(params, "test")
var request interface{} = this.CreateOrderRequest(symbol, typeVar, side, amount, price, params)
var response interface{} = nil
if IsTrue(GetValue(market, "swap")) {
if IsTrue(test) {
response = (<-this.SwapV2PrivatePostTradeOrderTest(request))
PanicOnError(response)
} else if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PrivatePostTradeOrder(request))
PanicOnError(response)
} else if IsTrue(IsEqual(typeVar, "twap")) {
response = (<-this.SwapV1PrivatePostTwapOrder(request))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivatePostTradeOrder(request))
PanicOnError(response)
}
} else {
response = (<-this.SpotV1PrivatePostTradeOrder(request))
PanicOnError(response)
}
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "symbol": "XRP-USDT",
// "orderId": 1514090846268424192,
// "transactTime": 1649822362855,
// "price": "0.5",
// "origQty": "10",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY"
// }
// }
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "order": {
// "symbol": "BTC-USDT",
// "orderId": 1709036527545438208,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "TRIGGER_LIMIT",
// "clientOrderID": "",
// "workingType": ""
// }
// }
// }
//
// inverse swap
//
// {
// "orderId": 1809841379603398656,
// "symbol": "SOL-USD",
// "positionSide": "LONG",
// "side": "BUY",
// "type": "LIMIT",
// "price": 100,
// "quantity": 1,
// "stopPrice": 0,
// "workingType": "",
// "timeInForce": ""
// }
//
// twap order
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1732693774386,
// "data": {
// "mainOrderId": "4633860139993029715"
// }
// }
//
if IsTrue(IsString(response)) {
// broken api engine : order-ids are too long numbers (i.e. 1742930526912864656)
// and JSON.parse can not handle them in JS, so we have to use .parseJson
// however, when order has an attached SL/TP, their value types need extra parsing
response = this.FixStringifiedJsonMembers(response)
response = this.ParseJson(response)
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var result interface{} = map[string]interface{} {}
if IsTrue(GetValue(market, "swap")) {
if IsTrue(GetValue(market, "inverse")) {
result = response
} else {
result = this.SafeDict(data, "order", data)
}
} else {
result = data
}
ch <- this.ParseOrder(result, market)
return nil
}()
return ch
}
/**
* @method
* @name bingx#createOrders
* @description create a list of trade orders
* @see https://bingx-api.github.io/docs/#/spot/trade-api.html#Batch%20Placing%20Orders
* @see https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Bulk%20order
* @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
* @param {boolean} [params.sync] *spot only* if true, multiple orders are ordered serially and all orders do not require the same symbol/side/type
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) CreateOrders(orders interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes31548 := (<-this.LoadMarkets())
PanicOnError(retRes31548)
var ordersRequests interface{} = []interface{}{}
var marketIds interface{} = []interface{}{}
for i := 0; IsLessThan(i, GetArrayLength(orders)); i++ {
var rawOrder interface{} = GetValue(orders, i)
var marketId interface{} = this.SafeString(rawOrder, "symbol")
var typeVar interface{} = this.SafeString(rawOrder, "type")
AppendToArray(&marketIds,marketId)
var side interface{} = this.SafeString(rawOrder, "side")
var amount interface{} = this.SafeNumber(rawOrder, "amount")
var price interface{} = this.SafeNumber(rawOrder, "price")
var orderParams interface{} = this.SafeDict(rawOrder, "params", map[string]interface{} {})
var orderRequest interface{} = this.CreateOrderRequest(marketId, typeVar, side, amount, price, orderParams)
AppendToArray(&ordersRequests,orderRequest)
}
var symbols interface{} = this.MarketSymbols(marketIds, nil, false, true, true)
var symbolsLength interface{} = GetArrayLength(symbols)
var market interface{} = this.Market(GetValue(symbols, 0))
var request interface{} = map[string]interface{} {}
var response interface{} = nil
if IsTrue(GetValue(market, "swap")) {
if IsTrue(IsGreaterThan(symbolsLength, 5)) {
panic(InvalidOrder(Add(this.Id, " createOrders() can not create more than 5 orders at once for swap markets")))
}
AddElementToObject(request, "batchOrders", this.Json(ordersRequests))
response = (<-this.SwapV2PrivatePostTradeBatchOrders(request))
PanicOnError(response)
} else {
var sync interface{} = this.SafeBool(params, "sync", false)
if IsTrue(sync) {
AddElementToObject(request, "sync", true)
}
AddElementToObject(request, "data", this.Json(ordersRequests))
response = (<-this.SpotV1PrivatePostTradeBatchOrders(request))
PanicOnError(response)
}
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "debugMsg": "",
// "data": {
// "orders": [
// {
// "symbol": "BTC-USDT",
// "orderId": 1720661389564968960,
// "transactTime": 1699072618272,
// "price": "25000",
// "origQty": "0.0002",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY"
// },
// ]
// }
// }
//
// swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "BTC-USDT",
// "orderId": 1720657081994006528,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "LIMIT",
// "clientOrderID": "",
// "workingType": ""
// },
// ]
// }
// }
//
if IsTrue(IsString(response)) {
// broken api engine : order-ids are too long numbers (i.e. 1742930526912864656)
// and JSON.parse can not handle them in JS, so we have to use .parseJson
// however, when order has an attached SL/TP, their value types need extra parsing
response = this.FixStringifiedJsonMembers(response)
response = this.ParseJson(response)
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var result interface{} = this.SafeList(data, "orders", []interface{}{})
ch <- this.ParseOrders(result, market)
return nil
}()
return ch
}
func (this *bingx) ParseOrderSide(side interface{}) interface{} {
var sides interface{} = map[string]interface{} {
"BUY": "buy",
"SELL": "sell",
"SHORT": "sell",
"LONG": "buy",
"ask": "sell",
"bid": "buy",
}
return this.SafeString(sides, side, side)
}
func (this *bingx) ParseOrderType(typeVar interface{}) interface{} {
var types interface{} = map[string]interface{} {
"trigger_market": "market",
"trigger_limit": "limit",
"stop_limit": "limit",
"stop_market": "market",
"take_profit_market": "market",
"stop": "limit",
}
return this.SafeString(types, typeVar, typeVar)
}
func (this *bingx) ParseOrder(order interface{}, optionalArgs ...interface{}) interface{} {
//
// spot
// createOrder, createOrders, cancelOrder
//
// {
// "symbol": "XRP-USDT",
// "orderId": 1514090846268424192,
// "transactTime": 1649822362855,
// "price": "0.5",
// "origQty": "10",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY"
// }
//
// fetchOrder
//
// {
// "symbol": "ETH-USDT",
// "orderId": "1660602123001266176",
// "price": "1700",
// "origQty": "0.003",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY",
// "time": "1684753373276",
// "updateTime": "1684753373276",
// "origQuoteOrderQty": "0",
// "fee": "0",
// "feeAsset": "ETH"
// }
//
// fetchOpenOrders, fetchClosedOrders
//
// {
// "symbol": "XRP-USDT",
// "orderId": 1514073325788200960,
// "price": "0.5",
// "StopPrice": "0",
// "origQty": "20",
// "executedQty": "10",
// "cummulativeQuoteQty": "5",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY",
// "time": 1649818185647,
// "updateTime": 1649818185647,
// "origQuoteOrderQty": "0"
// "fee": "-0.01"
// }
//
//
// linear swap
// createOrder, createOrders
//
// {
// "symbol": "BTC-USDT",
// "orderId": 1590973236294713344,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "LIMIT"
// }
//
// inverse swap createOrder
//
// {
// "orderId": 1809841379603398656,
// "symbol": "SOL-USD",
// "positionSide": "LONG",
// "side": "BUY",
// "type": "LIMIT",
// "price": 100,
// "quantity": 1,
// "stopPrice": 0,
// "workingType": "",
// "timeInForce": ""
// }
//
// fetchOrder, fetchOpenOrders, fetchClosedOrders
//
// {
// "symbol": "BTC-USDT",
// "orderId": 1709036527545438208,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "TRIGGER_LIMIT",
// "origQty": "0.0010",
// "price": "22000.0",
// "executedQty": "0.0000",
// "avgPrice": "0.0",
// "cumQuote": "",
// "stopPrice": "23000.0",
// "profit": "",
// "commission": "",
// "status": "NEW",
// "time": 1696301035187,
// "updateTime": 1696301035187,
// "clientOrderId": "",
// "leverage": "",
// "takeProfit": "",
// "stopLoss": "",
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": "MARK_PRICE"
// }
// with tp and sl
// {
// orderId: 1741440894764281900,
// symbol: 'LTC-USDT',
// positionSide: 'LONG',
// side: 'BUY',
// type: 'MARKET',
// price: 0,
// quantity: 1,
// stopPrice: 0,
// workingType: 'MARK_PRICE',
// clientOrderID: '',
// timeInForce: 'GTC',
// priceRate: 0,
// stopLoss: '{"stopPrice":50,"workingType":"MARK_PRICE","type":"STOP_MARKET","quantity":1}',
// takeProfit: '{"stopPrice":150,"workingType":"MARK_PRICE","type":"TAKE_PROFIT_MARKET","quantity":1}',
// reduceOnly: false
// }
//
// editOrder (swap)
//
// {
// cancelResult: 'true',
// cancelMsg: '',
// cancelResponse: {
// cancelClientOrderId: '',
// cancelOrderId: '1755336244265705472',
// symbol: 'SOL-USDT',
// orderId: '1755336244265705472',
// side: 'SELL',
// positionSide: 'SHORT',
// type: 'LIMIT',
// origQty: '1',
// price: '100.000',
// executedQty: '0',
// avgPrice: '0.000',
// cumQuote: '0',
// stopPrice: '',
// profit: '0.0000',
// commission: '0.000000',
// status: 'PENDING',
// time: '1707339747860',
// updateTime: '1707339747860',
// clientOrderId: '',
// leverage: '20X',
// workingType: 'MARK_PRICE',
// onlyOnePosition: false,
// reduceOnly: false
// },
// replaceResult: 'true',
// replaceMsg: '',
// newOrderResponse: {
// orderId: '1755338440612995072',
// symbol: 'SOL-USDT',
// positionSide: 'SHORT',
// side: 'SELL',
// type: 'LIMIT',
// price: '99',
// quantity: '2',
// stopPrice: '0',
// workingType: 'MARK_PRICE',
// clientOrderID: '',
// timeInForce: 'GTC',
// priceRate: '0',
// stopLoss: '',
// takeProfit: '',
// reduceOnly: false
// }
// }
//
// editOrder (spot)
//
// {
// cancelResult: { code: '0', msg: '', result: true },
// openResult: { code: '0', msg: '', result: true },
// orderOpenResponse: {
// symbol: 'SOL-USDT',
// orderId: '1755334007697866752',
// transactTime: '1707339214620',
// price: '99',
// stopPrice: '0',
// origQty: '0.2',
// executedQty: '0',
// cummulativeQuoteQty: '0',
// status: 'PENDING',
// type: 'LIMIT',
// side: 'SELL',
// clientOrderID: ''
// },
// orderCancelResponse: {
// symbol: 'SOL-USDT',
// orderId: '1755117055251480576',
// price: '100',
// stopPrice: '0',
// origQty: '0.2',
// executedQty: '0',
// cummulativeQuoteQty: '0',
// status: 'CANCELED',
// type: 'LIMIT',
// side: 'SELL'
// }
// }
//
// stop loss order
//
// {
// "symbol": "ETH-USDT",
// "orderId": "1792461744476422144",
// "price": "2775.65",
// "StopPrice": "2778.42",
// "origQty": "0.032359",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "NEW",
// "type": "TAKE_STOP_LIMIT",
// "side": "SELL",
// "time": "1716191156868",
// "updateTime": "1716191156868",
// "origQuoteOrderQty": "0",
// "fee": "0",
// "feeAsset": "USDT",
// "clientOrderID": ""
// }
//
// inverse swap cancelAllOrders, cancelOrder, fetchOrder, fetchOpenOrders, fetchClosedOrders, fetchCanceledOrders
//
// {
// "symbol": "SOL-USD",
// "orderId": "1809845251327672320",
// "side": "BUY",
// "positionSide": "LONG",
// "type": "LIMIT",
// "quantity": 1,
// "origQty": "0",
// "price": "90",
// "executedQty": "0",
// "avgPrice": "0",
// "cumQuote": "0",
// "stopPrice": "",
// "profit": "0.0000",
// "commission": "0.000000",
// "status": "CANCELLED",
// "time": 1720335707872,
// "updateTime": 1720335707912,
// "clientOrderId": "",
// "leverage": "",
// "takeProfit": {
// "type": "",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "",
// "stopGuaranteed": ""
// },
// "stopLoss": {
// "type": "",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "",
// "stopGuaranteed": ""
// },
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": ""
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var info interface{} = order
var newOrder interface{} = this.SafeDict2(order, "newOrderResponse", "orderOpenResponse")
if IsTrue(!IsEqual(newOrder, nil)) {
order = newOrder
}
var positionSide interface{} = this.SafeString2(order, "positionSide", "ps")
var marketType interface{} = Ternary(IsTrue((IsEqual(positionSide, nil))), "spot", "swap")
var marketId interface{} = this.SafeString2(order, "symbol", "s")
if IsTrue(IsEqual(market, nil)) {
market = this.SafeMarket(marketId, nil, nil, marketType)
}
var side interface{} = this.SafeStringLower2(order, "side", "S")
var timestamp interface{} = this.SafeIntegerN(order, []interface{}{"time", "transactTime", "E", "createdTime"})
var lastTradeTimestamp interface{} = this.SafeInteger2(order, "updateTime", "T")
var statusId interface{} = this.SafeStringUpperN(order, []interface{}{"status", "X", "orderStatus"})
var feeCurrencyCode interface{} = this.SafeString2(order, "feeAsset", "N")
var feeCost interface{} = this.SafeStringN(order, []interface{}{"fee", "commission", "n"})
if IsTrue((IsEqual(feeCurrencyCode, nil))) {
if IsTrue(GetValue(market, "spot")) {
if IsTrue(IsEqual(side, "buy")) {
feeCurrencyCode = GetValue(market, "base")
} else {
feeCurrencyCode = GetValue(market, "quote")
}
} else {
feeCurrencyCode = GetValue(market, "quote")
}
}
var stopLoss interface{} = this.SafeValue(order, "stopLoss")
var stopLossPrice interface{} = nil
if IsTrue(IsTrue((!IsEqual(stopLoss, nil))) && IsTrue((!IsEqual(stopLoss, "")))) {
stopLossPrice = this.OmitZero(this.SafeString(stopLoss, "stopLoss"))
}
if IsTrue(IsTrue(IsTrue((!IsEqual(stopLoss, nil))) && IsTrue((!IsNumber(stopLoss)))) && IsTrue((!IsEqual(stopLoss, "")))) {
// stopLoss: '{"stopPrice":50,"workingType":"MARK_PRICE","type":"STOP_MARKET","quantity":1}',
if IsTrue(IsString(stopLoss)) {
stopLoss = this.ParseJson(stopLoss)
}
stopLossPrice = this.OmitZero(this.SafeString(stopLoss, "stopPrice"))
}
var takeProfit interface{} = this.SafeValue(order, "takeProfit")
var takeProfitPrice interface{} = nil
if IsTrue(IsTrue(!IsEqual(takeProfit, nil)) && IsTrue((!IsEqual(takeProfit, "")))) {
takeProfitPrice = this.OmitZero(this.SafeString(takeProfit, "takeProfit"))
}
if IsTrue(IsTrue(IsTrue((!IsEqual(takeProfit, nil))) && IsTrue((!IsNumber(takeProfit)))) && IsTrue((!IsEqual(takeProfit, "")))) {
// takeProfit: '{"stopPrice":150,"workingType":"MARK_PRICE","type":"TAKE_PROFIT_MARKET","quantity":1}',
if IsTrue(IsString(takeProfit)) {
takeProfit = this.ParseJson(takeProfit)
}
takeProfitPrice = this.OmitZero(this.SafeString(takeProfit, "stopPrice"))
}
var rawType interface{} = this.SafeStringLower2(order, "type", "o")
var stopPrice interface{} = this.OmitZero(this.SafeString2(order, "StopPrice", "stopPrice"))
var triggerPrice interface{} = stopPrice
if IsTrue(!IsEqual(stopPrice, nil)) {
if IsTrue(IsTrue((IsGreaterThan(GetIndexOf(rawType, "stop"), OpNeg(1)))) && IsTrue((IsEqual(stopLossPrice, nil)))) {
stopLossPrice = stopPrice
triggerPrice = nil
}
if IsTrue(IsTrue((IsGreaterThan(GetIndexOf(rawType, "take"), OpNeg(1)))) && IsTrue((IsEqual(takeProfitPrice, nil)))) {
takeProfitPrice = stopPrice
triggerPrice = nil
}
}
return this.SafeOrder(map[string]interface{} {
"info": info,
"id": this.SafeStringN(order, []interface{}{"orderId", "i", "mainOrderId"}),
"clientOrderId": this.SafeStringN(order, []interface{}{"clientOrderID", "clientOrderId", "origClientOrderId", "c"}),
"symbol": this.SafeSymbol(marketId, market, "-", marketType),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"lastTradeTimestamp": lastTradeTimestamp,
"lastUpdateTimestamp": this.SafeInteger(order, "updateTime"),
"type": this.ParseOrderType(rawType),
"timeInForce": this.SafeString(order, "timeInForce"),
"postOnly": nil,
"side": this.ParseOrderSide(side),
"price": this.SafeString2(order, "price", "p"),
"triggerPrice": triggerPrice,
"stopLossPrice": stopLossPrice,
"takeProfitPrice": takeProfitPrice,
"average": this.SafeString2(order, "avgPrice", "ap"),
"cost": this.SafeString(order, "cummulativeQuoteQty"),
"amount": this.SafeStringN(order, []interface{}{"origQty", "q", "quantity", "totalAmount"}),
"filled": this.SafeString2(order, "executedQty", "z"),
"remaining": nil,
"status": this.ParseOrderStatus(statusId),
"fee": map[string]interface{} {
"currency": feeCurrencyCode,
"cost": Precise.StringAbs(feeCost),
},
"trades": nil,
"reduceOnly": this.SafeBool2(order, "reduceOnly", "ro"),
}, market)
}
func (this *bingx) ParseOrderStatus(status interface{}) interface{} {
var statuses interface{} = map[string]interface{} {
"NEW": "open",
"PENDING": "open",
"PARTIALLY_FILLED": "open",
"RUNNING": "open",
"FILLED": "closed",
"CANCELED": "canceled",
"CANCELLED": "canceled",
"FAILED": "canceled",
}
return this.SafeString(statuses, status, status)
}
/**
* @method
* @name bingx#cancelOrder
* @description cancels an open order
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20Order
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Cancel%20Order
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Cancel%20an%20Order
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Cancel%20TWAP%20Order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] a unique id for the order
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) CancelOrder(id interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes36788 := (<-this.LoadMarkets())
PanicOnError(retRes36788)
var isTwapOrder interface{} = this.SafeBool(params, "twap", false)
params = this.Omit(params, "twap")
var response interface{} = nil
var market interface{} = nil
if IsTrue(isTwapOrder) {
var twapRequest interface{} = map[string]interface{} {
"mainOrderId": id,
}
response = (<-this.SwapV1PrivatePostTwapCancelOrder(this.Extend(twapRequest, params)))
PanicOnError(response)
} else {
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " cancelOrder() requires a symbol argument")))
}
market = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var clientOrderId interface{} = this.SafeString2(params, "clientOrderId", "clientOrderID")
params = this.Omit(params, []interface{}{"clientOrderId"})
if IsTrue(!IsEqual(clientOrderId, nil)) {
AddElementToObject(request, "clientOrderID", clientOrderId)
} else {
AddElementToObject(request, "orderId", id)
}
var typeVar interface{} = nil
var subType interface{} = nil
typeVarparamsVariable := this.HandleMarketTypeAndParams("cancelOrder", market, params);
typeVar = GetValue(typeVarparamsVariable,0);
params = GetValue(typeVarparamsVariable,1)
subTypeparamsVariable := this.HandleSubTypeAndParams("cancelOrder", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
if IsTrue(IsEqual(typeVar, "spot")) {
response = (<-this.SpotV1PrivatePostTradeCancel(this.Extend(request, params)))
PanicOnError(response)
} else {
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PrivateDeleteTradeCancelOrder(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateDeleteTradeOrder(this.Extend(request, params)))
PanicOnError(response)
}
}
}
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "symbol": "XRP-USDT",
// "orderId": 1514090846268424192,
// "price": "0.5",
// "origQty": "10",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "CANCELED",
// "type": "LIMIT",
// "side": "BUY"
// }
// }
//
// inverse swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "order": {
// "symbol": "SOL-USD",
// "orderId": "1816002957423951872",
// "side": "BUY",
// "positionSide": "Long",
// "type": "Pending",
// "quantity": 0,
// "origQty": "0",
// "price": "150",
// "executedQty": "0",
// "avgPrice": "0",
// "cumQuote": "0",
// "stopPrice": "",
// "profit": "0.0000",
// "commission": "0.000000",
// "status": "CANCELLED",
// "time": 1721803819410,
// "updateTime": 1721803819427,
// "clientOrderId": "",
// "leverage": "",
// "takeProfit": {
// "type": "",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "",
// "stopGuaranteed": ""
// },
// "stopLoss": {
// "type": "",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "",
// "stopGuaranteed": ""
// },
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": ""
// }
// }
// }
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "order": {
// "symbol": "LINK-USDT",
// "orderId": 1597783850786750464,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "TRIGGER_MARKET",
// "origQty": "5.0",
// "price": "5.0000",
// "executedQty": "0.0",
// "avgPrice": "0.0000",
// "cumQuote": "0",
// "stopPrice": "5.0000",
// "profit": "",
// "commission": "",
// "status": "CANCELLED",
// "time": 1669776330000,
// "updateTime": 1669776330000
// }
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var order interface{} = this.SafeDict(data, "order", data)
ch <- this.ParseOrder(order, market)
return nil
}()
return ch
}
/**
* @method
* @name bingx#cancelAllOrders
* @description cancel all open orders
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20orders%20by%20symbol
* @see https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Cancel%20All%20Orders
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Cancel%20all%20orders
* @param {string} [symbol] unified market symbol, only orders in the market of this symbol are cancelled when symbol is not undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) CancelAllOrders(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " cancelAllOrders() requires a symbol argument")))
}
retRes38598 := (<-this.LoadMarkets())
PanicOnError(retRes38598)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var response interface{} = nil
if IsTrue(GetValue(market, "spot")) {
response = (<-this.SpotV1PrivatePostTradeCancelOpenOrders(this.Extend(request, params)))
PanicOnError(response)
} else if IsTrue(GetValue(market, "swap")) {
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PrivateDeleteTradeAllOpenOrders(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateDeleteTradeAllOpenOrders(this.Extend(request, params)))
PanicOnError(response)
}
} else {
panic(BadRequest(Add(this.Id, " cancelAllOrders is only supported for spot and swap markets.")))
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var orders interface{} = this.SafeList2(data, "success", "orders", []interface{}{})
ch <- this.ParseOrders(orders)
return nil
}()
return ch
}
/**
* @method
* @name bingx#cancelOrders
* @description cancel multiple orders
* @see https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Cancel%20a%20Batch%20of%20Orders
* @see https://bingx-api.github.io/docs/#/spot/trade-api.html#Cancel%20a%20Batch%20of%20Orders
* @param {string[]} ids order ids
* @param {string} symbol unified market symbol, default is undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string[]} [params.clientOrderIds] client order ids
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) CancelOrders(ids interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " cancelOrders() requires a symbol argument")))
}
retRes40038 := (<-this.LoadMarkets())
PanicOnError(retRes40038)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var clientOrderIds interface{} = this.SafeValue(params, "clientOrderIds")
params = this.Omit(params, "clientOrderIds")
var idsToParse interface{} = ids
var areClientOrderIds interface{} = (!IsEqual(clientOrderIds, nil))
if IsTrue(areClientOrderIds) {
idsToParse = clientOrderIds
}
var parsedIds interface{} = []interface{}{}
for i := 0; IsLessThan(i, GetArrayLength(idsToParse)); i++ {
var id interface{} = GetValue(idsToParse, i)
var stringId interface{} = ToString(id)
AppendToArray(&parsedIds,stringId)
}
var response interface{} = nil
if IsTrue(GetValue(market, "spot")) {
var spotReqKey interface{} = Ternary(IsTrue(areClientOrderIds), "clientOrderIDs", "orderIds")
AddElementToObject(request, spotReqKey, Join(parsedIds, ","))
response = (<-this.SpotV1PrivatePostTradeCancelOrders(this.Extend(request, params)))
PanicOnError(response)
} else {
if IsTrue(areClientOrderIds) {
AddElementToObject(request, "clientOrderIDList", this.Json(parsedIds))
} else {
AddElementToObject(request, "orderIdList", parsedIds)
}
response = (<-this.SwapV2PrivateDeleteTradeBatchOrders(this.Extend(request, params)))
PanicOnError(response)
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var success interface{} = this.SafeList2(data, "success", "orders", []interface{}{})
ch <- this.ParseOrders(success)
return nil
}()
return ch
}
/**
* @method
* @name bingx#cancelAllOrdersAfter
* @description dead man's switch, cancel all orders after the given timeout
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20all%20orders%20in%20countdown
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Cancel%20all%20orders%20in%20countdown
* @param {number} timeout time in milliseconds, 0 represents cancel the timer
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.type] spot or swap market
* @returns {object} the api result
*/
func (this *bingx) CancelAllOrdersAfter(timeout interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes41068 := (<-this.LoadMarkets())
PanicOnError(retRes41068)
var isActive interface{} = (IsGreaterThan(timeout, 0))
var request interface{} = map[string]interface{} {
"type": Ternary(IsTrue((isActive)), "ACTIVATE", "CLOSE"),
"timeOut": Ternary(IsTrue((isActive)), (this.ParseToInt(Divide(timeout, 1000))), 0),
}
var response interface{} = nil
var typeVar interface{} = nil
typeVarparamsVariable := this.HandleMarketTypeAndParams("cancelAllOrdersAfter", nil, params);
typeVar = GetValue(typeVarparamsVariable,0);
params = GetValue(typeVarparamsVariable,1)
if IsTrue(IsEqual(typeVar, "spot")) {
response = (<-this.SpotV1PrivatePostTradeCancelAllAfter(this.Extend(request, params)))
PanicOnError(response)
} else if IsTrue(IsEqual(typeVar, "swap")) {
response = (<-this.SwapV2PrivatePostTradeCancelAllAfter(this.Extend(request, params)))
PanicOnError(response)
} else {
panic(NotSupported(Add(Add(Add(this.Id, " cancelAllOrdersAfter() is not supported for "), typeVar), " markets")))
}
//
// {
// code: '0',
// msg: '',
// data: {
// triggerTime: '1712645434',
// status: 'ACTIVATED',
// note: 'All your perpetual pending orders will be closed automatically at 2024-04-09 06:50:34 UTC(+0),before that you can cancel the timer, or extend triggerTime time by this request'
// }
// }
//
ch <- response
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchOrder
* @description fetches information on an order made by the user
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Order%20details
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20details
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Order
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#TWAP%20Order%20Details
* @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
* @param {boolean} [params.twap] if fetching twap order
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) FetchOrder(id interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes41518 := (<-this.LoadMarkets())
PanicOnError(retRes41518)
var isTwapOrder interface{} = this.SafeBool(params, "twap", false)
params = this.Omit(params, "twap")
var response interface{} = nil
var market interface{} = nil
if IsTrue(isTwapOrder) {
var twapRequest interface{} = map[string]interface{} {
"mainOrderId": id,
}
response = (<-this.SwapV1PrivateGetTwapOrderDetail(this.Extend(twapRequest, params)))
PanicOnError(response)
} else {
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchOrder() requires a symbol argument")))
}
market = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"orderId": id,
}
var typeVar interface{} = nil
var subType interface{} = nil
typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchOrder", market, params);
typeVar = GetValue(typeVarparamsVariable,0);
params = GetValue(typeVarparamsVariable,1)
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchOrder", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
if IsTrue(IsEqual(typeVar, "spot")) {
response = (<-this.SpotV1PrivateGetTradeQuery(this.Extend(request, params)))
PanicOnError(response)
} else {
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PrivateGetTradeOrderDetail(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateGetTradeOrder(this.Extend(request, params)))
PanicOnError(response)
}
}
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var order interface{} = this.SafeDict(data, "order", data)
ch <- this.ParseOrder(order, market)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#All%20Orders
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20history (returns less fields than above)
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch entries for
* @param {int} [params.orderId] Only return subsequent orders, and return the latest order by default
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) FetchOrders(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes43288 := (<-this.LoadMarkets())
PanicOnError(retRes43288)
var request interface{} = map[string]interface{} {}
var market interface{} = nil
if IsTrue(!IsEqual(symbol, nil)) {
market = this.Market(symbol)
AddElementToObject(request, "symbol", GetValue(market, "id"))
}
var typeVar interface{} = nil
typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchOrders", market, params);
typeVar = GetValue(typeVarparamsVariable,0);
params = GetValue(typeVarparamsVariable,1)
if IsTrue(!IsEqual(typeVar, "swap")) {
panic(NotSupported(Add(this.Id, " fetchOrders() is only supported for swap markets")))
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "limit", limit)
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startTime", since)
}
requestparamsVariable := this.HandleUntilOption("endTime", request, params);
request = GetValue(requestparamsVariable,0);
params = GetValue(requestparamsVariable,1)
response:= (<-this.SwapV1PrivateGetTradeFullOrder(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "PYTH-USDT",
// "orderId": 1736007506620112100,
// "side": "SELL",
// "positionSide": "SHORT",
// "type": "LIMIT",
// "origQty": "33",
// "price": "0.3916",
// "executedQty": "33",
// "avgPrice": "0.3916",
// "cumQuote": "13",
// "stopPrice": "",
// "profit": "0.0000",
// "commission": "-0.002585",
// "status": "FILLED",
// "time": 1702731418000,
// "updateTime": 1702731470000,
// "clientOrderId": "",
// "leverage": "15X",
// "takeProfit": {
// "type": "TAKE_PROFIT",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": ""
// },
// "stopLoss": {
// "type": "STOP",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": ""
// },
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": "MARK_PRICE",
// "stopGuaranteed": false,
// "triggerOrderId": 1736012449498123500
// }
// ]
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var orders interface{} = this.SafeList(data, "orders", []interface{}{})
ch <- this.ParseOrders(orders, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Current%20Open%20Orders
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Current%20All%20Open%20Orders
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20all%20current%20pending%20orders
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20TWAP%20Entrusted%20Order
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.twap] if fetching twap open orders
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) FetchOpenOrders(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes44218 := (<-this.LoadMarkets())
PanicOnError(retRes44218)
var market interface{} = nil
var request interface{} = map[string]interface{} {}
if IsTrue(!IsEqual(symbol, nil)) {
market = this.Market(symbol)
AddElementToObject(request, "symbol", GetValue(market, "id"))
}
var typeVar interface{} = nil
var subType interface{} = nil
var response interface{} = nil
typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchOpenOrders", market, params);
typeVar = GetValue(typeVarparamsVariable,0);
params = GetValue(typeVarparamsVariable,1)
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchOpenOrders", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
if IsTrue(IsEqual(typeVar, "spot")) {
response = (<-this.SpotV1PrivateGetTradeOpenOrders(this.Extend(request, params)))
PanicOnError(response)
} else {
var isTwapOrder interface{} = this.SafeBool(params, "twap", false)
params = this.Omit(params, "twap")
if IsTrue(isTwapOrder) {
response = (<-this.SwapV1PrivateGetTwapOpenOrders(this.Extend(request, params)))
PanicOnError(response)
} else if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PrivateGetTradeOpenOrders(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateGetTradeOpenOrders(this.Extend(request, params)))
PanicOnError(response)
}
}
//
// spot
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "XRP-USDT",
// "orderId": 1514073325788200960,
// "price": "0.5",
// "origQty": "20",
// "executedQty": "0",
// "cummulativeQuoteQty": "0",
// "status": "PENDING",
// "type": "LIMIT",
// "side": "BUY",
// "time": 1649818185647,
// "updateTime": 1649818185647,
// "origQuoteOrderQty": "0"
// }
// ]
// }
// }
//
// inverse swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "SOL-USD",
// "orderId": "1816013900044320768",
// "side": "BUY",
// "positionSide": "Long",
// "type": "LIMIT",
// "quantity": 1,
// "origQty": "",
// "price": "150",
// "executedQty": "0",
// "avgPrice": "0.000",
// "cumQuote": "",
// "stopPrice": "",
// "profit": "0.0000",
// "commission": "0.0000",
// "status": "Pending",
// "time": 1721806428334,
// "updateTime": 1721806428352,
// "clientOrderId": "",
// "leverage": "",
// "takeProfit": {
// "type": "TAKE_PROFIT",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "MARK_PRICE",
// "stopGuaranteed": ""
// },
// "stopLoss": {
// "type": "STOP",
// "quantity": 0,
// "stopPrice": 0,
// "price": 0,
// "workingType": "MARK_PRICE",
// "stopGuaranteed": ""
// },
// "advanceAttr": 0,
// "positionID": 0,
// "takeProfitEntrustPrice": 0,
// "stopLossEntrustPrice": 0,
// "orderType": "",
// "workingType": "MARK_PRICE"
// }
// ]
// }
// }
//
// linear swap
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "symbol": "LINK-USDT",
// "orderId": 1585839271162413056,
// "side": "BUY",
// "positionSide": "LONG",
// "type": "TRIGGER_MARKET",
// "origQty": "5.0",
// "price": "9",
// "executedQty": "0.0",
// "avgPrice": "0",
// "cumQuote": "0",
// "stopPrice": "5",
// "profit": "0.0000",
// "commission": "0.000000",
// "status": "CANCELLED",
// "time": 1667631605000,
// "updateTime": 1667631605000
// },
// ]
// }
// }
//
// twap
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1702731661854,
// "data": {
// "list": [
// {
// "symbol": "BNB-USDT",
// "side": "BUY",
// "positionSide": "LONG",
// "priceType": "constant",
// "priceVariance": "2000",
// "triggerPrice": "68000",
// "interval": 8,
// "amountPerOrder": "0.111",
// "totalAmount": "0.511",
// "orderStatus": "Running",
// "executedQty": "0.1",
// "duration": 800,
// "maxDuration": 9000,
// "createdTime": 1702731661854,
// "updateTime": 1702731661854
// }
// ],
// "total": 1
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var orders interface{} = this.SafeList2(data, "orders", "list", []interface{}{})
ch <- this.ParseOrders(orders, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Order%20history
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20history
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#User's%20History%20Orders
* @see https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order
* @param {string} symbol unified market symbol of the closed orders
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the max number of closed orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @param {boolean} [params.standard] whether to fetch standard contract orders
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) FetchClosedOrders(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes46078 := (<-this.LoadMarkets())
PanicOnError(retRes46078)
orders:= (<-this.FetchCanceledAndClosedOrders(symbol, since, limit, params))
PanicOnError(orders)
ch <- this.FilterBy(orders, "status", "closed")
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchCanceledOrders
* @description fetches information on multiple canceled orders made by the user
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Order%20history
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20history
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#User's%20History%20Orders
* @see https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order
* @param {string} symbol unified market symbol of the canceled orders
* @param {int} [since] timestamp in ms of the earliest order
* @param {int} [limit] the max number of canceled orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @param {boolean} [params.standard] whether to fetch standard contract orders
* @returns {object} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) FetchCanceledOrders(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes46298 := (<-this.LoadMarkets())
PanicOnError(retRes46298)
orders:= (<-this.FetchCanceledAndClosedOrders(symbol, since, limit, params))
PanicOnError(orders)
ch <- this.FilterBy(orders, "status", "canceled")
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchCanceledAndClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Order%20history
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Order%20history
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#User's%20History%20Orders
* @see https://bingx-api.github.io/docs/#/standard/contract-interface.html#Historical%20order
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20TWAP%20Historical%20Orders
* @param {string} [symbol] unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @param {boolean} [params.standard] whether to fetch standard contract orders
* @param {boolean} [params.twap] if fetching twap orders
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) FetchCanceledAndClosedOrders(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes46538 := (<-this.LoadMarkets())
PanicOnError(retRes46538)
var market interface{} = nil
var request interface{} = map[string]interface{} {}
if IsTrue(!IsEqual(symbol, nil)) {
market = this.Market(symbol)
AddElementToObject(request, "symbol", GetValue(market, "id"))
}
var typeVar interface{} = nil
var subType interface{} = nil
var standard interface{} = nil
var response interface{} = nil
typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchClosedOrders", market, params);
typeVar = GetValue(typeVarparamsVariable,0);
params = GetValue(typeVarparamsVariable,1)
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchClosedOrders", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
standardparamsVariable := this.HandleOptionAndParams(params, "fetchClosedOrders", "standard", false);
standard = GetValue(standardparamsVariable,0);
params = GetValue(standardparamsVariable,1)
if IsTrue(standard) {
response = (<-this.ContractV1PrivateGetAllOrders(this.Extend(request, params)))
PanicOnError(response)
} else if IsTrue(IsEqual(typeVar, "spot")) {
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "pageSize", limit)
}
response = (<-this.SpotV1PrivateGetTradeHistoryOrders(this.Extend(request, params)))
PanicOnError(response)
} else {
var isTwapOrder interface{} = this.SafeBool(params, "twap", false)
params = this.Omit(params, "twap")
if IsTrue(isTwapOrder) {
AddElementToObject(request, "pageIndex", 1)
AddElementToObject(request, "pageSize", Ternary(IsTrue((IsEqual(limit, nil))), 100, limit))
AddElementToObject(request, "startTime", Ternary(IsTrue((IsEqual(since, nil))), 1, since))
var until interface{} = this.SafeInteger(params, "until", this.Milliseconds())
params = this.Omit(params, "until")
AddElementToObject(request, "endTime", until)
response = (<-this.SwapV1PrivateGetTwapHistoryOrders(this.Extend(request, params)))
PanicOnError(response)
} else if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PrivateGetTradeOrderHistory(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateGetTradeAllOrders(this.Extend(request, params)))
PanicOnError(response)
}
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var orders interface{} = this.SafeList2(data, "orders", "list", []interface{}{})
ch <- this.ParseOrders(orders, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name bingx#transfer
* @description transfer currency internally between wallets on the same account
* @see https://bingx-api.github.io/docs/#/spot/account-api.html#User%20Universal%20Transfer
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount account to transfer from
* @param {string} toAccount account to transfer to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/#/?id=transfer-structure}
*/
func (this *bingx) Transfer(code interface{}, amount interface{}, fromAccount interface{}, toAccount interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes48438 := (<-this.LoadMarkets())
PanicOnError(retRes48438)
var currency interface{} = this.Currency(code)
var accountsByType interface{} = this.SafeDict(this.Options, "accountsByType", map[string]interface{} {})
var fromId interface{} = this.SafeString(accountsByType, fromAccount, fromAccount)
var toId interface{} = this.SafeString(accountsByType, toAccount, toAccount)
var request interface{} = map[string]interface{} {
"asset": GetValue(currency, "id"),
"amount": this.CurrencyToPrecision(code, amount),
"type": Add(Add(fromId, "_"), toId),
}
response:= (<-this.SpotV3PrivateGetGetAssetTransfer(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "tranId":13526853623
// }
//
ch <- map[string]interface{} {
"info": response,
"id": this.SafeString(response, "tranId"),
"timestamp": nil,
"datetime": nil,
"currency": code,
"amount": amount,
"fromAccount": fromAccount,
"toAccount": toAccount,
"status": nil,
}
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchTransfers
* @description fetch a history of internal transfers made on an account
* @see https://bingx-api.github.io/docs/#/spot/account-api.html#Query%20User%20Universal%20Transfer%20History%20(USER_DATA)
* @param {string} [code] unified currency code of the currency transferred
* @param {int} [since] the earliest time in ms to fetch transfers for
* @param {int} [limit] the maximum number of transfers structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/#/?id=transfer-structure}
*/
func (this *bingx) FetchTransfers(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
code := GetArg(optionalArgs, 0, nil)
_ = code
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes48848 := (<-this.LoadMarkets())
PanicOnError(retRes48848)
var currency interface{} = nil
if IsTrue(!IsEqual(code, nil)) {
currency = this.Currency(code)
}
var accountsByType interface{} = this.SafeDict(this.Options, "accountsByType", map[string]interface{} {})
var fromAccount interface{} = this.SafeString(params, "fromAccount")
var toAccount interface{} = this.SafeString(params, "toAccount")
var fromId interface{} = this.SafeString(accountsByType, fromAccount, fromAccount)
var toId interface{} = this.SafeString(accountsByType, toAccount, toAccount)
if IsTrue(IsTrue(IsEqual(fromId, nil)) || IsTrue(IsEqual(toId, nil))) {
panic(ExchangeError(Add(this.Id, " fromAccount & toAccount parameter are required")))
}
var request interface{} = map[string]interface{} {
"type": Add(Add(fromId, "_"), toId),
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startTime", since)
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "size", limit)
}
response:= (<-this.SpotV3PrivateGetAssetTransfer(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "total": 3,
// "rows": [
// {
// "asset":"USDT",
// "amount":"-100.00000000000000000000",
// "type":"FUND_SFUTURES",
// "status":"CONFIRMED",
// "tranId":1067594500957016069,
// "timestamp":1658388859000
// },
// ]
// }
//
var rows interface{} = this.SafeList(response, "rows", []interface{}{})
ch <- this.ParseTransfers(rows, currency, since, limit)
return nil
}()
return ch
}
func (this *bingx) ParseTransfer(transfer interface{}, optionalArgs ...interface{}) interface{} {
currency := GetArg(optionalArgs, 0, nil)
_ = currency
var tranId interface{} = this.SafeString(transfer, "tranId")
var timestamp interface{} = this.SafeInteger(transfer, "timestamp")
var currencyCode interface{} = this.SafeCurrencyCode(nil, currency)
var status interface{} = this.SafeString(transfer, "status")
var accountsById interface{} = this.SafeDict(this.Options, "accountsById", map[string]interface{} {})
var typeId interface{} = this.SafeString(transfer, "type")
var typeIdSplit interface{} = Split(typeId, "_")
var fromId interface{} = this.SafeString(typeIdSplit, 0)
var toId interface{} = this.SafeString(typeId, 1)
var fromAccount interface{} = this.SafeString(accountsById, fromId, fromId)
var toAccount interface{} = this.SafeString(accountsById, toId, toId)
return map[string]interface{} {
"info": transfer,
"id": tranId,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"currency": currencyCode,
"amount": this.SafeNumber(transfer, "amount"),
"fromAccount": fromAccount,
"toAccount": toAccount,
"status": status,
}
}
/**
* @method
* @name bingx#fetchDepositAddressesByNetwork
* @description fetch the deposit addresses for a currency associated with this account
* @see https://bingx-api.github.io/docs/#/en-us/common/wallet-api.html#Query%20Main%20Account%20Deposit%20Address
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary [address structures]{@link https://docs.ccxt.com/#/?id=address-structure}, indexed by the network
*/
func (this *bingx) FetchDepositAddressesByNetwork(code interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes49618 := (<-this.LoadMarkets())
PanicOnError(retRes49618)
var currency interface{} = this.Currency(code)
var defaultRecvWindow interface{} = this.SafeInteger(this.Options, "recvWindow")
var recvWindow interface{} = this.SafeInteger(this.ParseParams, "recvWindow", defaultRecvWindow)
var request interface{} = map[string]interface{} {
"coin": GetValue(currency, "id"),
"offset": 0,
"limit": 1000,
"recvWindow": recvWindow,
}
response:= (<-this.WalletsV1PrivateGetCapitalDepositAddress(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "0",
// "timestamp": "1695200226859",
// "data": {
// "data": [
// {
// "coinId": "799",
// "coin": "USDT",
// "network": "BEP20",
// "address": "6a7eda2817462dabb6493277a2cfe0f5c3f2550b",
// "tag": ''
// }
// ],
// "total": "1"
// }
// }
//
var data interface{} = this.SafeList(this.SafeDict(response, "data"), "data")
var parsed interface{} = this.ParseDepositAddresses(data, []interface{}{GetValue(currency, "code")}, false)
ch <- this.IndexBy(parsed, "network")
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://bingx-api.github.io/docs/#/en-us/common/wallet-api.html#Query%20Main%20Account%20Deposit%20Address
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.network] The chain of currency. This only apply for multi-chain currency, and there is no need for single chain currency
* @returns {object} an [address structure]{@link https://docs.ccxt.com/#/?id=address-structure}
*/
func (this *bingx) FetchDepositAddress(code interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
var network interface{} = this.SafeString(params, "network")
params = this.Omit(params, []interface{}{"network"})
addressStructures:= (<-this.FetchDepositAddressesByNetwork(code, params))
PanicOnError(addressStructures)
if IsTrue(!IsEqual(network, nil)) {
ch <- this.SafeDict(addressStructures, network)
return nil
} else {
var options interface{} = this.SafeDict(this.Options, "defaultNetworks")
var defaultNetworkForCurrency interface{} = this.SafeString(options, code)
if IsTrue(!IsEqual(defaultNetworkForCurrency, nil)) {
ch <- this.SafeDict(addressStructures, defaultNetworkForCurrency)
return nil
} else {
var keys interface{} = ObjectKeys(addressStructures)
var key interface{} = this.SafeString(keys, 0)
ch <- this.SafeDict(addressStructures, key)
return nil
}
}
return nil
}()
return ch
}
func (this *bingx) ParseDepositAddress(depositAddress interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "coinId":"4",
// "coin":"USDT",
// "network":"OMNI",
// "address":"1HXyx8HVQRY7Nhqz63nwnRB7SpS9xQPzLN",
// "addressWithPrefix":"1HXyx8HVQRY7Nhqz63nwnRB7SpS9xQPzLN"
// }
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
var tag interface{} = this.SafeString(depositAddress, "tag")
var currencyId interface{} = this.SafeString(depositAddress, "coin")
currency = this.SafeCurrency(currencyId, currency)
var code interface{} = GetValue(currency, "code")
var address interface{} = this.SafeString(depositAddress, "addressWithPrefix")
var networkdId interface{} = this.SafeString(depositAddress, "network")
var networkCode interface{} = this.NetworkIdToCode(networkdId, code)
this.CheckAddress(address)
return map[string]interface{} {
"info": depositAddress,
"currency": code,
"network": networkCode,
"address": address,
"tag": tag,
}
}
/**
* @method
* @name bingx#fetchDeposits
* @description fetch all deposits made to an account
* @see https://bingx-api.github.io/docs/#/spot/account-api.html#Deposit%20History(supporting%20network)
* @param {string} [code] unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
func (this *bingx) FetchDeposits(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
code := GetArg(optionalArgs, 0, nil)
_ = code
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes50638 := (<-this.LoadMarkets())
PanicOnError(retRes50638)
var request interface{} = map[string]interface{} {}
var currency interface{} = nil
if IsTrue(!IsEqual(code, nil)) {
currency = this.Currency(code)
AddElementToObject(request, "coin", GetValue(currency, "id"))
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startTime", since)
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "limit", limit) // default 1000
}
response:= (<-this.SpotV3PrivateGetCapitalDepositHisrec(this.Extend(request, params)))
PanicOnError(response)
//
// [
// {
// "amount":"0.00999800",
// "coin":"PAXG",
// "network":"ETH",
// "status":1,
// "address":"0x788cabe9236ce061e5a892e1a59395a81fc8d62c",
// "addressTag":"",
// "txId":"0xaad4654a3234aa6118af9b4b335f5ae81c360b2394721c019b5d1e75328b09f3",
// "insertTime":1599621997000,
// "transferType":0,
// "unlockConfirm":"12/12", // confirm times for unlocking
// "confirmTimes":"12/12"
// },
// ]
//
ch <- this.ParseTransactions(response, currency, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://bingx-api.github.io/docs/#/spot/account-api.html#Withdraw%20History%20(supporting%20network)
* @param {string} [code] unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
func (this *bingx) FetchWithdrawals(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
code := GetArg(optionalArgs, 0, nil)
_ = code
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes51108 := (<-this.LoadMarkets())
PanicOnError(retRes51108)
var request interface{} = map[string]interface{} {}
var currency interface{} = nil
if IsTrue(!IsEqual(code, nil)) {
currency = this.Currency(code)
AddElementToObject(request, "coin", GetValue(currency, "id"))
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startTime", since)
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "limit", limit) // default 1000
}
response:= (<-this.SpotV3PrivateGetCapitalWithdrawHistory(this.Extend(request, params)))
PanicOnError(response)
//
// [
// {
// "address": "0x94df8b352de7f46f64b01d3666bf6e936e44ce60",
// "amount": "8.91000000",
// "applyTime": "2019-10-12 11:12:02",
// "coin": "USDT",
// "id": "b6ae22b3aa844210a7041aee7589627c",
// "withdrawOrderId": "WITHDRAWtest123",
// "network": "ETH",
// "transferType": 0
// "status": 6,
// "transactionFee": "0.004",
// "confirmNo":3,
// "info": "The address is not valid. Please confirm with the recipient",
// "txId": "0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268"
// },
// ]
//
ch <- this.ParseTransactions(response, currency, since, limit)
return nil
}()
return ch
}
func (this *bingx) ParseTransaction(transaction interface{}, optionalArgs ...interface{}) interface{} {
//
// fetchDeposits
//
// {
// "amount":"0.00999800",
// "coin":"PAXG",
// "network":"ETH",
// "status":1,
// "address":"0x788cabe9236ce061e5a892e1a59395a81fc8d62c",
// "addressTag":"",
// "txId":"0xaad4654a3234aa6118af9b4b335f5ae81c360b2394721c019b5d1e75328b09f3",
// "insertTime":1599621997000,
// "transferType":0,
// "unlockConfirm":"12/12", // confirm times for unlocking
// "confirmTimes":"12/12"
// }
//
// fetchWithdrawals
//
// {
// "address": "0x94df8b352de7f46f64b01d3666bf6e936e44ce60",
// "amount": "8.91000000",
// "applyTime": "2019-10-12 11:12:02",
// "coin": "USDT",
// "id": "b6ae22b3aa844210a7041aee7589627c",
// "withdrawOrderId": "WITHDRAWtest123",
// "network": "ETH",
// "transferType": 0
// "status": 6,
// "transactionFee": "0.004",
// "confirmNo":3,
// "info": "The address is not valid. Please confirm with the recipient",
// "txId": "0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268"
// }
//
// withdraw
//
// {
// "code":0,
// "timestamp":1705274263621,
// "data":{
// "id":"1264246141278773252"
// }
// }
//
// parse withdraw-type output first...
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
var data interface{} = this.SafeValue(transaction, "data")
var dataId interface{} = Ternary(IsTrue((IsEqual(data, nil))), nil, this.SafeString(data, "id"))
var id interface{} = this.SafeString(transaction, "id", dataId)
var address interface{} = this.SafeString(transaction, "address")
var tag interface{} = this.SafeString(transaction, "addressTag")
var timestamp interface{} = this.SafeInteger(transaction, "insertTime")
var datetime interface{} = this.Iso8601(timestamp)
if IsTrue(IsEqual(timestamp, nil)) {
datetime = this.SafeString(transaction, "applyTime")
timestamp = this.Parse8601(datetime)
}
var network interface{} = this.SafeString(transaction, "network")
var currencyId interface{} = this.SafeString(transaction, "coin")
var code interface{} = this.SafeCurrencyCode(currencyId, currency)
if IsTrue(IsTrue(IsTrue((!IsEqual(code, nil))) && IsTrue((!IsEqual(code, network)))) && IsTrue(IsGreaterThanOrEqual(GetIndexOf(code, network), 0))) {
if IsTrue(!IsEqual(network, nil)) {
code = Replace(code, network, "")
}
}
var rawType interface{} = this.SafeString(transaction, "transferType")
var typeVar interface{} = Ternary(IsTrue((IsEqual(rawType, "0"))), "deposit", "withdrawal")
return map[string]interface{} {
"info": transaction,
"id": id,
"txid": this.SafeString(transaction, "txId"),
"type": typeVar,
"currency": code,
"network": this.NetworkIdToCode(network),
"amount": this.SafeNumber(transaction, "amount"),
"status": this.ParseTransactionStatus(this.SafeString(transaction, "status")),
"timestamp": timestamp,
"datetime": datetime,
"address": address,
"addressFrom": nil,
"addressTo": address,
"tag": tag,
"tagFrom": tag,
"tagTo": nil,
"updated": nil,
"comment": this.SafeString(transaction, "info"),
"fee": map[string]interface{} {
"currency": code,
"cost": this.SafeNumber(transaction, "transactionFee"),
"rate": nil,
},
"internal": nil,
}
}
func (this *bingx) ParseTransactionStatus(status interface{}) interface{} {
var statuses interface{} = map[string]interface{} {
"0": "pending",
"1": "ok",
"10": "pending",
"20": "rejected",
"30": "ok",
"40": "rejected",
"50": "ok",
"60": "pending",
"70": "rejected",
"2": "pending",
"3": "rejected",
"4": "pending",
"5": "rejected",
"6": "ok",
}
return this.SafeString(statuses, status, status)
}
/**
* @method
* @name bingx#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Change%20Margin%20Type
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Set%20Margin%20Type
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
func (this *bingx) SetMarginMode(marginMode interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " setMarginMode() requires a symbol argument")))
}
retRes52798 := (<-this.LoadMarkets())
PanicOnError(retRes52798)
var market interface{} = this.Market(symbol)
if IsTrue(!IsEqual(GetValue(market, "type"), "swap")) {
panic(BadSymbol(Add(this.Id, " setMarginMode() supports swap contracts only")))
}
marginMode = ToUpper(marginMode)
if IsTrue(IsEqual(marginMode, "CROSS")) {
marginMode = "CROSSED"
}
if IsTrue(IsTrue(!IsEqual(marginMode, "ISOLATED")) && IsTrue(!IsEqual(marginMode, "CROSSED"))) {
panic(BadRequest(Add(this.Id, " setMarginMode() marginMode argument should be isolated or cross")))
}
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"marginType": marginMode,
}
var subType interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("setMarginMode", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
if IsTrue(IsEqual(subType, "inverse")) {
retRes529819 := (<-this.CswapV1PrivatePostTradeMarginType(this.Extend(request, params)))
PanicOnError(retRes529819)
ch <- retRes529819
return nil
} else {
retRes530019 := (<-this.SwapV2PrivatePostTradeMarginType(this.Extend(request, params)))
PanicOnError(retRes530019)
ch <- retRes530019
return nil
}
return nil
}()
return ch
}
func (this *bingx) AddMargin(symbol interface{}, amount interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
var request interface{} = map[string]interface{} {
"type": 1,
}
retRes530815 := (<-this.SetMargin(symbol, amount, this.Extend(request, params)))
PanicOnError(retRes530815)
ch <- retRes530815
return nil
}()
return ch
}
func (this *bingx) ReduceMargin(symbol interface{}, amount interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
var request interface{} = map[string]interface{} {
"type": 2,
}
retRes531515 := (<-this.SetMargin(symbol, amount, this.Extend(request, params)))
PanicOnError(retRes531515)
ch <- retRes531515
return nil
}()
return ch
}
/**
* @method
* @name bingx#setMargin
* @description Either adds or reduces margin in an isolated position in order to set the margin to a specific value
* @see https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Adjust%20isolated%20margin
* @param {string} symbol unified market symbol of the market to set margin in
* @param {float} amount the amount to set the margin to
* @param {object} [params] parameters specific to the bingx api endpoint
* @returns {object} A [margin structure]{@link https://docs.ccxt.com/#/?id=add-margin-structure}
*/
func (this *bingx) SetMargin(symbol interface{}, amount interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
var typeVar interface{} = this.SafeInteger(params, "type") // 1 increase margin 2 decrease margin
if IsTrue(IsEqual(typeVar, nil)) {
panic(ArgumentsRequired(Add(this.Id, " setMargin() requires a type parameter either 1 (increase margin) or 2 (decrease margin)")))
}
if !IsTrue(this.InArray(typeVar, []interface{}{1, 2})) {
panic(ArgumentsRequired(Add(this.Id, " setMargin() requires a type parameter either 1 (increase margin) or 2 (decrease margin)")))
}
retRes53368 := (<-this.LoadMarkets())
PanicOnError(retRes53368)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"amount": this.AmountToPrecision(GetValue(market, "symbol"), amount),
"type": typeVar,
}
response:= (<-this.SwapV2PrivatePostTradePositionMargin(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "amount": 1,
// "type": 1
// }
//
ch <- this.ParseMarginModification(response, market)
return nil
}()
return ch
}
func (this *bingx) ParseMarginModification(data interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "code": 0,
// "msg": "",
// "amount": 1,
// "type": 1
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var typeVar interface{} = this.SafeString(data, "type")
return map[string]interface{} {
"info": data,
"symbol": this.SafeString(market, "symbol"),
"type": Ternary(IsTrue((IsEqual(typeVar, "1"))), "add", "reduce"),
"marginMode": "isolated",
"amount": this.SafeNumber(data, "amount"),
"total": this.SafeNumber(data, "margin"),
"code": this.SafeString(market, "settle"),
"status": nil,
"timestamp": nil,
"datetime": nil,
}
}
/**
* @method
* @name bingx#fetchLeverage
* @description fetch the set leverage for a market
* @see https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Query%20Leverage
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [leverage structure]{@link https://docs.ccxt.com/#/?id=leverage-structure}
*/
func (this *bingx) FetchLeverage(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes53908 := (<-this.LoadMarkets())
PanicOnError(retRes53908)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var response interface{} = nil
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PrivateGetTradeLeverage(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateGetTradeLeverage(this.Extend(request, params)))
PanicOnError(response)
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
ch <- this.ParseLeverage(data, market)
return nil
}()
return ch
}
func (this *bingx) ParseLeverage(leverage interface{}, optionalArgs ...interface{}) interface{} {
//
// linear swap
//
// {
// "longLeverage": 5,
// "shortLeverage": 5,
// "maxLongLeverage": 125,
// "maxShortLeverage": 125,
// "availableLongVol": "0.0000",
// "availableShortVol": "0.0000",
// "availableLongVal": "0.0",
// "availableShortVal": "0.0",
// "maxPositionLongVal": "0.0",
// "maxPositionShortVal": "0.0"
// }
//
// inverse swap
//
// {
// "symbol": "SOL-USD",
// "longLeverage": 5,
// "shortLeverage": 5,
// "maxLongLeverage": 50,
// "maxShortLeverage": 50,
// "availableLongVol": "4000000",
// "availableShortVol": "4000000"
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(leverage, "symbol")
return map[string]interface{} {
"info": leverage,
"symbol": this.SafeSymbol(marketId, market),
"marginMode": nil,
"longLeverage": this.SafeInteger(leverage, "longLeverage"),
"shortLeverage": this.SafeInteger(leverage, "shortLeverage"),
}
}
/**
* @method
* @name bingx#setLeverage
* @description set the level of leverage for a market
* @see https://bingx-api.github.io/docs/#/swapV2/trade-api.html#Switch%20Leverage
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Modify%20Leverage
* @param {float} leverage the rate of leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.side] hedged: ['long' or 'short']. one way: ['both']
* @returns {object} response from the exchange
*/
func (this *bingx) SetLeverage(leverage interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " setLeverage() requires a symbol argument")))
}
var side interface{} = this.SafeStringUpper(params, "side")
this.CheckRequiredArgument("setLeverage", side, "side", []interface{}{"LONG", "SHORT", "BOTH"})
retRes54968 := (<-this.LoadMarkets())
PanicOnError(retRes54968)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"side": side,
"leverage": leverage,
}
if IsTrue(GetValue(market, "inverse")) {
retRes550419 := (<-this.CswapV1PrivatePostTradeLeverage(this.Extend(request, params)))
PanicOnError(retRes550419)
ch <- retRes550419
return nil
} else {
retRes552219 := (<-this.SwapV2PrivatePostTradeLeverage(this.Extend(request, params)))
PanicOnError(retRes552219)
ch <- retRes552219
return nil
}
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchMyTrades
* @description fetch all trades made by the user
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20transaction%20details
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20historical%20transaction%20orders
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20historical%20transaction%20details
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Order%20Trade%20Detail
* @param {string} [symbol] unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms for the ending date filter, default is undefined
* @param {string} params.trandingUnit COIN (directly represent assets such as BTC and ETH) or CONT (represents the number of contract sheets)
* @param {string} params.orderId the order id required for inverse swap
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure}
*/
func (this *bingx) FetchMyTrades(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchMyTrades() requires a symbol argument")))
}
retRes55638 := (<-this.LoadMarkets())
PanicOnError(retRes55638)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {}
var fills interface{} = nil
var response interface{} = nil
var subType interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchMyTrades", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
if IsTrue(IsEqual(subType, "inverse")) {
var orderId interface{} = this.SafeString(params, "orderId")
if IsTrue(IsEqual(orderId, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchMyTrades() requires an orderId argument for inverse swap trades")))
}
response = (<-this.CswapV1PrivateGetTradeAllFillOrders(this.Extend(request, params)))
PanicOnError(response)
fills = this.SafeList(response, "data", []interface{}{})
} else {
AddElementToObject(request, "symbol", GetValue(market, "id"))
var now interface{} = this.Milliseconds()
if IsTrue(!IsEqual(since, nil)) {
var startTimeReq interface{} = Ternary(IsTrue(GetValue(market, "spot")), "startTime", "startTs")
AddElementToObject(request, startTimeReq, since)
} else if IsTrue(GetValue(market, "swap")) {
AddElementToObject(request, "startTs", Subtract(now, Multiply(Multiply(Multiply(Multiply(30, 24), 60), 60), 1000))) // 30 days for swap
}
var until interface{} = this.SafeInteger(params, "until")
params = this.Omit(params, "until")
if IsTrue(!IsEqual(until, nil)) {
var endTimeReq interface{} = Ternary(IsTrue(GetValue(market, "spot")), "endTime", "endTs")
AddElementToObject(request, endTimeReq, until)
} else if IsTrue(GetValue(market, "swap")) {
AddElementToObject(request, "endTs", now)
}
if IsTrue(GetValue(market, "spot")) {
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "limit", limit) // default 500, maximum 1000
}
response = (<-this.SpotV1PrivateGetTradeMyTrades(this.Extend(request, params)))
PanicOnError(response)
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
fills = this.SafeList(data, "fills", []interface{}{})
} else {
var tradingUnit interface{} = this.SafeStringUpper(params, "tradingUnit", "CONT")
params = this.Omit(params, "tradingUnit")
AddElementToObject(request, "tradingUnit", tradingUnit)
response = (<-this.SwapV2PrivateGetTradeAllFillOrders(this.Extend(request, params)))
PanicOnError(response)
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
fills = this.SafeList(data, "fill_orders", []interface{}{})
}
}
ch <- this.ParseTrades(fills, market, since, limit, params)
return nil
}()
return ch
}
func (this *bingx) ParseDepositWithdrawFee(fee interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "coin": "BTC",
// "name": "BTC",
// "networkList": [
// {
// "name": "BTC",
// "network": "BTC",
// "isDefault": true,
// "minConfirm": "2",
// "withdrawEnable": true,
// "withdrawFee": "0.00035",
// "withdrawMax": "1.62842",
// "withdrawMin": "0.0005"
// },
// {
// "name": "BTC",
// "network": "BEP20",
// "isDefault": false,
// "minConfirm": "15",
// "withdrawEnable": true,
// "withdrawFee": "0.00001",
// "withdrawMax": "1.62734",
// "withdrawMin": "0.0001"
// }
// ]
// }
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
var networkList interface{} = this.SafeList(fee, "networkList", []interface{}{})
var networkListLength interface{} = GetArrayLength(networkList)
var result interface{} = map[string]interface{} {
"info": fee,
"withdraw": map[string]interface{} {
"fee": nil,
"percentage": nil,
},
"deposit": map[string]interface{} {
"fee": nil,
"percentage": nil,
},
"networks": map[string]interface{} {},
}
if IsTrue(!IsEqual(networkListLength, 0)) {
for i := 0; IsLessThan(i, networkListLength); i++ {
var network interface{} = GetValue(networkList, i)
var networkId interface{} = this.SafeString(network, "network")
var isDefault interface{} = this.SafeBool(network, "isDefault")
var currencyCode interface{} = this.SafeString(currency, "code")
var networkCode interface{} = this.NetworkIdToCode(networkId, currencyCode)
AddElementToObject(GetValue(result, "networks"), networkCode, map[string]interface{} {
"deposit": map[string]interface{} {
"fee": nil,
"percentage": nil,
},
"withdraw": map[string]interface{} {
"fee": this.SafeNumber(network, "withdrawFee"),
"percentage": false,
},
})
if IsTrue(isDefault) {
AddElementToObject(GetValue(result, "withdraw"), "fee", this.SafeNumber(network, "withdrawFee"))
AddElementToObject(GetValue(result, "withdraw"), "percentage", false)
}
}
}
return result
}
/**
* @method
* @name bingx#fetchDepositWithdrawFees
* @description fetch deposit and withdraw fees
* @see https://bingx-api.github.io/docs/#/common/account-api.html#All%20Coins'%20Information
* @param {string[]|undefined} codes list of unified currency codes
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [fee structures]{@link https://docs.ccxt.com/#/?id=fee-structure}
*/
func (this *bingx) FetchDepositWithdrawFees(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
codes := GetArg(optionalArgs, 0, nil)
_ = codes
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes57568 := (<-this.LoadMarkets())
PanicOnError(retRes57568)
response:= (<-this.WalletsV1PrivateGetCapitalConfigGetall(params))
PanicOnError(response)
var coins interface{} = this.SafeList(response, "data")
ch <- this.ParseDepositWithdrawFees(coins, codes, "coin")
return nil
}()
return ch
}
/**
* @method
* @name bingx#withdraw
* @description make a withdrawal
* @see https://bingx-api.github.io/docs/#/en-us/spot/wallet-api.html#Withdraw
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {string} [tag]
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.walletType] 1 fund account, 2 standard account, 3 perpetual account
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
func (this *bingx) Withdraw(code interface{}, amount interface{}, address interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
tag := GetArg(optionalArgs, 0, nil)
_ = tag
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
tagparamsVariable := this.HandleWithdrawTagAndParams(tag, params);
tag = GetValue(tagparamsVariable,0);
params = GetValue(tagparamsVariable,1)
this.CheckAddress(address)
retRes57788 := (<-this.LoadMarkets())
PanicOnError(retRes57788)
var currency interface{} = this.Currency(code)
var walletType interface{} = this.SafeInteger(params, "walletType")
if IsTrue(IsEqual(walletType, nil)) {
walletType = 1
}
if !IsTrue(this.InArray(walletType, []interface{}{1, 2, 3})) {
panic(BadRequest(Add(this.Id, " withdraw() requires either 1 fund account, 2 standard futures account, 3 perpetual account for walletType")))
}
var request interface{} = map[string]interface{} {
"coin": GetValue(currency, "id"),
"address": address,
"amount": this.CurrencyToPrecision(code, amount),
"walletType": walletType,
}
var network interface{} = this.SafeStringUpper(params, "network")
if IsTrue(!IsEqual(network, nil)) {
AddElementToObject(request, "network", this.NetworkCodeToId(network))
}
if IsTrue(!IsEqual(tag, nil)) {
AddElementToObject(request, "addressTag", tag)
}
params = this.Omit(params, []interface{}{"walletType", "network"})
response:= (<-this.WalletsV1PrivatePostCapitalWithdrawApply(this.Extend(request, params)))
PanicOnError(response)
var data interface{} = this.SafeValue(response, "data")
// {
// "code":0,
// "timestamp":1689258953651,
// "data":{
// "id":"1197073063359000577"
// }
// }
ch <- this.ParseTransaction(data)
return nil
}()
return ch
}
func (this *bingx) ParseParams(params interface{}) interface{} {
var sortedParams interface{} = this.Keysort(params)
var keys interface{} = ObjectKeys(sortedParams)
for i := 0; IsLessThan(i, GetArrayLength(keys)); i++ {
var key interface{} = GetValue(keys, i)
var value interface{} = GetValue(sortedParams, key)
if IsTrue(IsArray(value)) {
var arrStr interface{} = "["
for j := 0; IsLessThan(j, GetArrayLength(value)); j++ {
var arrayElement interface{} = GetValue(value, j)
if IsTrue(IsGreaterThan(j, 0)) {
arrStr = Add(arrStr, ",")
}
arrStr = Add(arrStr, ToString(arrayElement))
}
arrStr = Add(arrStr, "]")
AddElementToObject(sortedParams, key, arrStr)
}
}
return sortedParams
}
/**
* @method
* @name bingx#fetchMyLiquidations
* @description retrieves the users liquidated positions
* @see https://bingx-api.github.io/docs/#/swapV2/trade-api.html#User's%20Force%20Orders
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20force%20orders
* @param {string} [symbol] unified CCXT market symbol
* @param {int} [since] the earliest time in ms to fetch liquidations for
* @param {int} [limit] the maximum number of liquidation structures to retrieve
* @param {object} [params] exchange specific parameters for the bingx api endpoint
* @param {int} [params.until] timestamp in ms of the latest liquidation
* @returns {object} an array of [liquidation structures]{@link https://docs.ccxt.com/#/?id=liquidation-structure}
*/
func (this *bingx) FetchMyLiquidations(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes58498 := (<-this.LoadMarkets())
PanicOnError(retRes58498)
var request interface{} = map[string]interface{} {
"autoCloseType": "LIQUIDATION",
}
requestparamsVariable := this.HandleUntilOption("endTime", request, params);
request = GetValue(requestparamsVariable,0);
params = GetValue(requestparamsVariable,1)
var market interface{} = nil
if IsTrue(!IsEqual(symbol, nil)) {
market = this.Market(symbol)
AddElementToObject(request, "symbol", GetValue(market, "id"))
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startTime", since)
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "limit", limit)
}
var subType interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchMyLiquidations", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
var response interface{} = nil
var liquidations interface{} = nil
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PrivateGetTradeForceOrders(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1721280071678,
// "data": [
// {
// "orderId": "string",
// "symbol": "string",
// "type": "string",
// "side": "string",
// "positionSide": "string",
// "price": "string",
// "quantity": "float64",
// "stopPrice": "string",
// "workingType": "string",
// "status": "string",
// "time": "int64",
// "avgPrice": "string",
// "executedQty": "string",
// "profit": "string",
// "commission": "string",
// "updateTime": "string"
// }
// ]
// }
//
liquidations = this.SafeList(response, "data", []interface{}{})
} else {
response = (<-this.SwapV2PrivateGetTradeForceOrders(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "orders": [
// {
// "time": "int64",
// "symbol": "string",
// "side": "string",
// "type": "string",
// "positionSide": "string",
// "cumQuote": "string",
// "status": "string",
// "stopPrice": "string",
// "price": "string",
// "origQty": "string",
// "avgPrice": "string",
// "executedQty": "string",
// "orderId": "int64",
// "profit": "string",
// "commission": "string",
// "workingType": "string",
// "updateTime": "int64"
// },
// ]
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
liquidations = this.SafeList(data, "orders", []interface{}{})
}
ch <- this.ParseLiquidations(liquidations, market, since, limit)
return nil
}()
return ch
}
func (this *bingx) ParseLiquidation(liquidation interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "time": "int64",
// "symbol": "string",
// "side": "string",
// "type": "string",
// "positionSide": "string",
// "cumQuote": "string",
// "status": "string",
// "stopPrice": "string",
// "price": "string",
// "origQty": "string",
// "avgPrice": "string",
// "executedQty": "string",
// "orderId": "int64",
// "profit": "string",
// "commission": "string",
// "workingType": "string",
// "updateTime": "int64"
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(liquidation, "symbol")
var timestamp interface{} = this.SafeInteger(liquidation, "time")
var contractsString interface{} = this.SafeString(liquidation, "executedQty")
var contractSizeString interface{} = this.SafeString(market, "contractSize")
var priceString interface{} = this.SafeString(liquidation, "avgPrice")
var baseValueString interface{} = Precise.StringMul(contractsString, contractSizeString)
var quoteValueString interface{} = Precise.StringMul(baseValueString, priceString)
return this.SafeLiquidation(map[string]interface{} {
"info": liquidation,
"symbol": this.SafeSymbol(marketId, market),
"contracts": this.ParseNumber(contractsString),
"contractSize": this.ParseNumber(contractSizeString),
"price": this.ParseNumber(priceString),
"baseValue": this.ParseNumber(baseValueString),
"quoteValue": this.ParseNumber(quoteValueString),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
})
}
/**
* @method
* @name bingx#closePosition
* @description closes open positions for a market
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#One-Click%20Close%20All%20Positions
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Close%20all%20positions%20in%20bulk
* @param {string} symbol Unified CCXT market symbol
* @param {string} [side] not used by bingx
* @param {object} [params] extra parameters specific to the bingx api endpoint
* @param {string|undefined} [params.positionId] the id of the position you would like to close
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) ClosePosition(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
side := GetArg(optionalArgs, 0, nil)
_ = side
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes59918 := (<-this.LoadMarkets())
PanicOnError(retRes59918)
var market interface{} = this.Market(symbol)
var positionId interface{} = this.SafeString(params, "positionId")
var request interface{} = map[string]interface{} {}
var response interface{} = nil
if IsTrue(!IsEqual(positionId, nil)) {
response = (<-this.SwapV1PrivatePostTradeClosePosition(this.Extend(request, params)))
PanicOnError(response)
} else {
AddElementToObject(request, "symbol", GetValue(market, "id"))
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PrivatePostTradeCloseAllPositions(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivatePostTradeCloseAllPositions(this.Extend(request, params)))
PanicOnError(response)
}
}
var data interface{} = this.SafeDict(response, "data")
ch <- this.ParseOrder(data, market)
return nil
}()
return ch
}
/**
* @method
* @name bitget#closePositions
* @description closes open positions for a market
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#One-Click%20Close%20All%20Positions
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Close%20all%20positions%20in%20bulk
* @param {object} [params] extra parameters specific to the bingx api endpoint
* @param {string} [params.recvWindow] request valid time window value
* @returns {object[]} [a list of position structures]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *bingx) CloseAllPositions(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes60608 := (<-this.LoadMarkets())
PanicOnError(retRes60608)
var defaultRecvWindow interface{} = this.SafeInteger(this.Options, "recvWindow")
var recvWindow interface{} = this.SafeInteger(this.ParseParams, "recvWindow", defaultRecvWindow)
var marketType interface{} = nil
marketTypeparamsVariable := this.HandleMarketTypeAndParams("closeAllPositions", nil, params);
marketType = GetValue(marketTypeparamsVariable,0);
params = GetValue(marketTypeparamsVariable,1)
var subType interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("closeAllPositions", nil, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
if IsTrue(IsEqual(marketType, "margin")) {
panic(BadRequest(Add(Add(Add(this.Id, " closePositions () cannot be used for "), marketType), " markets")))
}
var request interface{} = map[string]interface{} {
"recvWindow": recvWindow,
}
var response interface{} = nil
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PrivatePostTradeCloseAllPositions(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivatePostTradeCloseAllPositions(this.Extend(request, params)))
PanicOnError(response)
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var success interface{} = this.SafeList(data, "success", []interface{}{})
var positions interface{} = []interface{}{}
for i := 0; IsLessThan(i, GetArrayLength(success)); i++ {
var position interface{} = this.ParsePosition(map[string]interface{} {
"positionId": GetValue(success, i),
})
AppendToArray(&positions,position)
}
ch <- positions
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchPositionMode
* @description fetchs the position mode, hedged or one way, hedged for binance is set identically for all linear markets or all inverse markets
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Get%20Position%20Mode
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an object detailing whether the market is in hedged or one-way mode
*/
func (this *bingx) FetchPositionMode(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
response:= (<-this.SwapV1PrivateGetPositionSideDual(params))
PanicOnError(response)
//
// {
// "code": "0",
// "msg": "",
// "timeStamp": "1709002057516",
// "data": {
// "dualSidePosition": "false"
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var dualSidePosition interface{} = this.SafeString(data, "dualSidePosition")
ch <- map[string]interface{} {
"info": response,
"hedged": (IsEqual(dualSidePosition, "true")),
}
return nil
}()
return ch
}
/**
* @method
* @name bingx#setPositionMode
* @description set hedged to true or false for a market
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Set%20Position%20Mode
* @param {bool} hedged set to true to use dualSidePosition
* @param {string} symbol not used by bingx setPositionMode ()
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
func (this *bingx) SetPositionMode(hedged interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
var dualSidePosition interface{} = nil
if IsTrue(hedged) {
dualSidePosition = "true"
} else {
dualSidePosition = "false"
}
var request interface{} = map[string]interface{} {
"dualSidePosition": dualSidePosition,
}
retRes617015 := (<-this.SwapV1PrivatePostPositionSideDual(this.Extend(request, params)))
PanicOnError(retRes617015)
//
// {
// code: '0',
// msg: '',
// timeStamp: '1703327432734',
// data: { dualSidePosition: 'false' }
// }
//
ch <- retRes617015
return nil
}()
return ch
}
/**
* @method
* @name bingx#editOrder
* @description cancels an order and places a new order
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Cancel%20order%20and%20place%20a%20new%20order // spot
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Cancel%20an%20order%20and%20then%20Place%20a%20new%20order // swap
* @param {string} id order id
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of the currency you want to trade in units of the base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.triggerPrice] Trigger price used for TAKE_STOP_LIMIT, TAKE_STOP_MARKET, TRIGGER_LIMIT, TRIGGER_MARKET order types.
* @param {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered
* @param {float} [params.takeProfit.triggerPrice] take profit trigger price
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered
* @param {float} [params.stopLoss.triggerPrice] stop loss trigger price
*
* EXCHANGE SPECIFIC PARAMETERS
* @param {string} [params.cancelClientOrderID] the user-defined id of the order to be canceled, 1-40 characters, different orders cannot use the same clientOrderID, only supports a query range of 2 hours
* @param {string} [params.cancelRestrictions] cancel orders with specified status, NEW: New order, PENDING: Pending order, PARTIALLY_FILLED: Partially filled
* @param {string} [params.cancelReplaceMode] STOP_ON_FAILURE - if the cancel order fails, it will not continue to place a new order, ALLOW_FAILURE - regardless of whether the cancel order succeeds or fails, it will continue to place a new order
* @param {float} [params.quoteOrderQty] order amount
* @param {string} [params.newClientOrderId] custom order id consisting of letters, numbers, and _, 1-40 characters, different orders cannot use the same newClientOrderId.
* @param {string} [params.positionSide] *contract only* position direction, required for single position as BOTH, for both long and short positions only LONG or SHORT can be chosen, defaults to LONG if empty
* @param {string} [params.reduceOnly] *contract only* true or false, default=false for single position mode. this parameter is not accepted for both long and short positions mode
* @param {float} [params.priceRate] *contract only* for type TRAILING_STOP_Market or TRAILING_TP_SL, Max = 1
* @param {string} [params.workingType] *contract only* StopPrice trigger price types, MARK_PRICE (default), CONTRACT_PRICE, or INDEX_PRICE
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *bingx) EditOrder(id interface{}, symbol interface{}, typeVar interface{}, side interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
amount := GetArg(optionalArgs, 0, nil)
_ = amount
price := GetArg(optionalArgs, 1, nil)
_ = price
params := GetArg(optionalArgs, 2, map[string]interface{} {})
_ = params
retRes62058 := (<-this.LoadMarkets())
PanicOnError(retRes62058)
var market interface{} = this.Market(symbol)
var request interface{} = this.CreateOrderRequest(symbol, typeVar, side, amount, price, params)
AddElementToObject(request, "cancelOrderId", id)
AddElementToObject(request, "cancelReplaceMode", "STOP_ON_FAILURE")
var response interface{} = nil
if IsTrue(GetValue(market, "swap")) {
response = (<-this.SwapV1PrivatePostTradeCancelReplace(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SpotV1PrivatePostTradeOrderCancelReplace(this.Extend(request, params)))
PanicOnError(response)
}
var data interface{} = this.SafeDict(response, "data")
ch <- this.ParseOrder(data, market)
return nil
}()
return ch
}
/**
* @method
* @name bingx#fetchMarginMode
* @description fetches the margin mode of the trading pair
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/trade-api.html#Query%20Margin%20Type
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Margin%20Type
* @param {string} symbol unified symbol of the market to fetch the margin mode for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin mode structure]{@link https://docs.ccxt.com/#/?id=margin-mode-structure}
*/
func (this *bingx) FetchMarginMode(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes63228 := (<-this.LoadMarkets())
PanicOnError(retRes63228)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var subType interface{} = nil
var response interface{} = nil
subTypeparamsVariable := this.HandleSubTypeAndParams("fetchMarginMode", market, params);
subType = GetValue(subTypeparamsVariable,0);
params = GetValue(subTypeparamsVariable,1)
if IsTrue(IsEqual(subType, "inverse")) {
response = (<-this.CswapV1PrivateGetTradeMarginType(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.SwapV2PrivateGetTradeMarginType(this.Extend(request, params)))
PanicOnError(response)
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
ch <- this.ParseMarginMode(data, market)
return nil
}()
return ch
}
func (this *bingx) ParseMarginMode(marginMode interface{}, optionalArgs ...interface{}) interface{} {
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(marginMode, "symbol")
var marginType interface{} = this.SafeStringLower(marginMode, "marginType")
marginType = Ternary(IsTrue((IsEqual(marginType, "crossed"))), "cross", marginType)
return map[string]interface{} {
"info": marginMode,
"symbol": this.SafeSymbol(marketId, market, "-", "swap"),
"marginMode": marginType,
}
}
/**
* @method
* @name bingx#fetchTradingFee
* @description fetch the trading fees for a market
* @see https://bingx-api.github.io/docs/#/en-us/spot/trade-api.html#Query%20Trading%20Commission%20Rate
* @see https://bingx-api.github.io/docs/#/en-us/swapV2/account-api.html#Query%20Trading%20Commission%20Rate
* @see https://bingx-api.github.io/docs/#/en-us/cswap/trade-api.html#Query%20Trade%20Commission%20Rate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [fee structure]{@link https://docs.ccxt.com/#/?id=fee-structure}
*/
func (this *bingx) FetchTradingFee(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes63828 := (<-this.LoadMarkets())
PanicOnError(retRes63828)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
var response interface{} = nil
var commission interface{} = map[string]interface{} {}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
if IsTrue(GetValue(market, "spot")) {
response = (<-this.SpotV1PrivateGetUserCommissionRate(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "debugMsg": "",
// "data": {
// "takerCommissionRate": 0.001,
// "makerCommissionRate": 0.001
// }
// }
//
commission = data
} else {
if IsTrue(GetValue(market, "inverse")) {
response = (<-this.CswapV1PrivateGetUserCommissionRate(params))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "timestamp": 1721365261438,
// "data": {
// "takerCommissionRate": "0.0005",
// "makerCommissionRate": "0.0002"
// }
// }
//
commission = data
} else {
response = (<-this.SwapV2PrivateGetUserCommissionRate(params))
PanicOnError(response)
//
// {
// "code": 0,
// "msg": "",
// "data": {
// "commission": {
// "takerCommissionRate": 0.0005,
// "makerCommissionRate": 0.0002
// }
// }
// }
//
commission = this.SafeDict(data, "commission", map[string]interface{} {})
}
}
ch <- this.ParseTradingFee(commission, market)
return nil
}()
return ch
}
func (this *bingx) ParseTradingFee(fee interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "takerCommissionRate": 0.001,
// "makerCommissionRate": 0.001
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var symbol interface{} = Ternary(IsTrue((!IsEqual(market, nil))), GetValue(market, "symbol"), nil)
return map[string]interface{} {
"info": fee,
"symbol": symbol,
"maker": this.SafeNumber(fee, "makerCommissionRate"),
"taker": this.SafeNumber(fee, "takerCommissionRate"),
"percentage": false,
"tierBased": false,
}
}
func (this *bingx) CustomEncode(params interface{}) interface{} {
var sortedParams interface{} = this.Keysort(params)
var keys interface{} = ObjectKeys(sortedParams)
var adjustedValue interface{} = nil
var result interface{} = nil
for i := 0; IsLessThan(i, GetArrayLength(keys)); i++ {
var key interface{} = GetValue(keys, i)
var value interface{} = GetValue(sortedParams, key)
if IsTrue(IsArray(value)) {
var arrStr interface{} = nil
for j := 0; IsLessThan(j, GetArrayLength(value)); j++ {
var arrayElement interface{} = GetValue(value, j)
var isString interface{} = (IsString(arrayElement))
if IsTrue(isString) {
if IsTrue(IsGreaterThan(j, 0)) {
arrStr = Add(arrStr, Add(Add(Add(",", "\""), ToString(arrayElement)), "\""))
} else {
arrStr = Add(Add("\"", ToString(arrayElement)), "\"")
}
} else {
if IsTrue(IsGreaterThan(j, 0)) {
arrStr = Add(arrStr, Add(",", ToString(arrayElement)))
} else {
arrStr = ToString(arrayElement)
}
}
}
adjustedValue = Add(Add("[", arrStr), "]")
value = adjustedValue
}
if IsTrue(IsEqual(i, 0)) {
result = Add(Add(key, "="), value)
} else {
result = Add(result, Add(Add(Add("&", key), "="), value))
}
}
return result
}
func (this *bingx) Sign(path interface{}, optionalArgs ...interface{}) interface{} {
section := GetArg(optionalArgs, 0, "public")
_ = section
method := GetArg(optionalArgs, 1, "GET")
_ = method
params := GetArg(optionalArgs, 2, map[string]interface{} {})
_ = params
headers := GetArg(optionalArgs, 3, nil)
_ = headers
body := GetArg(optionalArgs, 4, nil)
_ = body
var typeVar interface{} = GetValue(section, 0)
var version interface{} = GetValue(section, 1)
var access interface{} = GetValue(section, 2)
var isSandbox interface{} = this.SafeBool(this.Options, "sandboxMode", false)
if IsTrue(IsTrue(isSandbox) && IsTrue((!IsEqual(typeVar, "swap")))) {
panic(NotSupported(Add(Add(Add(this.Id, " does not have a testnet/sandbox URL for "), typeVar), " endpoints")))
}
var url interface{} = this.ImplodeHostname(GetValue(GetValue(this.Urls, "api"), typeVar))
path = this.ImplodeParams(path, params)
if IsTrue(IsEqual(version, "transfer")) {
typeVar = "account/transfer"
version = GetValue(section, 2)
access = GetValue(section, 3)
}
if IsTrue(!IsEqual(path, "account/apiPermissions")) {
if IsTrue(IsTrue(IsEqual(typeVar, "spot")) && IsTrue(IsEqual(version, "v3"))) {
url = Add(url, "/api")
} else {
url = Add(url, Add("/", typeVar))
}
}
url = Add(url, Add(Add(Add("/", version), "/"), path))
params = this.Omit(params, this.ExtractParams(path))
AddElementToObject(params, "timestamp", this.Nonce())
params = this.Keysort(params)
if IsTrue(IsEqual(access, "public")) {
if IsTrue(GetArrayLength(ObjectKeys(params))) {
url = Add(url, Add("?", this.Urlencode(params)))
}
} else if IsTrue(IsEqual(access, "private")) {
this.CheckRequiredCredentials()
var isJsonContentType interface{} = (IsTrue((IsTrue((IsEqual(typeVar, "subAccount"))) || IsTrue((IsEqual(typeVar, "account/transfer"))))) && IsTrue((IsEqual(method, "POST"))))
var parsedParams interface{} = nil
var encodeRequest interface{} = nil
if IsTrue(isJsonContentType) {
encodeRequest = this.CustomEncode(params)
} else {
parsedParams = this.ParseParams(params)
encodeRequest = this.Rawencode(parsedParams)
}
var signature interface{} = this.Hmac(this.Encode(encodeRequest), this.Encode(this.Secret), sha256)
headers = map[string]interface{} {
"X-BX-APIKEY": this.ApiKey,
"X-SOURCE-KEY": this.SafeString(this.Options, "broker", "CCXT"),
}
if IsTrue(isJsonContentType) {
AddElementToObject(headers, "Content-Type", "application/json")
AddElementToObject(params, "signature", signature)
body = this.Json(params)
} else {
var query interface{} = this.Urlencode(parsedParams)
url = Add(url, Add(Add(Add(Add("?", query), "&"), "signature="), signature))
}
}
return map[string]interface{} {
"url": url,
"method": method,
"body": body,
"headers": headers,
}
}
func (this *bingx) Nonce() interface{} {
return this.Milliseconds()
}
func (this *bingx) SetSandboxMode(enable interface{}) {
this.Exchange.SetSandboxMode(enable)
AddElementToObject(this.Options, "sandboxMode", enable)
}
func (this *bingx) HandleErrors(httpCode interface{}, reason interface{}, url interface{}, method interface{}, headers interface{}, body interface{}, response interface{}, requestHeaders interface{}, requestBody interface{}) interface{} {
if IsTrue(IsEqual(response, nil)) {
return nil // fallback to default error handler
}
//
// {
// "code": 80014,
// "msg": "Invalid parameters, err:Key: 'GetTickerRequest.Symbol' Error:Field validation for "Symbol" failed on the "len=0|endswith=-USDT" tag",
// "data": {
// }
// }
//
var code interface{} = this.SafeString(response, "code")
var message interface{} = this.SafeString(response, "msg")
if IsTrue(IsTrue(!IsEqual(code, nil)) && IsTrue(!IsEqual(code, "0"))) {
var feedback interface{} = Add(Add(this.Id, " "), body)
this.ThrowExactlyMatchedException(GetValue(this.Exceptions, "exact"), message, feedback)
this.ThrowExactlyMatchedException(GetValue(this.Exceptions, "exact"), code, feedback)
this.ThrowBroadlyMatchedException(GetValue(this.Exceptions, "broad"), message, feedback)
panic(ExchangeError(feedback))
}
return nil
}
func (this *bingx) Init(userConfig map[string]interface{}) {
this.Exchange = Exchange{}
this.Exchange.InitParent(userConfig, this.Describe().(map[string]interface{}), this)
this.Exchange.DerivedExchange = this
}