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 binance struct { Exchange } func NewBinanceCore() binance { p := binance{} setDefaults(&p) return p } func (this *binance) Describe() interface{} { return this.DeepExtend(this.Exchange.Describe(), map[string]interface{} { "id": "binance", "name": "Binance", "countries": []interface{}{"JP", "MT"}, "rateLimit": 50, "certified": true, "pro": true, "has": map[string]interface{} { "CORS": nil, "spot": true, "margin": true, "swap": true, "future": true, "option": true, "addMargin": true, "borrowCrossMargin": true, "borrowIsolatedMargin": true, "cancelAllOrders": true, "cancelOrder": true, "cancelOrders": true, "closeAllPositions": false, "closePosition": false, "createConvertTrade": true, "createDepositAddress": false, "createLimitBuyOrder": true, "createLimitSellOrder": true, "createMarketBuyOrder": true, "createMarketBuyOrderWithCost": true, "createMarketOrderWithCost": true, "createMarketSellOrder": true, "createMarketSellOrderWithCost": true, "createOrder": true, "createOrders": true, "createOrderWithTakeProfitAndStopLoss": false, "createPostOnlyOrder": true, "createReduceOnlyOrder": true, "createStopLimitOrder": true, "createStopLossOrder": true, "createStopMarketOrder": false, "createStopOrder": true, "createTakeProfitOrder": true, "createTrailingPercentOrder": true, "createTriggerOrder": true, "editOrder": true, "editOrders": true, "fetchAccounts": nil, "fetchBalance": true, "fetchBidsAsks": true, "fetchBorrowInterest": true, "fetchBorrowRateHistories": false, "fetchBorrowRateHistory": true, "fetchCanceledAndClosedOrders": "emulated", "fetchCanceledOrders": "emulated", "fetchClosedOrder": false, "fetchClosedOrders": "emulated", "fetchConvertCurrencies": true, "fetchConvertQuote": true, "fetchConvertTrade": true, "fetchConvertTradeHistory": true, "fetchCrossBorrowRate": true, "fetchCrossBorrowRates": false, "fetchCurrencies": true, "fetchDeposit": false, "fetchDepositAddress": true, "fetchDepositAddresses": false, "fetchDepositAddressesByNetwork": false, "fetchDeposits": true, "fetchDepositsWithdrawals": false, "fetchDepositWithdrawFee": "emulated", "fetchDepositWithdrawFees": true, "fetchFundingHistory": true, "fetchFundingInterval": "emulated", "fetchFundingIntervals": true, "fetchFundingRate": true, "fetchFundingRateHistory": true, "fetchFundingRates": true, "fetchGreeks": true, "fetchIndexOHLCV": true, "fetchIsolatedBorrowRate": "emulated", "fetchIsolatedBorrowRates": true, "fetchL3OrderBook": false, "fetchLastPrices": true, "fetchLedger": true, "fetchLedgerEntry": true, "fetchLeverage": "emulated", "fetchLeverages": true, "fetchLeverageTiers": true, "fetchLiquidations": false, "fetchLongShortRatio": false, "fetchLongShortRatioHistory": true, "fetchMarginAdjustmentHistory": true, "fetchMarginMode": true, "fetchMarginModes": true, "fetchMarketLeverageTiers": "emulated", "fetchMarkets": true, "fetchMarkOHLCV": true, "fetchMarkPrice": true, "fetchMarkPrices": true, "fetchMyLiquidations": true, "fetchMySettlementHistory": true, "fetchMyTrades": true, "fetchOHLCV": true, "fetchOpenInterest": true, "fetchOpenInterestHistory": true, "fetchOpenOrder": true, "fetchOpenOrders": true, "fetchOption": true, "fetchOptionChain": false, "fetchOrder": true, "fetchOrderBook": true, "fetchOrderBooks": false, "fetchOrders": true, "fetchOrderTrades": true, "fetchPosition": true, "fetchPositionHistory": false, "fetchPositionMode": true, "fetchPositions": true, "fetchPositionsHistory": false, "fetchPositionsRisk": true, "fetchPremiumIndexOHLCV": true, "fetchSettlementHistory": true, "fetchStatus": true, "fetchTicker": true, "fetchTickers": true, "fetchTime": true, "fetchTrades": true, "fetchTradingFee": true, "fetchTradingFees": true, "fetchTradingLimits": "emulated", "fetchTransactionFee": "emulated", "fetchTransactionFees": true, "fetchTransactions": false, "fetchTransfer": false, "fetchTransfers": true, "fetchUnderlyingAssets": false, "fetchVolatilityHistory": false, "fetchWithdrawAddresses": false, "fetchWithdrawal": false, "fetchWithdrawals": true, "fetchWithdrawalWhitelist": false, "reduceMargin": true, "repayCrossMargin": true, "repayIsolatedMargin": true, "sandbox": true, "setLeverage": true, "setMargin": false, "setMarginMode": true, "setPositionMode": true, "signIn": false, "transfer": true, "withdraw": true, }, "timeframes": map[string]interface{} { "1s": "1s", "1m": "1m", "3m": "3m", "5m": "5m", "15m": "15m", "30m": "30m", "1h": "1h", "2h": "2h", "4h": "4h", "6h": "6h", "8h": "8h", "12h": "12h", "1d": "1d", "3d": "3d", "1w": "1w", "1M": "1M", }, "urls": map[string]interface{} { "logo": "https://github.com/user-attachments/assets/e9419b93-ccb0-46aa-9bff-c883f096274b", "test": map[string]interface{} { "dapiPublic": "https://testnet.binancefuture.com/dapi/v1", "dapiPrivate": "https://testnet.binancefuture.com/dapi/v1", "dapiPrivateV2": "https://testnet.binancefuture.com/dapi/v2", "fapiPublic": "https://testnet.binancefuture.com/fapi/v1", "fapiPublicV2": "https://testnet.binancefuture.com/fapi/v2", "fapiPublicV3": "https://testnet.binancefuture.com/fapi/v3", "fapiPrivate": "https://testnet.binancefuture.com/fapi/v1", "fapiPrivateV2": "https://testnet.binancefuture.com/fapi/v2", "fapiPrivateV3": "https://testnet.binancefuture.com/fapi/v3", "public": "https://testnet.binance.vision/api/v3", "private": "https://testnet.binance.vision/api/v3", "v1": "https://testnet.binance.vision/api/v1", }, "api": map[string]interface{} { "sapi": "https://api.binance.com/sapi/v1", "sapiV2": "https://api.binance.com/sapi/v2", "sapiV3": "https://api.binance.com/sapi/v3", "sapiV4": "https://api.binance.com/sapi/v4", "dapiPublic": "https://dapi.binance.com/dapi/v1", "dapiPrivate": "https://dapi.binance.com/dapi/v1", "eapiPublic": "https://eapi.binance.com/eapi/v1", "eapiPrivate": "https://eapi.binance.com/eapi/v1", "dapiPrivateV2": "https://dapi.binance.com/dapi/v2", "dapiData": "https://dapi.binance.com/futures/data", "fapiPublic": "https://fapi.binance.com/fapi/v1", "fapiPublicV2": "https://fapi.binance.com/fapi/v2", "fapiPublicV3": "https://fapi.binance.com/fapi/v3", "fapiPrivate": "https://fapi.binance.com/fapi/v1", "fapiPrivateV2": "https://fapi.binance.com/fapi/v2", "fapiPrivateV3": "https://fapi.binance.com/fapi/v3", "fapiData": "https://fapi.binance.com/futures/data", "public": "https://api.binance.com/api/v3", "private": "https://api.binance.com/api/v3", "v1": "https://api.binance.com/api/v1", "papi": "https://papi.binance.com/papi/v1", }, "www": "https://www.binance.com", "referral": map[string]interface{} { "url": "https://accounts.binance.com/en/register?ref=D7YA7CLY", "discount": 0.1, }, "doc": []interface{}{"https://developers.binance.com/en"}, "api_management": "https://www.binance.com/en/usercenter/settings/api-management", "fees": "https://www.binance.com/en/fee/schedule", }, "api": map[string]interface{} { "sapi": map[string]interface{} { "get": map[string]interface{} { "copyTrading/futures/userStatus": 2, "copyTrading/futures/leadSymbol": 2, "system/status": 0.1, "accountSnapshot": 240, "account/info": 0.1, "margin/asset": 1, "margin/pair": 1, "margin/allAssets": 0.1, "margin/allPairs": 0.1, "margin/priceIndex": 1, "spot/delist-schedule": 10, "asset/assetDividend": 1, "asset/dribblet": 0.1, "asset/transfer": 0.1, "asset/assetDetail": 0.1, "asset/tradeFee": 0.1, "asset/ledger-transfer/cloud-mining/queryByPage": 4.0002, "asset/convert-transfer/queryByPage": 0.033335, "asset/wallet/balance": 6, "asset/custody/transfer-history": 6, "margin/borrow-repay": 1, "margin/loan": 1, "margin/repay": 1, "margin/account": 1, "margin/transfer": 0.1, "margin/interestHistory": 0.1, "margin/forceLiquidationRec": 0.1, "margin/order": 1, "margin/openOrders": 1, "margin/allOrders": 20, "margin/myTrades": 1, "margin/maxBorrowable": 5, "margin/maxTransferable": 5, "margin/tradeCoeff": 1, "margin/isolated/transfer": 0.1, "margin/isolated/account": 1, "margin/isolated/pair": 1, "margin/isolated/allPairs": 1, "margin/isolated/accountLimit": 0.1, "margin/interestRateHistory": 0.1, "margin/orderList": 1, "margin/allOrderList": 20, "margin/openOrderList": 1, "margin/crossMarginData": map[string]interface{} { "cost": 0.1, "noCoin": 0.5, }, "margin/isolatedMarginData": map[string]interface{} { "cost": 0.1, "noCoin": 1, }, "margin/isolatedMarginTier": 0.1, "margin/rateLimit/order": 2, "margin/dribblet": 0.1, "margin/dust": 20.001, "margin/crossMarginCollateralRatio": 10, "margin/exchange-small-liability": 0.6667, "margin/exchange-small-liability-history": 0.6667, "margin/next-hourly-interest-rate": 0.6667, "margin/capital-flow": 10, "margin/delist-schedule": 10, "margin/available-inventory": 0.3334, "margin/leverageBracket": 0.1, "loan/vip/loanable/data": 40, "loan/vip/collateral/data": 40, "loan/vip/request/data": 2.6668, "loan/vip/request/interestRate": 2.6668, "loan/income": 40.002, "loan/ongoing/orders": 40, "loan/ltv/adjustment/history": 40, "loan/borrow/history": 40, "loan/repay/history": 40, "loan/loanable/data": 40, "loan/collateral/data": 40, "loan/repay/collateral/rate": 600, "loan/flexible/ongoing/orders": 30, "loan/flexible/borrow/history": 40, "loan/flexible/repay/history": 40, "loan/flexible/ltv/adjustment/history": 40, "loan/vip/ongoing/orders": 40, "loan/vip/repay/history": 40, "loan/vip/collateral/account": 600, "fiat/orders": 600.03, "fiat/payments": 0.1, "futures/transfer": 1, "futures/histDataLink": 0.1, "rebate/taxQuery": 80.004, "capital/config/getall": 1, "capital/deposit/address": 1, "capital/deposit/address/list": 1, "capital/deposit/hisrec": 0.1, "capital/deposit/subAddress": 0.1, "capital/deposit/subHisrec": 0.1, "capital/withdraw/history": 2, "capital/withdraw/address/list": 10, "capital/contract/convertible-coins": 4.0002, "convert/tradeFlow": 20.001, "convert/exchangeInfo": 50, "convert/assetInfo": 10, "convert/orderStatus": 0.6667, "convert/limit/queryOpenOrders": 20.001, "account/status": 0.1, "account/apiTradingStatus": 0.1, "account/apiRestrictions/ipRestriction": 0.1, "bnbBurn": 0.1, "sub-account/futures/account": 1, "sub-account/futures/accountSummary": 0.1, "sub-account/futures/positionRisk": 1, "sub-account/futures/internalTransfer": 0.1, "sub-account/list": 0.1, "sub-account/margin/account": 1, "sub-account/margin/accountSummary": 1, "sub-account/spotSummary": 0.1, "sub-account/status": 1, "sub-account/sub/transfer/history": 0.1, "sub-account/transfer/subUserHistory": 0.1, "sub-account/universalTransfer": 0.1, "sub-account/apiRestrictions/ipRestriction/thirdPartyList": 1, "sub-account/transaction-statistics": 0.40002, "sub-account/subAccountApi/ipRestriction": 20.001, "managed-subaccount/asset": 0.1, "managed-subaccount/accountSnapshot": 240, "managed-subaccount/queryTransLogForInvestor": 0.1, "managed-subaccount/queryTransLogForTradeParent": 0.40002, "managed-subaccount/fetch-future-asset": 0.40002, "managed-subaccount/marginAsset": 0.1, "managed-subaccount/info": 0.40002, "managed-subaccount/deposit/address": 0.006667, "managed-subaccount/query-trans-log": 0.40002, "lending/daily/product/list": 0.1, "lending/daily/userLeftQuota": 0.1, "lending/daily/userRedemptionQuota": 0.1, "lending/daily/token/position": 0.1, "lending/union/account": 0.1, "lending/union/purchaseRecord": 0.1, "lending/union/redemptionRecord": 0.1, "lending/union/interestHistory": 0.1, "lending/project/list": 0.1, "lending/project/position/list": 0.1, "eth-staking/eth/history/stakingHistory": 15, "eth-staking/eth/history/redemptionHistory": 15, "eth-staking/eth/history/rewardsHistory": 15, "eth-staking/eth/quota": 15, "eth-staking/eth/history/rateHistory": 15, "eth-staking/account": 15, "eth-staking/wbeth/history/wrapHistory": 15, "eth-staking/wbeth/history/unwrapHistory": 15, "eth-staking/eth/history/wbethRewardsHistory": 15, "sol-staking/sol/history/stakingHistory": 15, "sol-staking/sol/history/redemptionHistory": 15, "sol-staking/sol/history/bnsolRewardsHistory": 15, "sol-staking/sol/history/rateHistory": 15, "sol-staking/account": 15, "sol-staking/sol/quota": 15, "mining/pub/algoList": 0.1, "mining/pub/coinList": 0.1, "mining/worker/detail": 0.5, "mining/worker/list": 0.5, "mining/payment/list": 0.5, "mining/statistics/user/status": 0.5, "mining/statistics/user/list": 0.5, "mining/payment/uid": 0.5, "bswap/pools": 0.1, "bswap/liquidity": map[string]interface{} { "cost": 0.1, "noPoolId": 1, }, "bswap/liquidityOps": 20.001, "bswap/quote": 1.00005, "bswap/swap": 20.001, "bswap/poolConfigure": 1.00005, "bswap/addLiquidityPreview": 1.00005, "bswap/removeLiquidityPreview": 1.00005, "bswap/unclaimedRewards": 6.667, "bswap/claimedHistory": 6.667, "blvt/tokenInfo": 0.1, "blvt/subscribe/record": 0.1, "blvt/redeem/record": 0.1, "blvt/userLimit": 0.1, "apiReferral/ifNewUser": 1, "apiReferral/customization": 1, "apiReferral/userCustomization": 1, "apiReferral/rebate/recentRecord": 1, "apiReferral/rebate/historicalRecord": 1, "apiReferral/kickback/recentRecord": 1, "apiReferral/kickback/historicalRecord": 1, "broker/subAccountApi": 1, "broker/subAccount": 1, "broker/subAccountApi/commission/futures": 1, "broker/subAccountApi/commission/coinFutures": 1, "broker/info": 1, "broker/transfer": 1, "broker/transfer/futures": 1, "broker/rebate/recentRecord": 1, "broker/rebate/historicalRecord": 1, "broker/subAccount/bnbBurn/status": 1, "broker/subAccount/depositHist": 1, "broker/subAccount/spotSummary": 1, "broker/subAccount/marginSummary": 1, "broker/subAccount/futuresSummary": 1, "broker/rebate/futures/recentRecord": 1, "broker/subAccountApi/ipRestriction": 1, "broker/universalTransfer": 1, "account/apiRestrictions": 0.1, "c2c/orderMatch/listUserOrderHistory": 0.1, "nft/history/transactions": 20.001, "nft/history/deposit": 20.001, "nft/history/withdraw": 20.001, "nft/user/getAsset": 20.001, "pay/transactions": 20.001, "giftcard/verify": 0.1, "giftcard/cryptography/rsa-public-key": 0.1, "giftcard/buyCode/token-limit": 0.1, "algo/spot/openOrders": 0.1, "algo/spot/historicalOrders": 0.1, "algo/spot/subOrders": 0.1, "algo/futures/openOrders": 0.1, "algo/futures/historicalOrders": 0.1, "algo/futures/subOrders": 0.1, "portfolio/account": 0.1, "portfolio/collateralRate": 5, "portfolio/pmLoan": 3.3335, "portfolio/interest-history": 0.6667, "portfolio/asset-index-price": 0.1, "portfolio/repay-futures-switch": 3, "portfolio/margin-asset-leverage": 5, "portfolio/balance": 2, "portfolio/negative-balance-exchange-record": 2, "staking/productList": 0.1, "staking/position": 0.1, "staking/stakingRecord": 0.1, "staking/personalLeftQuota": 0.1, "lending/auto-invest/target-asset/list": 0.1, "lending/auto-invest/target-asset/roi/list": 0.1, "lending/auto-invest/all/asset": 0.1, "lending/auto-invest/source-asset/list": 0.1, "lending/auto-invest/plan/list": 0.1, "lending/auto-invest/plan/id": 0.1, "lending/auto-invest/history/list": 0.1, "lending/auto-invest/index/info": 0.1, "lending/auto-invest/index/user-summary": 0.1, "lending/auto-invest/one-off/status": 0.1, "lending/auto-invest/redeem/history": 0.1, "lending/auto-invest/rebalance/history": 0.1, "simple-earn/flexible/list": 15, "simple-earn/locked/list": 15, "simple-earn/flexible/personalLeftQuota": 15, "simple-earn/locked/personalLeftQuota": 15, "simple-earn/flexible/subscriptionPreview": 15, "simple-earn/locked/subscriptionPreview": 15, "simple-earn/flexible/history/rateHistory": 15, "simple-earn/flexible/position": 15, "simple-earn/locked/position": 15, "simple-earn/account": 15, "simple-earn/flexible/history/subscriptionRecord": 15, "simple-earn/locked/history/subscriptionRecord": 15, "simple-earn/flexible/history/redemptionRecord": 15, "simple-earn/locked/history/redemptionRecord": 15, "simple-earn/flexible/history/rewardsRecord": 15, "simple-earn/locked/history/rewardsRecord": 15, "simple-earn/flexible/history/collateralRecord": 0.1, "dci/product/list": 0.1, "dci/product/positions": 0.1, "dci/product/accounts": 0.1, }, "post": map[string]interface{} { "asset/dust": 0.06667, "asset/dust-btc": 0.1, "asset/transfer": 6.0003, "asset/get-funding-asset": 0.1, "asset/convert-transfer": 0.033335, "account/disableFastWithdrawSwitch": 0.1, "account/enableFastWithdrawSwitch": 0.1, "capital/withdraw/apply": 4.0002, "capital/contract/convertible-coins": 4.0002, "capital/deposit/credit-apply": 0.1, "margin/borrow-repay": 20.001, "margin/transfer": 4.0002, "margin/loan": 20.001, "margin/repay": 20.001, "margin/order": 0.040002, "margin/order/oco": 0.040002, "margin/dust": 20.001, "margin/exchange-small-liability": 20.001, "margin/isolated/transfer": 4.0002, "margin/isolated/account": 2.0001, "margin/max-leverage": 300, "bnbBurn": 0.1, "sub-account/virtualSubAccount": 0.1, "sub-account/margin/transfer": 4.0002, "sub-account/margin/enable": 0.1, "sub-account/futures/enable": 0.1, "sub-account/futures/transfer": 0.1, "sub-account/futures/internalTransfer": 0.1, "sub-account/transfer/subToSub": 0.1, "sub-account/transfer/subToMaster": 0.1, "sub-account/universalTransfer": 0.1, "sub-account/options/enable": 0.1, "managed-subaccount/deposit": 0.1, "managed-subaccount/withdraw": 0.1, "userDataStream": 0.1, "userDataStream/isolated": 0.1, "futures/transfer": 0.1, "lending/customizedFixed/purchase": 0.1, "lending/daily/purchase": 0.1, "lending/daily/redeem": 0.1, "bswap/liquidityAdd": 60, "bswap/liquidityRemove": 60, "bswap/swap": 60, "bswap/claimRewards": 6.667, "blvt/subscribe": 0.1, "blvt/redeem": 0.1, "apiReferral/customization": 1, "apiReferral/userCustomization": 1, "apiReferral/rebate/historicalRecord": 1, "apiReferral/kickback/historicalRecord": 1, "broker/subAccount": 1, "broker/subAccount/margin": 1, "broker/subAccount/futures": 1, "broker/subAccountApi": 1, "broker/subAccountApi/permission": 1, "broker/subAccountApi/commission": 1, "broker/subAccountApi/commission/futures": 1, "broker/subAccountApi/commission/coinFutures": 1, "broker/transfer": 1, "broker/transfer/futures": 1, "broker/rebate/historicalRecord": 1, "broker/subAccount/bnbBurn/spot": 1, "broker/subAccount/bnbBurn/marginInterest": 1, "broker/subAccount/blvt": 1, "broker/subAccountApi/ipRestriction": 1, "broker/subAccountApi/ipRestriction/ipList": 1, "broker/universalTransfer": 1, "broker/subAccountApi/permission/universalTransfer": 1, "broker/subAccountApi/permission/vanillaOptions": 1, "giftcard/createCode": 0.1, "giftcard/redeemCode": 0.1, "giftcard/buyCode": 0.1, "algo/spot/newOrderTwap": 20.001, "algo/futures/newOrderVp": 20.001, "algo/futures/newOrderTwap": 20.001, "staking/purchase": 0.1, "staking/redeem": 0.1, "staking/setAutoStaking": 0.1, "eth-staking/eth/stake": 15, "eth-staking/eth/redeem": 15, "eth-staking/wbeth/wrap": 15, "sol-staking/sol/stake": 15, "sol-staking/sol/redeem": 15, "mining/hash-transfer/config": 0.5, "mining/hash-transfer/config/cancel": 0.5, "portfolio/repay": 20.001, "loan/vip/renew": 40.002, "loan/vip/borrow": 40.002, "loan/borrow": 40.002, "loan/repay": 40.002, "loan/adjust/ltv": 40.002, "loan/customize/margin_call": 40.002, "loan/flexible/repay": 40.002, "loan/flexible/adjust/ltv": 40.002, "loan/vip/repay": 40.002, "convert/getQuote": 1.3334, "convert/acceptQuote": 3.3335, "convert/limit/placeOrder": 3.3335, "convert/limit/cancelOrder": 1.3334, "portfolio/auto-collection": 150, "portfolio/asset-collection": 6, "portfolio/bnb-transfer": 150, "portfolio/repay-futures-switch": 150, "portfolio/repay-futures-negative-balance": 150, "portfolio/mint": 20, "portfolio/redeem": 20, "lending/auto-invest/plan/add": 0.1, "lending/auto-invest/plan/edit": 0.1, "lending/auto-invest/plan/edit-status": 0.1, "lending/auto-invest/one-off": 0.1, "lending/auto-invest/redeem": 0.1, "simple-earn/flexible/subscribe": 0.1, "simple-earn/locked/subscribe": 0.1, "simple-earn/flexible/redeem": 0.1, "simple-earn/locked/redeem": 0.1, "simple-earn/flexible/setAutoSubscribe": 15, "simple-earn/locked/setAutoSubscribe": 15, "simple-earn/locked/setRedeemOption": 5, "dci/product/subscribe": 0.1, "dci/product/auto_compound/edit": 0.1, }, "put": map[string]interface{} { "userDataStream": 0.1, "userDataStream/isolated": 0.1, }, "delete": map[string]interface{} { "margin/openOrders": 0.1, "margin/order": 0.006667, "margin/orderList": 0.006667, "margin/isolated/account": 2.0001, "userDataStream": 0.1, "userDataStream/isolated": 0.1, "broker/subAccountApi": 1, "broker/subAccountApi/ipRestriction/ipList": 1, "algo/spot/order": 0.1, "algo/futures/order": 0.1, "sub-account/subAccountApi/ipRestriction/ipList": 20.001, }, }, "sapiV2": map[string]interface{} { "get": map[string]interface{} { "eth-staking/account": 15, "sub-account/futures/account": 0.1, "sub-account/futures/accountSummary": 1, "sub-account/futures/positionRisk": 0.1, "loan/flexible/ongoing/orders": 30, "loan/flexible/borrow/history": 40, "loan/flexible/repay/history": 40, "loan/flexible/ltv/adjustment/history": 40, "loan/flexible/loanable/data": 40, "loan/flexible/collateral/data": 40, "portfolio/account": 2, }, "post": map[string]interface{} { "eth-staking/eth/stake": 15, "sub-account/subAccountApi/ipRestriction": 20.001, "loan/flexible/borrow": 40.002, "loan/flexible/repay": 40.002, "loan/flexible/adjust/ltv": 40.002, }, }, "sapiV3": map[string]interface{} { "get": map[string]interface{} { "sub-account/assets": 0.40002, }, "post": map[string]interface{} { "asset/getUserAsset": 0.5, }, }, "sapiV4": map[string]interface{} { "get": map[string]interface{} { "sub-account/assets": 0.40002, }, }, "dapiPublic": map[string]interface{} { "get": map[string]interface{} { "ping": 1, "time": 1, "exchangeInfo": 1, "depth": map[string]interface{} { "cost": 2, "byLimit": []interface{}{[]interface{}{50, 2}, []interface{}{100, 5}, []interface{}{500, 10}, []interface{}{1000, 20}}, }, "trades": 5, "historicalTrades": 20, "aggTrades": 20, "premiumIndex": 10, "fundingRate": 1, "klines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "continuousKlines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "indexPriceKlines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "markPriceKlines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "premiumIndexKlines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "ticker/24hr": map[string]interface{} { "cost": 1, "noSymbol": 40, }, "ticker/price": map[string]interface{} { "cost": 1, "noSymbol": 2, }, "ticker/bookTicker": map[string]interface{} { "cost": 2, "noSymbol": 5, }, "constituents": 2, "openInterest": 1, "fundingInfo": 1, }, }, "dapiData": map[string]interface{} { "get": map[string]interface{} { "delivery-price": 1, "openInterestHist": 1, "topLongShortAccountRatio": 1, "topLongShortPositionRatio": 1, "globalLongShortAccountRatio": 1, "takerBuySellVol": 1, "basis": 1, }, }, "dapiPrivate": map[string]interface{} { "get": map[string]interface{} { "positionSide/dual": 30, "orderAmendment": 1, "order": 1, "openOrder": 1, "openOrders": map[string]interface{} { "cost": 1, "noSymbol": 5, }, "allOrders": map[string]interface{} { "cost": 20, "noSymbol": 40, }, "balance": 1, "account": 5, "positionMargin/history": 1, "positionRisk": 1, "userTrades": map[string]interface{} { "cost": 20, "noSymbol": 40, }, "income": 20, "leverageBracket": 1, "forceOrders": map[string]interface{} { "cost": 20, "noSymbol": 50, }, "adlQuantile": 5, "commissionRate": 20, "income/asyn": 5, "income/asyn/id": 5, "trade/asyn": 0.5, "trade/asyn/id": 0.5, "order/asyn": 0.5, "order/asyn/id": 0.5, "pmExchangeInfo": 0.5, "pmAccountInfo": 0.5, }, "post": map[string]interface{} { "positionSide/dual": 1, "order": 4, "batchOrders": 5, "countdownCancelAll": 10, "leverage": 1, "marginType": 1, "positionMargin": 1, "listenKey": 1, }, "put": map[string]interface{} { "listenKey": 1, "order": 1, "batchOrders": 5, }, "delete": map[string]interface{} { "order": 1, "allOpenOrders": 1, "batchOrders": 5, "listenKey": 1, }, }, "dapiPrivateV2": map[string]interface{} { "get": map[string]interface{} { "leverageBracket": 1, }, }, "fapiPublic": map[string]interface{} { "get": map[string]interface{} { "ping": 1, "time": 1, "exchangeInfo": 1, "depth": map[string]interface{} { "cost": 2, "byLimit": []interface{}{[]interface{}{50, 2}, []interface{}{100, 5}, []interface{}{500, 10}, []interface{}{1000, 20}}, }, "trades": 5, "historicalTrades": 20, "aggTrades": 20, "klines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "continuousKlines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "markPriceKlines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "indexPriceKlines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "premiumIndexKlines": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{99, 1}, []interface{}{499, 2}, []interface{}{1000, 5}, []interface{}{10000, 10}}, }, "fundingRate": 1, "fundingInfo": 1, "premiumIndex": 1, "ticker/24hr": map[string]interface{} { "cost": 1, "noSymbol": 40, }, "ticker/price": map[string]interface{} { "cost": 1, "noSymbol": 2, }, "ticker/bookTicker": map[string]interface{} { "cost": 1, "noSymbol": 2, }, "openInterest": 1, "indexInfo": 1, "assetIndex": map[string]interface{} { "cost": 1, "noSymbol": 10, }, "constituents": 2, "apiTradingStatus": map[string]interface{} { "cost": 1, "noSymbol": 10, }, "lvtKlines": 1, "convert/exchangeInfo": 4, }, }, "fapiData": map[string]interface{} { "get": map[string]interface{} { "delivery-price": 1, "openInterestHist": 1, "topLongShortAccountRatio": 1, "topLongShortPositionRatio": 1, "globalLongShortAccountRatio": 1, "takerlongshortRatio": 1, "basis": 1, }, }, "fapiPrivate": map[string]interface{} { "get": map[string]interface{} { "forceOrders": map[string]interface{} { "cost": 20, "noSymbol": 50, }, "allOrders": 5, "openOrder": 1, "openOrders": map[string]interface{} { "cost": 1, "noSymbol": 40, }, "order": 1, "account": 5, "balance": 5, "leverageBracket": 1, "positionMargin/history": 1, "positionRisk": 5, "positionSide/dual": 30, "userTrades": 5, "income": 30, "commissionRate": 20, "rateLimit/order": 1, "apiTradingStatus": 1, "multiAssetsMargin": 30, "apiReferral/ifNewUser": 1, "apiReferral/customization": 1, "apiReferral/userCustomization": 1, "apiReferral/traderNum": 1, "apiReferral/overview": 1, "apiReferral/tradeVol": 1, "apiReferral/rebateVol": 1, "apiReferral/traderSummary": 1, "adlQuantile": 5, "pmAccountInfo": 5, "orderAmendment": 1, "income/asyn": 1000, "income/asyn/id": 10, "order/asyn": 1000, "order/asyn/id": 10, "trade/asyn": 1000, "trade/asyn/id": 10, "feeBurn": 1, "symbolConfig": 5, "accountConfig": 5, "convert/orderStatus": 5, }, "post": map[string]interface{} { "batchOrders": 5, "positionSide/dual": 1, "positionMargin": 1, "marginType": 1, "order": 4, "leverage": 1, "listenKey": 1, "countdownCancelAll": 10, "multiAssetsMargin": 1, "apiReferral/customization": 1, "apiReferral/userCustomization": 1, "feeBurn": 1, "convert/getQuote": 200, "convert/acceptQuote": 20, }, "put": map[string]interface{} { "listenKey": 1, "order": 1, "batchOrders": 5, }, "delete": map[string]interface{} { "batchOrders": 1, "order": 1, "allOpenOrders": 1, "listenKey": 1, }, }, "fapiPublicV2": map[string]interface{} { "get": map[string]interface{} { "ticker/price": 0, }, }, "fapiPrivateV2": map[string]interface{} { "get": map[string]interface{} { "account": 1, "balance": 1, "positionRisk": 1, }, }, "fapiPublicV3": map[string]interface{} { "get": map[string]interface{} {}, }, "fapiPrivateV3": map[string]interface{} { "get": map[string]interface{} { "account": 1, "balance": 1, "positionRisk": 1, }, }, "eapiPublic": map[string]interface{} { "get": map[string]interface{} { "ping": 1, "time": 1, "exchangeInfo": 1, "index": 1, "ticker": 5, "mark": 5, "depth": 1, "klines": 1, "trades": 5, "historicalTrades": 20, "exerciseHistory": 3, "openInterest": 3, }, }, "eapiPrivate": map[string]interface{} { "get": map[string]interface{} { "account": 3, "position": 5, "openOrders": map[string]interface{} { "cost": 1, "noSymbol": 40, }, "historyOrders": 3, "userTrades": 5, "exerciseRecord": 5, "bill": 1, "income/asyn": 5, "income/asyn/id": 5, "marginAccount": 3, "mmp": 1, "countdownCancelAll": 1, "order": 1, "block/order/orders": 5, "block/order/execute": 5, "block/user-trades": 5, "blockTrades": 5, }, "post": map[string]interface{} { "order": 1, "batchOrders": 5, "listenKey": 1, "mmpSet": 1, "mmpReset": 1, "countdownCancelAll": 1, "countdownCancelAllHeartBeat": 10, "block/order/create": 5, "block/order/execute": 5, }, "put": map[string]interface{} { "listenKey": 1, "block/order/create": 5, }, "delete": map[string]interface{} { "order": 1, "batchOrders": 1, "allOpenOrders": 1, "allOpenOrdersByUnderlying": 1, "listenKey": 1, "block/order/create": 5, }, }, "public": map[string]interface{} { "get": map[string]interface{} { "ping": 0.2, "time": 0.2, "depth": map[string]interface{} { "cost": 1, "byLimit": []interface{}{[]interface{}{100, 1}, []interface{}{500, 5}, []interface{}{1000, 10}, []interface{}{5000, 50}}, }, "trades": 2, "aggTrades": 0.4, "historicalTrades": 2, "klines": 0.4, "uiKlines": 0.4, "ticker/24hr": map[string]interface{} { "cost": 0.4, "noSymbol": 16, }, "ticker": map[string]interface{} { "cost": 0.4, "noSymbol": 16, }, "ticker/tradingDay": 0.8, "ticker/price": map[string]interface{} { "cost": 0.4, "noSymbol": 0.8, }, "ticker/bookTicker": map[string]interface{} { "cost": 0.4, "noSymbol": 0.8, }, "exchangeInfo": 4, "avgPrice": 0.4, }, "put": map[string]interface{} { "userDataStream": 0.4, }, "post": map[string]interface{} { "userDataStream": 0.4, }, "delete": map[string]interface{} { "userDataStream": 0.4, }, }, "private": map[string]interface{} { "get": map[string]interface{} { "allOrderList": 4, "openOrderList": 1.2, "orderList": 0.8, "order": 0.8, "openOrders": map[string]interface{} { "cost": 1.2, "noSymbol": 16, }, "allOrders": 4, "account": 4, "myTrades": 4, "rateLimit/order": 8, "myPreventedMatches": 4, "myAllocations": 4, "account/commission": 4, }, "post": map[string]interface{} { "order/oco": 0.2, "orderList/oco": 0.2, "orderList/oto": 0.2, "orderList/otoco": 0.2, "sor/order": 0.2, "sor/order/test": 0.2, "order": 0.2, "order/cancelReplace": 0.2, "order/test": 0.2, }, "delete": map[string]interface{} { "openOrders": 0.2, "orderList": 0.2, "order": 0.2, }, }, "papi": map[string]interface{} { "get": map[string]interface{} { "ping": 0.2, "um/order": 1, "um/openOrder": 1, "um/openOrders": map[string]interface{} { "cost": 1, "noSymbol": 40, }, "um/allOrders": 5, "cm/order": 1, "cm/openOrder": 1, "cm/openOrders": map[string]interface{} { "cost": 1, "noSymbol": 40, }, "cm/allOrders": 20, "um/conditional/openOrder": 1, "um/conditional/openOrders": map[string]interface{} { "cost": 1, "noSymbol": 40, }, "um/conditional/orderHistory": 1, "um/conditional/allOrders": map[string]interface{} { "cost": 1, "noSymbol": 40, }, "cm/conditional/openOrder": 1, "cm/conditional/openOrders": map[string]interface{} { "cost": 1, "noSymbol": 40, }, "cm/conditional/orderHistory": 1, "cm/conditional/allOrders": 40, "margin/order": 10, "margin/openOrders": 5, "margin/allOrders": 100, "margin/orderList": 5, "margin/allOrderList": 100, "margin/openOrderList": 5, "margin/myTrades": 5, "balance": 4, "account": 4, "margin/maxBorrowable": 1, "margin/maxWithdraw": 1, "um/positionRisk": 1, "cm/positionRisk": 0.2, "um/positionSide/dual": 6, "cm/positionSide/dual": 6, "um/userTrades": 5, "cm/userTrades": 20, "um/leverageBracket": 0.2, "cm/leverageBracket": 0.2, "margin/forceOrders": 1, "um/forceOrders": map[string]interface{} { "cost": 20, "noSymbol": 50, }, "cm/forceOrders": map[string]interface{} { "cost": 20, "noSymbol": 50, }, "um/apiTradingStatus": map[string]interface{} { "cost": 0.2, "noSymbol": 2, }, "um/commissionRate": 4, "cm/commissionRate": 4, "margin/marginLoan": 2, "margin/repayLoan": 2, "margin/marginInterestHistory": 0.2, "portfolio/interest-history": 10, "um/income": 6, "cm/income": 6, "um/account": 1, "cm/account": 1, "repay-futures-switch": 6, "um/adlQuantile": 5, "cm/adlQuantile": 5, "um/trade/asyn": 300, "um/trade/asyn/id": 2, "um/order/asyn": 300, "um/order/asyn/id": 2, "um/income/asyn": 300, "um/income/asyn/id": 2, "um/orderAmendment": 1, "cm/orderAmendment": 1, "um/feeBurn": 30, "um/accountConfig": 1, "um/symbolConfig": 1, "cm/accountConfig": 1, "cm/symbolConfig": 1, "rateLimit/order": 1, }, "post": map[string]interface{} { "um/order": 1, "um/conditional/order": 1, "cm/order": 1, "cm/conditional/order": 1, "margin/order": 1, "marginLoan": 100, "repayLoan": 100, "margin/order/oco": 1, "um/leverage": 0.2, "cm/leverage": 0.2, "um/positionSide/dual": 0.2, "cm/positionSide/dual": 0.2, "auto-collection": 150, "bnb-transfer": 150, "repay-futures-switch": 150, "repay-futures-negative-balance": 150, "listenKey": 0.2, "asset-collection": 6, "margin/repay-debt": 3000, "um/feeBurn": 1, }, "put": map[string]interface{} { "listenKey": 0.2, "um/order": 1, "cm/order": 1, }, "delete": map[string]interface{} { "um/order": 1, "um/conditional/order": 1, "um/allOpenOrders": 1, "um/conditional/allOpenOrders": 1, "cm/order": 1, "cm/conditional/order": 1, "cm/allOpenOrders": 1, "cm/conditional/allOpenOrders": 1, "margin/order": 2, "margin/allOpenOrders": 5, "margin/orderList": 2, "listenKey": 0.2, }, }, }, "fees": map[string]interface{} { "trading": map[string]interface{} { "feeSide": "get", "tierBased": false, "percentage": true, "taker": this.ParseNumber("0.001"), "maker": this.ParseNumber("0.001"), }, "linear": map[string]interface{} { "trading": map[string]interface{} { "feeSide": "quote", "tierBased": true, "percentage": true, "taker": this.ParseNumber("0.000500"), "maker": this.ParseNumber("0.000200"), "tiers": map[string]interface{} { "taker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.000400")}, []interface{}{this.ParseNumber("250"), this.ParseNumber("0.000400")}, []interface{}{this.ParseNumber("2500"), this.ParseNumber("0.000350")}, []interface{}{this.ParseNumber("7500"), this.ParseNumber("0.000320")}, []interface{}{this.ParseNumber("22500"), this.ParseNumber("0.000300")}, []interface{}{this.ParseNumber("50000"), this.ParseNumber("0.000270")}, []interface{}{this.ParseNumber("100000"), this.ParseNumber("0.000250")}, []interface{}{this.ParseNumber("200000"), this.ParseNumber("0.000220")}, []interface{}{this.ParseNumber("400000"), this.ParseNumber("0.000200")}, []interface{}{this.ParseNumber("750000"), this.ParseNumber("0.000170")}}, "maker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.000200")}, []interface{}{this.ParseNumber("250"), this.ParseNumber("0.000160")}, []interface{}{this.ParseNumber("2500"), this.ParseNumber("0.000140")}, []interface{}{this.ParseNumber("7500"), this.ParseNumber("0.000120")}, []interface{}{this.ParseNumber("22500"), this.ParseNumber("0.000100")}, []interface{}{this.ParseNumber("50000"), this.ParseNumber("0.000080")}, []interface{}{this.ParseNumber("100000"), this.ParseNumber("0.000060")}, []interface{}{this.ParseNumber("200000"), this.ParseNumber("0.000040")}, []interface{}{this.ParseNumber("400000"), this.ParseNumber("0.000020")}, []interface{}{this.ParseNumber("750000"), this.ParseNumber("0")}}, }, }, }, "inverse": map[string]interface{} { "trading": map[string]interface{} { "feeSide": "base", "tierBased": true, "percentage": true, "taker": this.ParseNumber("0.000500"), "maker": this.ParseNumber("0.000100"), "tiers": map[string]interface{} { "taker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.000500")}, []interface{}{this.ParseNumber("250"), this.ParseNumber("0.000450")}, []interface{}{this.ParseNumber("2500"), this.ParseNumber("0.000400")}, []interface{}{this.ParseNumber("7500"), this.ParseNumber("0.000300")}, []interface{}{this.ParseNumber("22500"), this.ParseNumber("0.000250")}, []interface{}{this.ParseNumber("50000"), this.ParseNumber("0.000240")}, []interface{}{this.ParseNumber("100000"), this.ParseNumber("0.000240")}, []interface{}{this.ParseNumber("200000"), this.ParseNumber("0.000240")}, []interface{}{this.ParseNumber("400000"), this.ParseNumber("0.000240")}, []interface{}{this.ParseNumber("750000"), this.ParseNumber("0.000240")}}, "maker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.000100")}, []interface{}{this.ParseNumber("250"), this.ParseNumber("0.000080")}, []interface{}{this.ParseNumber("2500"), this.ParseNumber("0.000050")}, []interface{}{this.ParseNumber("7500"), this.ParseNumber("0.0000030")}, []interface{}{this.ParseNumber("22500"), this.ParseNumber("0")}, []interface{}{this.ParseNumber("50000"), this.ParseNumber("-0.000050")}, []interface{}{this.ParseNumber("100000"), this.ParseNumber("-0.000060")}, []interface{}{this.ParseNumber("200000"), this.ParseNumber("-0.000070")}, []interface{}{this.ParseNumber("400000"), this.ParseNumber("-0.000080")}, []interface{}{this.ParseNumber("750000"), this.ParseNumber("-0.000090")}}, }, }, }, "option": map[string]interface{} {}, }, "currencies": map[string]interface{} { "BNFCR": this.SafeCurrencyStructure(map[string]interface{} { "id": "BNFCR", "code": "BNFCR", "precision": this.ParseNumber("0.001"), }), }, "commonCurrencies": map[string]interface{} { "BCC": "BCC", "YOYO": "YOYOW", }, "precisionMode": TICK_SIZE, "options": map[string]interface{} { "sandboxMode": false, "fetchMargins": true, "fetchMarkets": []interface{}{"spot", "linear", "inverse"}, "fetchCurrencies": true, "defaultTimeInForce": "GTC", "defaultType": "spot", "defaultSubType": nil, "hasAlreadyAuthenticatedSuccessfully": false, "warnOnFetchOpenOrdersWithoutSymbol": true, "throwMarginModeAlreadySet": false, "fetchPositions": "positionRisk", "recvWindow": Multiply(10, 1000), "timeDifference": 0, "adjustForTimeDifference": false, "newOrderRespType": map[string]interface{} { "market": "FULL", "limit": "FULL", }, "quoteOrderQty": true, "broker": map[string]interface{} { "spot": "x-R4BD3S82", "margin": "x-R4BD3S82", "future": "x-xcKtGhcu", "delivery": "x-xcKtGhcu", "swap": "x-xcKtGhcu", "option": "x-xcKtGhcu", }, "accountsByType": map[string]interface{} { "main": "MAIN", "spot": "MAIN", "funding": "FUNDING", "margin": "MARGIN", "cross": "MARGIN", "future": "UMFUTURE", "delivery": "CMFUTURE", "linear": "UMFUTURE", "swap": "UMFUTURE", "inverse": "CMFUTURE", "option": "OPTION", }, "accountsById": map[string]interface{} { "MAIN": "spot", "FUNDING": "funding", "MARGIN": "margin", "UMFUTURE": "linear", "CMFUTURE": "inverse", "OPTION": "option", }, "networks": map[string]interface{} { "ERC20": "ETH", "TRC20": "TRX", "BEP2": "BNB", "BEP20": "BSC", "OMNI": "OMNI", "EOS": "EOS", "SPL": "SOL", "SOL": "SOL", }, "reverseNetworks": map[string]interface{} { "tronscan.org": "TRC20", "etherscan.io": "ERC20", "bscscan.com": "BSC", "explorer.binance.org": "BEP2", "bithomp.com": "XRP", "bloks.io": "EOS", "stellar.expert": "XLM", "blockchair.com/bitcoin": "BTC", "blockchair.com/bitcoin-cash": "BCH", "blockchair.com/ecash": "XEC", "explorer.litecoin.net": "LTC", "explorer.avax.network": "AVAX", "solscan.io": "SOL", "polkadot.subscan.io": "DOT", "dashboard.internetcomputer.org": "ICP", "explorer.chiliz.com": "CHZ", "cardanoscan.io": "ADA", "mainnet.theoan.com": "AION", "algoexplorer.io": "ALGO", "explorer.ambrosus.com": "AMB", "viewblock.io/zilliqa": "ZIL", "viewblock.io/arweave": "AR", "explorer.ark.io": "ARK", "atomscan.com": "ATOM", "www.mintscan.io": "CTK", "explorer.bitcoindiamond.org": "BCD", "btgexplorer.com": "BTG", "bts.ai": "BTS", "explorer.celo.org": "CELO", "explorer.nervos.org": "CKB", "cerebro.cortexlabs.ai": "CTXC", "chainz.cryptoid.info": "VIA", "explorer.dcrdata.org": "DCR", "digiexplorer.info": "DGB", "dock.subscan.io": "DOCK", "dogechain.info": "DOGE", "explorer.elrond.com": "EGLD", "blockscout.com": "ETC", "explore-fetchhub.fetch.ai": "FET", "filfox.info": "FIL", "fio.bloks.io": "FIO", "explorer.firo.org": "FIRO", "neoscan.io": "NEO", "ftmscan.com": "FTM", "explorer.gochain.io": "GO", "block.gxb.io": "GXS", "hash-hash.info": "HBAR", "www.hiveblockexplorer.com": "HIVE", "explorer.helium.com": "HNT", "tracker.icon.foundation": "ICX", "www.iostabc.com": "IOST", "explorer.iota.org": "IOTA", "iotexscan.io": "IOTX", "irishub.iobscan.io": "IRIS", "kava.mintscan.io": "KAVA", "scope.klaytn.com": "KLAY", "kmdexplorer.io": "KMD", "kusama.subscan.io": "KSM", "explorer.lto.network": "LTO", "polygonscan.com": "POLYGON", "explorer.ont.io": "ONT", "minaexplorer.com": "MINA", "nanolooker.com": "NANO", "explorer.nebulas.io": "NAS", "explorer.nbs.plus": "NBS", "explorer.nebl.io": "NEBL", "nulscan.io": "NULS", "nxscan.com": "NXS", "explorer.harmony.one": "ONE", "explorer.poa.network": "POA", "qtum.info": "QTUM", "explorer.rsk.co": "RSK", "www.oasisscan.com": "ROSE", "ravencoin.network": "RVN", "sc.tokenview.com": "SC", "secretnodes.com": "SCRT", "explorer.skycoin.com": "SKY", "steemscan.com": "STEEM", "explorer.stacks.co": "STX", "www.thetascan.io": "THETA", "scan.tomochain.com": "TOMO", "explore.vechain.org": "VET", "explorer.vite.net": "VITE", "www.wanscan.org": "WAN", "wavesexplorer.com": "WAVES", "wax.eosx.io": "WAXP", "waltonchain.pro": "WTC", "chain.nem.ninja": "XEM", "verge-blockchain.info": "XVG", "explorer.yoyow.org": "YOYOW", "explorer.zcha.in": "ZEC", "explorer.zensystem.io": "ZEN", }, "networksById": map[string]interface{} { "SOL": "SOL", "tronscan.org": "TRC20", "etherscan.io": "ERC20", "bscscan.com": "BSC", "explorer.binance.org": "BEP2", "bithomp.com": "XRP", "bloks.io": "EOS", "stellar.expert": "XLM", "blockchair.com/bitcoin": "BTC", "blockchair.com/bitcoin-cash": "BCH", "blockchair.com/ecash": "XEC", "explorer.litecoin.net": "LTC", "explorer.avax.network": "AVAX", "solscan.io": "SOL", "polkadot.subscan.io": "DOT", "dashboard.internetcomputer.org": "ICP", "explorer.chiliz.com": "CHZ", "cardanoscan.io": "ADA", "mainnet.theoan.com": "AION", "algoexplorer.io": "ALGO", "explorer.ambrosus.com": "AMB", "viewblock.io/zilliqa": "ZIL", "viewblock.io/arweave": "AR", "explorer.ark.io": "ARK", "atomscan.com": "ATOM", "www.mintscan.io": "CTK", "explorer.bitcoindiamond.org": "BCD", "btgexplorer.com": "BTG", "bts.ai": "BTS", "explorer.celo.org": "CELO", "explorer.nervos.org": "CKB", "cerebro.cortexlabs.ai": "CTXC", "chainz.cryptoid.info": "VIA", "explorer.dcrdata.org": "DCR", "digiexplorer.info": "DGB", "dock.subscan.io": "DOCK", "dogechain.info": "DOGE", "explorer.elrond.com": "EGLD", "blockscout.com": "ETC", "explore-fetchhub.fetch.ai": "FET", "filfox.info": "FIL", "fio.bloks.io": "FIO", "explorer.firo.org": "FIRO", "neoscan.io": "NEO", "ftmscan.com": "FTM", "explorer.gochain.io": "GO", "block.gxb.io": "GXS", "hash-hash.info": "HBAR", "www.hiveblockexplorer.com": "HIVE", "explorer.helium.com": "HNT", "tracker.icon.foundation": "ICX", "www.iostabc.com": "IOST", "explorer.iota.org": "IOTA", "iotexscan.io": "IOTX", "irishub.iobscan.io": "IRIS", "kava.mintscan.io": "KAVA", "scope.klaytn.com": "KLAY", "kmdexplorer.io": "KMD", "kusama.subscan.io": "KSM", "explorer.lto.network": "LTO", "polygonscan.com": "POLYGON", "explorer.ont.io": "ONT", "minaexplorer.com": "MINA", "nanolooker.com": "NANO", "explorer.nebulas.io": "NAS", "explorer.nbs.plus": "NBS", "explorer.nebl.io": "NEBL", "nulscan.io": "NULS", "nxscan.com": "NXS", "explorer.harmony.one": "ONE", "explorer.poa.network": "POA", "qtum.info": "QTUM", "explorer.rsk.co": "RSK", "www.oasisscan.com": "ROSE", "ravencoin.network": "RVN", "sc.tokenview.com": "SC", "secretnodes.com": "SCRT", "explorer.skycoin.com": "SKY", "steemscan.com": "STEEM", "explorer.stacks.co": "STX", "www.thetascan.io": "THETA", "scan.tomochain.com": "TOMO", "explore.vechain.org": "VET", "explorer.vite.net": "VITE", "www.wanscan.org": "WAN", "wavesexplorer.com": "WAVES", "wax.eosx.io": "WAXP", "waltonchain.pro": "WTC", "chain.nem.ninja": "XEM", "verge-blockchain.info": "XVG", "explorer.yoyow.org": "YOYOW", "explorer.zcha.in": "ZEC", "explorer.zensystem.io": "ZEN", }, "impliedNetworks": map[string]interface{} { "ETH": map[string]interface{} { "ERC20": "ETH", }, "TRX": map[string]interface{} { "TRC20": "TRX", }, }, "legalMoney": map[string]interface{} { "MXN": true, "UGX": true, "SEK": true, "CHF": true, "VND": true, "AED": true, "DKK": true, "KZT": true, "HUF": true, "PEN": true, "PHP": true, "USD": true, "TRY": true, "EUR": true, "NGN": true, "PLN": true, "BRL": true, "ZAR": true, "KES": true, "ARS": true, "RUB": true, "AUD": true, "NOK": true, "CZK": true, "GBP": true, "UAH": true, "GHS": true, "HKD": true, "CAD": true, "INR": true, "JPY": true, "NZD": true, }, "legalMoneyCurrenciesById": map[string]interface{} { "BUSD": "USD", }, "defaultWithdrawPrecision": 1e-8, }, "features": map[string]interface{} { "spot": map[string]interface{} { "sandbox": true, "createOrder": map[string]interface{} { "marginMode": true, "triggerPrice": true, "triggerPriceType": nil, "triggerDirection": false, "stopLossPrice": true, "takeProfitPrice": true, "attachedStopLossTakeProfit": nil, "timeInForce": map[string]interface{} { "IOC": true, "FOK": true, "PO": true, "GTD": false, }, "hedged": true, "leverage": false, "marketBuyByCost": true, "marketBuyRequiresPrice": false, "selfTradePrevention": map[string]interface{} { "expire_maker": true, "expire_taker": true, "expire_both": true, "none": true, }, "trailing": false, "icebergAmount": true, }, "createOrders": nil, "fetchMyTrades": map[string]interface{} { "marginMode": false, "limit": 1000, "daysBack": nil, "untilDays": 1, "symbolRequired": true, }, "fetchOrder": map[string]interface{} { "marginMode": true, "trigger": false, "trailing": false, "symbolRequired": true, }, "fetchOpenOrders": map[string]interface{} { "marginMode": true, "limit": nil, "trigger": false, "trailing": false, "symbolRequired": false, }, "fetchOrders": map[string]interface{} { "marginMode": true, "limit": 1000, "daysBack": nil, "untilDays": 10000, "trigger": false, "trailing": false, "symbolRequired": true, }, "fetchClosedOrders": map[string]interface{} { "marginMode": true, "limit": 1000, "daysBack": nil, "daysBackCanceled": nil, "untilDays": 10000, "trigger": false, "trailing": false, "symbolRequired": true, }, "fetchOHLCV": map[string]interface{} { "limit": 1000, }, }, "forDerivatives": map[string]interface{} { "sandbox": true, "createOrder": map[string]interface{} { "marginMode": false, "triggerPrice": true, "triggerPriceType": map[string]interface{} { "mark": true, "last": true, "index": false, }, "stopLossPrice": true, "takeProfitPrice": true, "attachedStopLossTakeProfit": nil, "timeInForce": map[string]interface{} { "IOC": true, "FOK": true, "PO": true, "GTD": true, }, "hedged": true, "selfTradePrevention": true, "trailing": true, "iceberg": false, "leverage": false, "marketBuyRequiresPrice": false, "marketBuyByCost": true, }, "createOrders": map[string]interface{} { "max": 5, }, "fetchMyTrades": map[string]interface{} { "marginMode": false, "daysBack": nil, "limit": 1000, "untilDays": 7, "symbolRequired": true, }, "fetchOrder": map[string]interface{} { "marginMode": false, "trigger": false, "trailing": false, "symbolRequired": true, }, "fetchOpenOrders": map[string]interface{} { "marginMode": true, "limit": 500, "trigger": false, "trailing": false, "symbolRequired": false, }, "fetchOrders": map[string]interface{} { "marginMode": true, "limit": 1000, "daysBack": 90, "untilDays": 7, "trigger": false, "trailing": false, "symbolRequired": true, }, "fetchClosedOrders": map[string]interface{} { "marginMode": true, "limit": 1000, "daysBack": 90, "daysBackCanceled": 3, "untilDays": 7, "trigger": false, "trailing": false, "symbolRequired": true, }, "fetchOHLCV": map[string]interface{} { "limit": 1500, }, }, "swap": map[string]interface{} { "linear": map[string]interface{} { "extends": "forDerivatives", }, "inverse": map[string]interface{} { "extends": "forDerivatives", }, }, "future": map[string]interface{} { "linear": map[string]interface{} { "extends": "forDerivatives", }, "inverse": map[string]interface{} { "extends": "forDerivatives", }, }, }, "exceptions": map[string]interface{} { "spot": map[string]interface{} { "exact": map[string]interface{} { "-1004": OperationFailed, "-1008": OperationFailed, "-1099": AuthenticationError, "-1108": BadRequest, "-1131": BadRequest, "-1134": BadRequest, "-1135": BadRequest, "-1145": BadRequest, "-1151": BadSymbol, "-2008": AuthenticationError, "-2016": OperationRejected, "-2021": BadResponse, "-2022": BadResponse, "-2026": InvalidOrder, "-3000": OperationFailed, "-3001": AuthenticationError, "-3002": BadSymbol, "-3003": BadRequest, "-3004": OperationRejected, "-3005": BadRequest, "-3006": BadRequest, "-3007": OperationFailed, "-3008": BadRequest, "-3009": OperationRejected, "-3010": BadRequest, "-3011": BadRequest, "-3012": OperationRejected, "-3013": BadRequest, "-3014": AccountSuspended, "-3015": BadRequest, "-3016": BadRequest, "-3017": OperationRejected, "-3018": AccountSuspended, "-3019": AccountSuspended, "-3020": BadRequest, "-3021": BadRequest, "-3022": AccountSuspended, "-3023": OperationRejected, "-3024": OperationRejected, "-3025": BadRequest, "-3026": BadRequest, "-3027": BadSymbol, "-3028": BadSymbol, "-3029": OperationFailed, "-3036": AccountSuspended, "-3037": OperationFailed, "-3038": BadRequest, "-3041": InsufficientFunds, "-3042": BadRequest, "-3043": PermissionDenied, "-3044": OperationFailed, "-3045": OperationRejected, "-3999": PermissionDenied, "-4000": ExchangeError, "-4001": BadRequest, "-4002": BadRequest, "-4003": BadRequest, "-4004": AuthenticationError, "-4005": RateLimitExceeded, "-4006": BadRequest, "-4007": PermissionDenied, "-4008": PermissionDenied, "-4009": ExchangeError, "-4010": PermissionDenied, "-4011": BadRequest, "-4012": PermissionDenied, "-4013": AuthenticationError, "-4014": OperationRejected, "-4015": PermissionDenied, "-4016": PermissionDenied, "-4017": PermissionDenied, "-4018": BadSymbol, "-4019": BadRequest, "-4020": ExchangeError, "-4021": BadRequest, "-4022": BadRequest, "-4023": OperationRejected, "-4024": InsufficientFunds, "-4025": InsufficientFunds, "-4026": InsufficientFunds, "-4027": OperationFailed, "-4028": BadRequest, "-4029": BadRequest, "-4030": BadResponse, "-4031": OperationFailed, "-4032": OperationRejected, "-4033": BadRequest, "-4034": OperationRejected, "-4035": PermissionDenied, "-4036": PermissionDenied, "-4037": OperationFailed, "-4038": OperationFailed, "-4039": PermissionDenied, "-4040": OperationRejected, "-4041": OperationFailed, "-4042": OperationRejected, "-4043": OperationRejected, "-4044": PermissionDenied, "-4045": OperationFailed, "-4046": AuthenticationError, "-4047": BadRequest, "-4048": ExchangeError, "-4049": ExchangeError, "-4050": ExchangeError, "-4051": ExchangeError, "-4052": ExchangeError, "-4053": ExchangeError, "-4054": ExchangeError, "-4055": ExchangeError, "-4056": ExchangeError, "-4057": ExchangeError, "-4058": ExchangeError, "-4059": ExchangeError, "-4060": OperationFailed, "-4061": ExchangeError, "-4062": ExchangeError, "-4063": ExchangeError, "-4064": ExchangeError, "-4065": ExchangeError, "-4066": ExchangeError, "-4067": ExchangeError, "-4068": ExchangeError, "-4069": ExchangeError, "-4070": ExchangeError, "-4071": ExchangeError, "-4072": ExchangeError, "-4073": ExchangeError, "-4074": ExchangeError, "-4075": ExchangeError, "-4076": ExchangeError, "-4077": ExchangeError, "-4078": ExchangeError, "-4079": ExchangeError, "-4080": ExchangeError, "-4081": ExchangeError, "-4082": ExchangeError, "-4083": ExchangeError, "-4084": ExchangeError, "-4085": ExchangeError, "-4086": ExchangeError, "-4087": ExchangeError, "-4088": ExchangeError, "-4089": ExchangeError, "-4091": ExchangeError, "-4092": ExchangeError, "-4093": ExchangeError, "-4094": ExchangeError, "-4095": ExchangeError, "-4096": ExchangeError, "-4097": ExchangeError, "-4098": ExchangeError, "-4099": ExchangeError, "-4101": ExchangeError, "-4102": ExchangeError, "-4103": ExchangeError, "-4104": ExchangeError, "-4105": ExchangeError, "-4106": ExchangeError, "-4107": ExchangeError, "-4108": ExchangeError, "-4109": ExchangeError, "-4110": ExchangeError, "-4112": ExchangeError, "-4113": ExchangeError, "-4114": ExchangeError, "-4115": ExchangeError, "-4116": ExchangeError, "-4117": ExchangeError, "-4118": ExchangeError, "-4119": ExchangeError, "-4120": ExchangeError, "-4121": ExchangeError, "-4122": ExchangeError, "-4123": ExchangeError, "-4124": ExchangeError, "-4125": ExchangeError, "-4126": ExchangeError, "-4127": ExchangeError, "-4128": ExchangeError, "-4129": ExchangeError, "-4130": ExchangeError, "-4131": ExchangeError, "-4132": ExchangeError, "-4133": ExchangeError, "-4134": ExchangeError, "-4135": ExchangeError, "-4136": ExchangeError, "-4137": ExchangeError, "-4138": ExchangeError, "-4139": ExchangeError, "-4141": ExchangeError, "-4142": ExchangeError, "-4143": ExchangeError, "-4144": ExchangeError, "-4145": ExchangeError, "-4146": ExchangeError, "-4147": ExchangeError, "-4148": ExchangeError, "-4149": ExchangeError, "-4150": ExchangeError, "-5001": BadRequest, "-5002": InsufficientFunds, "-5003": InsufficientFunds, "-5004": OperationRejected, "-5005": OperationRejected, "-5006": OperationRejected, "-5007": BadRequest, "-5008": OperationRejected, "-5009": BadSymbol, "-5010": OperationFailed, "-5011": BadRequest, "-5012": OperationFailed, "-5013": InsufficientFunds, "-5021": BadRequest, "-5022": BadRequest, "-6001": BadSymbol, "-6003": PermissionDenied, "-6004": BadRequest, "-6005": BadRequest, "-6006": BadRequest, "-6007": OperationRejected, "-6008": OperationRejected, "-6009": RateLimitExceeded, "-6011": OperationRejected, "-6012": InsufficientFunds, "-6013": BadResponse, "-6014": OperationRejected, "-6015": BadRequest, "-6016": BadRequest, "-6017": PermissionDenied, "-6018": InsufficientFunds, "-6019": OperationRejected, "-6020": BadRequest, "-7001": BadRequest, "-7002": BadRequest, "-10001": OperationFailed, "-10002": BadRequest, "-10005": BadResponse, "-10007": BadRequest, "-10008": BadRequest, "-10009": BadRequest, "-10010": BadRequest, "-10011": InsufficientFunds, "-10012": BadRequest, "-10013": InsufficientFunds, "-10015": OperationFailed, "-10016": OperationFailed, "-10017": OperationRejected, "-10018": BadRequest, "-10019": BadRequest, "-10020": BadRequest, "-10021": InvalidOrder, "-10022": BadRequest, "-10023": OperationFailed, "-10024": BadRequest, "-10025": OperationFailed, "-10026": BadRequest, "-10028": BadRequest, "-10029": OperationRejected, "-10030": OperationRejected, "-10031": OperationRejected, "-10032": OperationFailed, "-10034": OperationRejected, "-10039": OperationRejected, "-10040": OperationRejected, "-10041": OperationFailed, "-10042": BadSymbol, "-10043": OperationRejected, "-10044": OperationRejected, "-10045": OperationRejected, "-10046": OperationRejected, "-10047": PermissionDenied, "-11008": OperationRejected, "-12014": RateLimitExceeded, "-13000": OperationRejected, "-13001": OperationRejected, "-13002": OperationRejected, "-13003": PermissionDenied, "-13004": OperationRejected, "-13005": OperationRejected, "-13006": OperationRejected, "-13007": PermissionDenied, "-18002": OperationRejected, "-18003": OperationRejected, "-18004": OperationRejected, "-18005": PermissionDenied, "-18006": OperationRejected, "-18007": OperationRejected, "-21001": BadRequest, "-21002": BadRequest, "-21003": BadResponse, "-21004": OperationRejected, "-21005": InsufficientFunds, "-21006": OperationFailed, "-21007": OperationFailed, "-32603": BadRequest, "400002": BadRequest, "100001003": AuthenticationError, "200003903": AuthenticationError, }, }, "linear": map[string]interface{} { "exact": map[string]interface{} { "-1005": PermissionDenied, "-1008": OperationFailed, "-1011": PermissionDenied, "-1023": BadRequest, "-1099": AuthenticationError, "-1109": PermissionDenied, "-1110": BadRequest, "-1113": BadRequest, "-1122": BadRequest, "-1126": BadSymbol, "-1136": BadRequest, "-2012": OperationFailed, "-2016": OperationRejected, "-2017": PermissionDenied, "-2018": InsufficientFunds, "-2019": InsufficientFunds, "-2020": OperationFailed, "-2021": OrderImmediatelyFillable, "-2022": InvalidOrder, "-2023": OperationFailed, "-2024": InsufficientFunds, "-2025": OperationRejected, "-2026": InvalidOrder, "-2027": OperationRejected, "-2028": OperationRejected, "-4063": BadRequest, "-4064": BadRequest, "-4065": BadRequest, "-4066": BadRequest, "-4069": BadRequest, "-4070": BadRequest, "-4071": BadRequest, "-4072": OperationRejected, "-4073": BadRequest, "-4074": OperationRejected, "-4075": BadRequest, "-4076": OperationRejected, "-4077": OperationRejected, "-4078": OperationFailed, "-4079": BadRequest, "-4080": PermissionDenied, "-4081": BadRequest, "-4085": BadRequest, "-4087": PermissionDenied, "-4088": PermissionDenied, "-4114": BadRequest, "-4115": BadRequest, "-4116": InvalidOrder, "-4117": OperationRejected, "-4118": OperationRejected, "-4131": OperationRejected, "-4140": BadRequest, "-4141": OperationRejected, "-4144": BadSymbol, "-4164": InvalidOrder, "-4136": InvalidOrder, "-4165": BadRequest, "-4167": BadRequest, "-4168": BadRequest, "-4169": OperationRejected, "-4170": OperationRejected, "-4171": OperationRejected, "-4172": OperationRejected, "-4183": BadRequest, "-4184": BadRequest, "-4192": PermissionDenied, "-4202": PermissionDenied, "-4203": PermissionDenied, "-4205": PermissionDenied, "-4206": PermissionDenied, "-4208": OperationRejected, "-4209": OperationRejected, "-4210": BadRequest, "-4211": BadRequest, "-4400": PermissionDenied, "-4401": PermissionDenied, "-4402": PermissionDenied, "-4403": PermissionDenied, "-5021": OrderNotFillable, "-5022": OrderNotFillable, "-5024": OperationRejected, "-5025": OperationRejected, "-5026": OperationRejected, "-5027": OperationRejected, "-5028": BadRequest, "-5037": BadRequest, "-5038": BadRequest, "-5039": BadRequest, "-5040": BadRequest, "-5041": OperationFailed, }, }, "inverse": map[string]interface{} { "exact": map[string]interface{} { "-1005": PermissionDenied, "-1011": PermissionDenied, "-1023": BadRequest, "-1109": AuthenticationError, "-1110": BadSymbol, "-1113": BadRequest, "-1128": BadRequest, "-1136": BadRequest, "-2016": OperationRejected, "-2018": InsufficientFunds, "-2019": InsufficientFunds, "-2020": OperationFailed, "-2021": OrderImmediatelyFillable, "-2022": InvalidOrder, "-2023": OperationFailed, "-2024": BadRequest, "-2025": OperationRejected, "-2026": InvalidOrder, "-2027": OperationRejected, "-2028": OperationRejected, "-4086": BadRequest, "-4087": BadSymbol, "-4088": BadRequest, "-4089": PermissionDenied, "-4090": PermissionDenied, "-4110": BadRequest, "-4111": BadRequest, "-4112": OperationRejected, "-4113": OperationRejected, "-4150": OperationRejected, "-4151": BadRequest, "-4152": BadRequest, "-4154": BadRequest, "-4155": BadRequest, "-4178": BadRequest, "-4188": BadRequest, "-4192": PermissionDenied, "-4194": PermissionDenied, "-4195": PermissionDenied, "-4196": BadRequest, "-4197": OperationRejected, "-4198": OperationRejected, "-4199": BadRequest, "-4200": PermissionDenied, "-4201": PermissionDenied, "-4202": OperationRejected, }, }, "option": map[string]interface{} { "exact": map[string]interface{} { "-1003": ExchangeError, "-1004": ExchangeError, "-1006": ExchangeError, "-1007": ExchangeError, "-1008": RateLimitExceeded, "-1010": ExchangeError, "-1013": ExchangeError, "-1108": ExchangeError, "-1112": ExchangeError, "-1114": ExchangeError, "-1128": BadSymbol, "-1129": BadSymbol, "-1131": BadRequest, "-2011": ExchangeError, "-2018": InsufficientFunds, "-2027": InsufficientFunds, "-3029": OperationFailed, "-4006": ExchangeError, "-4007": ExchangeError, "-4008": ExchangeError, "-4009": ExchangeError, "-4010": ExchangeError, "-4011": ExchangeError, "-4012": ExchangeError, "-4014": ExchangeError, "-4015": ExchangeError, "-4016": ExchangeError, "-4017": ExchangeError, "-4018": ExchangeError, "-4019": ExchangeError, "-4020": ExchangeError, "-4021": ExchangeError, "-4022": ExchangeError, "-4023": ExchangeError, "-4024": ExchangeError, "-4025": ExchangeError, "-4026": ExchangeError, "-4027": ExchangeError, "-4028": ExchangeError, "-4031": ExchangeError, "-4032": ExchangeError, "-4033": ExchangeError, "-4034": ExchangeError, "-4035": ExchangeError, "-4036": ExchangeError, "-4037": ExchangeError, "-4038": ExchangeError, "-4039": ExchangeError, "-4040": ExchangeError, "-4041": ExchangeError, "-4042": ExchangeError, "-4043": ExchangeError, "-4044": ExchangeError, "-4045": ExchangeError, "-4046": ExchangeError, "-4047": ExchangeError, "-4048": ExchangeError, "-4049": ExchangeError, "-4050": ExchangeError, "-4051": ExchangeError, "-4052": ExchangeError, "-4053": ExchangeError, "-4054": ExchangeError, "-4056": ExchangeError, "-4057": ExchangeError, "-4058": ExchangeError, "-4059": ExchangeError, "-4060": ExchangeError, "-4061": ExchangeError, "-4062": ExchangeError, "-4063": ExchangeError, "-4064": ExchangeError, "-4065": ExchangeError, "-4066": ExchangeError, "-4067": ExchangeError, "-4068": ExchangeError, "-4069": ExchangeError, "-4070": ExchangeError, "-4071": ExchangeError, "-4072": ExchangeError, "-4073": ExchangeError, "-4074": ExchangeError, "-4075": ExchangeError, "-4076": ExchangeError, "-4077": ExchangeError, "-4078": ExchangeError, "-4079": ExchangeError, "-4080": ExchangeError, "-4081": ExchangeError, "-4082": ExchangeError, "-4083": ExchangeError, "-4084": ExchangeError, "-4085": ExchangeError, "-4086": ExchangeError, "-4087": ExchangeError, "-4088": ExchangeError, "-4089": ExchangeError, "-4091": ExchangeError, "-4092": ExchangeError, "-4093": ExchangeError, "-4094": ExchangeError, "-4095": ExchangeError, "-4096": ExchangeError, "-4097": ExchangeError, "-4098": ExchangeError, "-4099": ExchangeError, "-4101": ExchangeError, "-4102": ExchangeError, "-4103": ExchangeError, "-4104": ExchangeError, "-4105": ExchangeError, "-4106": ExchangeError, "-4107": ExchangeError, "-4108": ExchangeError, "-4109": ExchangeError, "-4110": ExchangeError, "-4112": ExchangeError, "-4113": ExchangeError, "-4114": ExchangeError, "-4115": ExchangeError, "-4116": ExchangeError, "-4117": ExchangeError, "-4118": ExchangeError, "-4119": ExchangeError, "-4120": ExchangeError, "-4121": ExchangeError, "-4122": ExchangeError, "-4123": ExchangeError, "-4124": ExchangeError, "-4125": ExchangeError, "-4126": ExchangeError, "-4127": ExchangeError, "-4128": ExchangeError, "-4129": ExchangeError, "-4130": ExchangeError, "-4131": ExchangeError, "-4132": ExchangeError, "-4133": ExchangeError, "-4134": ExchangeError, "-4135": ExchangeError, "-4136": ExchangeError, "-4137": ExchangeError, "-4138": ExchangeError, "-4139": ExchangeError, "-4141": ExchangeError, "-4142": ExchangeError, "-4143": ExchangeError, "-4144": ExchangeError, "-4145": ExchangeError, "-4146": ExchangeError, "-4147": ExchangeError, "-4148": ExchangeError, "-4149": ExchangeError, "-4150": ExchangeError, "-20121": ExchangeError, "-20124": ExchangeError, "-20130": ExchangeError, "-20132": ExchangeError, "-20194": ExchangeError, "-20195": ExchangeError, "-20196": ExchangeError, "-20198": ExchangeError, "-20204": ExchangeError, }, }, "portfolioMargin": map[string]interface{} { "exact": map[string]interface{} { "-1000": OperationFailed, "-1001": ExchangeError, "-1002": PermissionDenied, "-1003": RateLimitExceeded, "-1004": BadRequest, "-1005": PermissionDenied, "-1006": BadResponse, "-1007": BadResponse, "-1008": OperationFailed, "-1010": ExchangeError, "-1011": PermissionDenied, "-1013": ExchangeError, "-1014": InvalidOrder, "-1015": InvalidOrder, "-1016": NotSupported, "-1020": NotSupported, "-1021": BadRequest, "-1022": BadRequest, "-1023": BadRequest, "-1099": OperationFailed, "-1100": BadRequest, "-1101": BadRequest, "-1102": BadRequest, "-1103": BadRequest, "-1104": BadRequest, "-1105": BadRequest, "-1106": BadRequest, "-1108": BadRequest, "-1109": BadRequest, "-1110": BadSymbol, "-1111": BadRequest, "-1112": BadRequest, "-1113": BadRequest, "-1114": BadRequest, "-1115": BadRequest, "-1116": BadRequest, "-1117": BadRequest, "-1118": BadRequest, "-1119": BadRequest, "-1120": BadRequest, "-1121": BadSymbol, "-1125": BadRequest, "-1127": BadRequest, "-1128": BadRequest, "-1130": BadRequest, "-1131": BadRequest, "-1134": BadRequest, "-1136": BadRequest, "-1145": BadRequest, "-1151": BadRequest, "-2010": InvalidOrder, "-2011": OperationRejected, "-2013": OrderNotFound, "-2014": OperationRejected, "-2015": OperationRejected, "-2016": OperationFailed, "-2018": OperationFailed, "-2019": OperationFailed, "-2020": OrderNotFillable, "-2021": OrderImmediatelyFillable, "-2022": InvalidOrder, "-2023": OperationFailed, "-2024": OperationRejected, "-2025": OperationRejected, "-2026": InvalidOrder, "-2027": OperationRejected, "-2028": OperationRejected, "-4000": BadRequest, "-4001": BadRequest, "-4002": BadRequest, "-4003": BadRequest, "-4004": BadRequest, "-4005": BadRequest, "-4006": BadRequest, "-4007": BadRequest, "-4008": BadRequest, "-4009": BadRequest, "-4010": BadRequest, "-4011": BadRequest, "-4012": BadRequest, "-4013": BadRequest, "-4014": BadRequest, "-4015": BadRequest, "-4016": BadRequest, "-4017": BadRequest, "-4018": BadRequest, "-4019": BadRequest, "-4020": BadRequest, "-4021": BadRequest, "-4022": BadRequest, "-4023": BadRequest, "-4024": BadRequest, "-4025": BadRequest, "-4026": BadRequest, "-4027": BadRequest, "-4028": BadRequest, "-4029": BadRequest, "-4030": BadRequest, "-4031": BadRequest, "-4032": BadRequest, "-4033": BadRequest, "-4044": BadRequest, "-4045": BadRequest, "-4046": BadRequest, "-4047": BadRequest, "-4048": BadRequest, "-4049": BadRequest, "-4050": BadRequest, "-4051": BadRequest, "-4052": BadRequest, "-4053": BadRequest, "-4054": BadRequest, "-4055": BadRequest, "-4056": PermissionDenied, "-4057": PermissionDenied, "-4058": BadRequest, "-4059": BadRequest, "-4060": BadRequest, "-4061": InvalidOrder, "-4062": BadRequest, "-4063": BadRequest, "-4064": BadRequest, "-4065": BadRequest, "-4066": BadRequest, "-4067": BadRequest, "-4068": BadRequest, "-4069": BadRequest, "-4070": BadRequest, "-4071": BadRequest, "-4072": OperationRejected, "-4073": BadRequest, "-4074": BadRequest, "-4075": BadRequest, "-4076": OperationRejected, "-4077": OperationRejected, "-4078": OperationFailed, "-4079": BadRequest, "-4080": PermissionDenied, "-4081": BadRequest, "-4082": BadRequest, "-4083": BadRequest, "-4084": NotSupported, "-4085": BadRequest, "-4086": BadRequest, "-4087": PermissionDenied, "-4088": PermissionDenied, "-4104": BadRequest, "-4114": BadRequest, "-4115": BadRequest, "-4118": OperationRejected, "-4131": OperationRejected, "-4135": BadRequest, "-4137": BadRequest, "-4138": BadRequest, "-4139": BadRequest, "-4140": OrderImmediatelyFillable, "-4141": BadRequest, "-4142": OrderImmediatelyFillable, "-4144": BadSymbol, "-4161": OperationRejected, "-4164": InvalidOrder, "-4165": BadRequest, "-4183": InvalidOrder, "-4184": InvalidOrder, "-4408": InvalidOrder, "-5021": OrderNotFillable, "-5022": OrderNotFillable, "-5028": OperationFailed, "-5041": RateLimitExceeded, }, }, "exact": map[string]interface{} { "-1000": OperationFailed, "-1001": OperationFailed, "-1002": AuthenticationError, "-1003": RateLimitExceeded, "-1004": OperationRejected, "-1006": OperationFailed, "-1007": RequestTimeout, "-1010": OperationFailed, "-1013": BadRequest, "-1014": InvalidOrder, "-1015": RateLimitExceeded, "-1016": BadRequest, "-1020": BadRequest, "-1021": InvalidNonce, "-1022": AuthenticationError, "-1100": BadRequest, "-1101": BadRequest, "-1102": BadRequest, "-1103": BadRequest, "-1104": BadRequest, "-1105": BadRequest, "-1106": BadRequest, "-1108": BadSymbol, "-1111": BadRequest, "-1112": OperationFailed, "-1114": BadRequest, "-1115": BadRequest, "-1116": BadRequest, "-1117": BadRequest, "-1118": BadRequest, "-1119": BadRequest, "-1120": BadRequest, "-1121": BadSymbol, "-1125": AuthenticationError, "-1127": BadRequest, "-1128": BadRequest, "-1130": BadRequest, "-2010": InvalidOrder, "-2011": OrderNotFound, "-2013": OrderNotFound, "-2014": AuthenticationError, "-2015": AuthenticationError, "-4000": InvalidOrder, "-4001": BadRequest, "-4002": BadRequest, "-4003": BadRequest, "-4004": BadRequest, "-4005": BadRequest, "-4006": BadRequest, "-4007": BadRequest, "-4008": BadRequest, "-4009": BadRequest, "-4010": BadRequest, "-4011": BadRequest, "-4012": BadRequest, "-4013": BadRequest, "-4014": BadRequest, "-4015": BadRequest, "-4016": BadRequest, "-4017": BadRequest, "-4018": BadRequest, "-4019": OperationRejected, "-4020": BadRequest, "-4021": BadRequest, "-4022": BadRequest, "-4023": BadRequest, "-4024": BadRequest, "-4025": BadRequest, "-4026": BadRequest, "-4027": BadRequest, "-4028": BadRequest, "-4029": BadRequest, "-4030": BadRequest, "-4031": BadRequest, "-4032": OperationRejected, "-4033": BadRequest, "-4044": BadRequest, "-4045": OperationRejected, "-4046": OperationRejected, "-4047": OperationRejected, "-4048": OperationRejected, "-4049": BadRequest, "-4050": InsufficientFunds, "-4051": InsufficientFunds, "-4052": OperationRejected, "-4053": BadRequest, "-4054": OperationRejected, "-4055": BadRequest, "-4056": AuthenticationError, "-4057": AuthenticationError, "-4058": BadRequest, "-4059": OperationRejected, "-4060": BadRequest, "-4061": OperationRejected, "-4062": BadRequest, "-4067": OperationRejected, "-4068": OperationRejected, "-4082": BadRequest, "-4083": OperationRejected, "-4084": BadRequest, "-4086": BadRequest, "-4104": BadRequest, "-4135": BadRequest, "-4137": BadRequest, "-4138": BadRequest, "-4139": BadRequest, "-4142": OrderImmediatelyFillable, "-20121": BadSymbol, "-20124": BadRequest, "-20130": BadRequest, "-20132": BadRequest, "-20194": BadRequest, "-20195": BadRequest, "-20196": BadRequest, "-20198": OperationRejected, "-20204": BadRequest, "System is under maintenance.": OnMaintenance, "System abnormality": OperationFailed, "You are not authorized to execute this request.": PermissionDenied, "API key does not exist": AuthenticationError, "Order would trigger immediately.": OrderImmediatelyFillable, "Stop price would trigger immediately.": OrderImmediatelyFillable, "Order would immediately match and take.": OrderImmediatelyFillable, "Account has insufficient balance for requested action.": InsufficientFunds, "Rest API trading is not enabled.": PermissionDenied, "This account may not place or cancel orders.": PermissionDenied, "You don\\'t have permission.": PermissionDenied, "Market is closed.": MarketClosed, "Too many requests. Please try again later.": RateLimitExceeded, "This action is disabled on this account.": AccountSuspended, "Limit orders require GTC for this phase.": BadRequest, "This order type is not possible in this trading phase.": BadRequest, "This type of sub-account exceeds the maximum number limit": OperationRejected, "This symbol is restricted for this account.": PermissionDenied, "This symbol is not permitted for this account.": PermissionDenied, }, "broad": map[string]interface{} { "has no operation privilege": PermissionDenied, "MAX_POSITION": BadRequest, }, }, }) } func (this *binance) IsInverse(typeVar interface{}, optionalArgs ...interface{}) interface{} { subType := GetArg(optionalArgs, 0, nil) _ = subType if IsTrue(IsEqual(subType, nil)) { return (IsEqual(typeVar, "delivery")) } else { return IsEqual(subType, "inverse") } } func (this *binance) IsLinear(typeVar interface{}, optionalArgs ...interface{}) interface{} { subType := GetArg(optionalArgs, 0, nil) _ = subType if IsTrue(IsEqual(subType, nil)) { return IsTrue((IsEqual(typeVar, "future"))) || IsTrue((IsEqual(typeVar, "swap"))) } else { return IsEqual(subType, "linear") } } func (this *binance) SetSandboxMode(enable interface{}) { this.Exchange.SetSandboxMode(enable) AddElementToObject(this.Options, "sandboxMode", enable) } func (this *binance) CreateExpiredOptionMarket(symbol interface{}) interface{} { // support expired option contracts var settle interface{} = "USDT" var optionParts interface{} = Split(symbol, "-") var symbolBase interface{} = Split(symbol, "/") var base interface{} = nil if IsTrue(IsGreaterThan(GetIndexOf(symbol, "/"), OpNeg(1))) { base = this.SafeString(symbolBase, 0) } else { base = this.SafeString(optionParts, 0) } var expiry interface{} = this.SafeString(optionParts, 1) var strike interface{} = this.SafeInteger(optionParts, 2) var strikeAsString interface{} = this.SafeString(optionParts, 2) var optionType interface{} = this.SafeString(optionParts, 3) var datetime interface{} = this.ConvertExpireDate(expiry) var timestamp interface{} = this.Parse8601(datetime) return map[string]interface{} { "id": Add(Add(Add(Add(Add(Add(base, "-"), expiry), "-"), strikeAsString), "-"), optionType), "symbol": Add(Add(Add(Add(Add(Add(Add(Add(Add(Add(base, "/"), settle), ":"), settle), "-"), expiry), "-"), strikeAsString), "-"), optionType), "base": base, "quote": settle, "baseId": base, "quoteId": settle, "active": nil, "type": "option", "linear": nil, "inverse": nil, "spot": false, "swap": false, "future": false, "option": true, "margin": false, "contract": true, "contractSize": nil, "expiry": timestamp, "expiryDatetime": datetime, "optionType": Ternary(IsTrue((IsEqual(optionType, "C"))), "call", "put"), "strike": strike, "settle": settle, "settleId": settle, "precision": map[string]interface{} { "amount": nil, "price": nil, }, "limits": map[string]interface{} { "amount": map[string]interface{} { "min": nil, "max": nil, }, "price": map[string]interface{} { "min": nil, "max": nil, }, "cost": map[string]interface{} { "min": nil, "max": nil, }, }, "info": nil, } } func (this *binance) Market(symbol interface{}) interface{} { if IsTrue(IsEqual(this.Markets, nil)) { panic(ExchangeError(Add(this.Id, " markets not loaded"))) } // defaultType has legacy support on binance var defaultType interface{} = this.SafeString(this.Options, "defaultType") var defaultSubType interface{} = this.SafeString(this.Options, "defaultSubType") var isLegacyLinear interface{} = IsEqual(defaultType, "future") var isLegacyInverse interface{} = IsEqual(defaultType, "delivery") var isLegacy interface{} = IsTrue(isLegacyLinear) || IsTrue(isLegacyInverse) if IsTrue(IsString(symbol)) { if IsTrue(InOp(this.Markets, symbol)) { var market interface{} = GetValue(this.Markets, symbol) // begin diff if IsTrue(IsTrue(isLegacy) && IsTrue(GetValue(market, "spot"))) { var settle interface{} = Ternary(IsTrue(isLegacyLinear), GetValue(market, "quote"), GetValue(market, "base")) var futuresSymbol interface{} = Add(Add(symbol, ":"), settle) if IsTrue(InOp(this.Markets, futuresSymbol)) { return GetValue(this.Markets, futuresSymbol) } } else { return market } } else if IsTrue(InOp(this.Markets_by_id, symbol)) { var markets interface{} = GetValue(this.Markets_by_id, symbol) // begin diff if IsTrue(isLegacyLinear) { defaultType = "linear" } else if IsTrue(isLegacyInverse) { defaultType = "inverse" } else if IsTrue(IsEqual(defaultType, nil)) { defaultType = defaultSubType } // end diff for i := 0; IsLessThan(i, GetArrayLength(markets)); i++ { var market interface{} = GetValue(markets, i) if IsTrue(GetValue(market, defaultType)) { return market } } return GetValue(markets, 0) } else if IsTrue(IsTrue((IsGreaterThan(GetIndexOf(symbol, "/"), OpNeg(1)))) && IsTrue((IsLessThan(GetIndexOf(symbol, ":"), 0)))) { // support legacy symbols basequoteVariable := Split(symbol, "/"); base := GetValue(basequoteVariable,0); quote := GetValue(basequoteVariable,1) var settle interface{} = Ternary(IsTrue((IsEqual(quote, "USD"))), base, quote) var futuresSymbol interface{} = Add(Add(symbol, ":"), settle) if IsTrue(InOp(this.Markets, futuresSymbol)) { return GetValue(this.Markets, futuresSymbol) } } else if IsTrue(IsTrue((IsGreaterThan(GetIndexOf(symbol, "-C"), OpNeg(1)))) || IsTrue((IsGreaterThan(GetIndexOf(symbol, "-P"), OpNeg(1))))) { return this.CreateExpiredOptionMarket(symbol) } } panic(BadSymbol(Add(Add(this.Id, " does not have market symbol "), symbol))) } func (this *binance) SafeMarket(optionalArgs ...interface{}) interface{} { marketId := GetArg(optionalArgs, 0, nil) _ = marketId market := GetArg(optionalArgs, 1, nil) _ = market delimiter := GetArg(optionalArgs, 2, nil) _ = delimiter marketType := GetArg(optionalArgs, 3, nil) _ = marketType var isOption interface{} = IsTrue((!IsEqual(marketId, nil))) && IsTrue((IsTrue((IsGreaterThan(GetIndexOf(marketId, "-C"), OpNeg(1)))) || IsTrue((IsGreaterThan(GetIndexOf(marketId, "-P"), OpNeg(1)))))) if IsTrue(IsTrue(isOption) && !IsTrue((InOp(this.Markets_by_id, marketId)))) { // handle expired option contracts return this.CreateExpiredOptionMarket(marketId) } return this.Exchange.SafeMarket(marketId, market, delimiter, marketType) } func (this *binance) CostToPrecision(symbol interface{}, cost interface{}) interface{} { return this.DecimalToPrecision(cost, TRUNCATE, GetValue(GetValue(GetValue(this.Markets, symbol), "precision"), "quote"), this.PrecisionMode, this.PaddingMode) } func (this *binance) CurrencyToPrecision(code interface{}, fee interface{}, optionalArgs ...interface{}) interface{} { // info is available in currencies only if the user has configured his api keys networkCode := GetArg(optionalArgs, 0, nil) _ = networkCode if IsTrue(!IsEqual(this.SafeValue(GetValue(this.Currencies, code), "precision"), nil)) { return this.DecimalToPrecision(fee, TRUNCATE, GetValue(GetValue(this.Currencies, code), "precision"), this.PrecisionMode, this.PaddingMode) } else { return this.NumberToString(fee) } } func (this *binance) Nonce() interface{} { return Subtract(this.Milliseconds(), GetValue(this.Options, "timeDifference")) } /** * @method * @name binance#fetchTime * @description fetches the current integer timestamp in milliseconds from the exchange server * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#check-server-time // spot * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Check-Server-Time // swap * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Check-Server-time // future * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.subType] "linear" or "inverse" * @returns {int} the current integer timestamp in milliseconds from the exchange server */ func (this *binance) 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 var defaultType interface{} = this.SafeString2(this.Options, "fetchTime", "defaultType", "spot") var typeVar interface{} = this.SafeString(params, "type", defaultType) var query interface{} = this.Omit(params, "type") var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchTime", nil, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { response = (<-this.FapiPublicGetTime(query)) PanicOnError(response) } else if IsTrue(this.IsInverse(typeVar, subType)) { response = (<-this.DapiPublicGetTime(query)) PanicOnError(response) } else { response = (<-this.PublicGetTime(query)) PanicOnError(response) } ch <- this.SafeInteger(response, "serverTime") return nil }() return ch } /** * @method * @name binance#fetchCurrencies * @description fetches all available currencies on an exchange * @see https://developers.binance.com/docs/wallet/capital/all-coins-info * @see https://developers.binance.com/docs/margin_trading/market-data/Get-All-Margin-Assets * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} an associative dictionary of currencies */ func (this *binance) 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 var fetchCurrenciesEnabled interface{} = this.SafeBool(this.Options, "fetchCurrencies") if !IsTrue(fetchCurrenciesEnabled) { return nil } // this endpoint requires authentication // while fetchCurrencies is a public API method by design // therefore we check the keys here // and fallback to generating the currencies from the markets if !IsTrue(this.CheckRequiredCredentials(false)) { return nil } // sandbox/testnet does not support sapi endpoints var apiBackup interface{} = this.SafeValue(this.Urls, "apiBackup") if IsTrue(!IsEqual(apiBackup, nil)) { return nil } var promises interface{} = []interface{}{this.SapiGetCapitalConfigGetall(params)} var fetchMargins interface{} = this.SafeBool(this.Options, "fetchMargins", false) if IsTrue(fetchMargins) { AppendToArray(&promises,this.SapiGetMarginAllPairs(params)) } results:= (<-promiseAll(promises)) PanicOnError(results) var responseCurrencies interface{} = GetValue(results, 0) var marginablesById interface{} = nil if IsTrue(fetchMargins) { var responseMarginables interface{} = GetValue(results, 1) marginablesById = this.IndexBy(responseMarginables, "assetName") } var result interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(responseCurrencies)); i++ { // // { // "coin": "LINK", // "depositAllEnable": true, // "withdrawAllEnable": true, // "name": "ChainLink", // "free": "0", // "locked": "0", // "freeze": "0", // "withdrawing": "0", // "ipoing": "0", // "ipoable": "0", // "storage": "0", // "isLegalMoney": false, // "trading": true, // "networkList": [ // { // "network": "BSC", // "coin": "LINK", // "withdrawIntegerMultiple": "0.00000001", // "isDefault": false, // "depositEnable": true, // "withdrawEnable": true, // "depositDesc": "", // "withdrawDesc": "", // "specialTips": "", // "specialWithdrawTips": "The network you have selected is BSC. Please ensure that the withdrawal address supports the Binance Smart Chain network. You will lose your assets if the chosen platform does not support retrievals.", // "name": "BNB Smart Chain (BEP20)", // "resetAddressStatus": false, // "addressRegex": "^(0x)[0-9A-Fa-f]{40}$", // "addressRule": "", // "memoRegex": "", // "withdrawFee": "0.012", // "withdrawMin": "0.024", // "withdrawMax": "9999999999.99999999", // "minConfirm": "15", // "unLockConfirm": "0", // "sameAddress": false, // "estimatedArrivalTime": "5", // "busy": false, // "country": "AE,BINANCE_BAHRAIN_BSC" // }, // { // "network": "BNB", // "coin": "LINK", // "withdrawIntegerMultiple": "0.00000001", // "isDefault": false, // "depositEnable": true, // "withdrawEnable": true, // "depositDesc": "", // "withdrawDesc": "", // "specialTips": "Both a MEMO and an Address are required to successfully deposit your LINK BEP2 tokens to Binance.", // "specialWithdrawTips": "", // "name": "BNB Beacon Chain (BEP2)", // "resetAddressStatus": false, // "addressRegex": "^(bnb1)[0-9a-z]{38}$", // "addressRule": "", // "memoRegex": "^[0-9A-Za-z\\-_]{1,120}$", // "withdrawFee": "0.002", // "withdrawMin": "0.01", // "withdrawMax": "10000000000", // "minConfirm": "1", // "unLockConfirm": "0", // "sameAddress": true, // "estimatedArrivalTime": "5", // "busy": false, // "country": "AE,BINANCE_BAHRAIN_BSC" // }, // { // "network": "ETH", // "coin": "LINK", // "withdrawIntegerMultiple": "0.00000001", // "isDefault": true, // "depositEnable": true, // "withdrawEnable": true, // "depositDesc": "", // "withdrawDesc": "", // "name": "Ethereum (ERC20)", // "resetAddressStatus": false, // "addressRegex": "^(0x)[0-9A-Fa-f]{40}$", // "addressRule": "", // "memoRegex": "", // "withdrawFee": "0.55", // "withdrawMin": "1.1", // "withdrawMax": "10000000000", // "minConfirm": "12", // "unLockConfirm": "0", // "sameAddress": false, // "estimatedArrivalTime": "5", // "busy": false, // "country": "AE,BINANCE_BAHRAIN_BSC" // } // ] // } // var entry interface{} = GetValue(responseCurrencies, i) var id interface{} = this.SafeString(entry, "coin") var name interface{} = this.SafeString(entry, "name") var code interface{} = this.SafeCurrencyCode(id) var isFiat interface{} = this.SafeBool(entry, "isLegalMoney") var minPrecision interface{} = nil var isWithdrawEnabled interface{} = true var isDepositEnabled interface{} = true var networkList interface{} = this.SafeList(entry, "networkList", []interface{}{}) var fees interface{} = map[string]interface{} {} var fee interface{} = nil var networks interface{} = map[string]interface{} {} for j := 0; IsLessThan(j, GetArrayLength(networkList)); j++ { var networkItem interface{} = GetValue(networkList, j) var network interface{} = this.SafeString(networkItem, "network") var networkCode interface{} = this.NetworkIdToCode(network) var isETF interface{} = (IsEqual(network, "ETF")) // e.g. BTCUP, ETHDOWN // const name = this.safeString (networkItem, 'name'); var withdrawFee interface{} = this.SafeNumber(networkItem, "withdrawFee") var depositEnable interface{} = this.SafeBool(networkItem, "depositEnable") var withdrawEnable interface{} = this.SafeBool(networkItem, "withdrawEnable") isDepositEnabled = IsTrue(isDepositEnabled) || IsTrue(depositEnable) isWithdrawEnabled = IsTrue(isWithdrawEnabled) || IsTrue(withdrawEnable) AddElementToObject(fees, network, withdrawFee) var isDefault interface{} = this.SafeBool(networkItem, "isDefault") if IsTrue(IsTrue(isDefault) || IsTrue((IsEqual(fee, nil)))) { fee = withdrawFee } // todo: default networks in "setMarkets" overload // if (isDefault) { // this.options['defaultNetworkCodesForCurrencies'][code] = networkCode; // } var precisionTick interface{} = this.SafeString(networkItem, "withdrawIntegerMultiple") var withdrawPrecision interface{} = precisionTick // avoid zero values, which are mostly from fiat or leveraged tokens or some abandoned coins : https://github.com/ccxt/ccxt/pull/14902#issuecomment-1271636731 if !IsTrue(Precise.StringEq(precisionTick, "0")) { minPrecision = Ternary(IsTrue((IsEqual(minPrecision, nil))), precisionTick, Precise.StringMin(minPrecision, precisionTick)) } else { if IsTrue(!IsTrue(isFiat) && !IsTrue(isETF)) { // non-fiat and non-ETF currency, there are many cases when precision is set to zero (probably bug, we've reported to binance already) // in such cases, we can set default precision of 8 (which is in UI for such coins) withdrawPrecision = this.OmitZero(this.SafeString(networkItem, "withdrawInternalMin")) if IsTrue(IsEqual(withdrawPrecision, nil)) { withdrawPrecision = this.SafeString(this.Options, "defaultWithdrawPrecision") } } } AddElementToObject(networks, networkCode, map[string]interface{} { "info": networkItem, "id": network, "network": networkCode, "active": IsTrue(depositEnable) && IsTrue(withdrawEnable), "deposit": depositEnable, "withdraw": withdrawEnable, "fee": withdrawFee, "precision": this.ParseNumber(withdrawPrecision), "limits": map[string]interface{} { "withdraw": map[string]interface{} { "min": this.SafeNumber(networkItem, "withdrawMin"), "max": this.SafeNumber(networkItem, "withdrawMax"), }, "deposit": map[string]interface{} { "min": this.SafeNumber(networkItem, "depositDust"), "max": nil, }, }, }) } var trading interface{} = this.SafeBool(entry, "trading") var active interface{} = (IsTrue(IsTrue(isWithdrawEnabled) && IsTrue(isDepositEnabled)) && IsTrue(trading)) var marginEntry interface{} = this.SafeDict(marginablesById, id, map[string]interface{} {}) // // { // assetName: "BTC", // assetFullName: "Bitcoin", // isBorrowable: true, // isMortgageable: true, // userMinBorrow: "0", // userMinRepay: "0", // } // AddElementToObject(result, code, map[string]interface{} { "id": id, "name": name, "code": code, "type": Ternary(IsTrue(isFiat), "fiat", "crypto"), "precision": this.ParseNumber(minPrecision), "info": entry, "active": active, "deposit": isDepositEnabled, "withdraw": isWithdrawEnabled, "networks": networks, "fee": fee, "fees": fees, "limits": this.Limits, "margin": this.SafeBool(marginEntry, "isBorrowable"), }) } ch <- result return nil }() return ch } /** * @method * @name binance#fetchMarkets * @description retrieves data on all markets for binance * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#exchange-information // spot * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Exchange-Information // swap * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Exchange-Information // future * @see https://developers.binance.com/docs/derivatives/option/market-data/Exchange-Information // option * @see https://developers.binance.com/docs/margin_trading/market-data/Get-All-Cross-Margin-Pairs // cross margin * @see https://developers.binance.com/docs/margin_trading/market-data/Get-All-Isolated-Margin-Symbol // isolated margin * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} an array of objects representing market data */ func (this *binance) 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 promisesRaw interface{} = []interface{}{} var rawFetchMarkets interface{} = this.SafeList(this.Options, "fetchMarkets", []interface{}{"spot", "linear", "inverse"}) var sandboxMode interface{} = this.SafeBool(this.Options, "sandboxMode", false) var fetchMarkets interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(rawFetchMarkets)); i++ { var typeVar interface{} = GetValue(rawFetchMarkets, i) if IsTrue(IsTrue(IsEqual(typeVar, "option")) && IsTrue(sandboxMode)) { continue } AppendToArray(&fetchMarkets,typeVar) } var fetchMargins interface{} = this.SafeBool(this.Options, "fetchMargins", false) for i := 0; IsLessThan(i, GetArrayLength(fetchMarkets)); i++ { var marketType interface{} = GetValue(fetchMarkets, i) if IsTrue(IsEqual(marketType, "spot")) { AppendToArray(&promisesRaw,this.PublicGetExchangeInfo(params)) if IsTrue(IsTrue(IsTrue(fetchMargins) && IsTrue(this.CheckRequiredCredentials(false))) && !IsTrue(sandboxMode)) { AppendToArray(&promisesRaw,this.SapiGetMarginAllPairs(params)) AppendToArray(&promisesRaw,this.SapiGetMarginIsolatedAllPairs(params)) } } else if IsTrue(IsEqual(marketType, "linear")) { AppendToArray(&promisesRaw,this.FapiPublicGetExchangeInfo(params)) } else if IsTrue(IsEqual(marketType, "inverse")) { AppendToArray(&promisesRaw,this.DapiPublicGetExchangeInfo(params)) } else if IsTrue(IsEqual(marketType, "option")) { AppendToArray(&promisesRaw,this.EapiPublicGetExchangeInfo(params)) } else { panic(ExchangeError(Add(Add(Add(this.Id, " fetchMarkets() this.options fetchMarkets \""), marketType), "\" is not a supported market type"))) } } results:= (<-promiseAll(promisesRaw)) PanicOnError(results) var markets interface{} = []interface{}{} AddElementToObject(this.Options, "crossMarginPairsData", []interface{}{}) AddElementToObject(this.Options, "isolatedMarginPairsData", []interface{}{}) for i := 0; IsLessThan(i, GetArrayLength(results)); i++ { var res interface{} = this.SafeValue(results, i) if IsTrue(IsTrue(fetchMargins) && IsTrue(IsArray(res))) { var keysList interface{} = ObjectKeys(this.IndexBy(res, "symbol")) var length interface{} = GetArrayLength(GetValue(this.Options, "crossMarginPairsData")) // first one is the cross-margin promise if IsTrue(IsEqual(length, 0)) { AddElementToObject(this.Options, "crossMarginPairsData", keysList) } else { AddElementToObject(this.Options, "isolatedMarginPairsData", keysList) } } else { var resultMarkets interface{} = this.SafeList2(res, "symbols", "optionSymbols", []interface{}{}) markets = this.ArrayConcat(markets, resultMarkets) } } // // spot / margin // // { // "timezone":"UTC", // "serverTime":1575416692969, // "rateLimits":[ // {"rateLimitType":"REQUEST_WEIGHT","interval":"MINUTE","intervalNum":1,"limit":1200}, // {"rateLimitType":"ORDERS","interval":"SECOND","intervalNum":10,"limit":100}, // {"rateLimitType":"ORDERS","interval":"DAY","intervalNum":1,"limit":200000} // ], // "exchangeFilters":[], // "symbols":[ // { // "symbol":"ETHBTC", // "status":"TRADING", // "baseAsset":"ETH", // "baseAssetPrecision":8, // "quoteAsset":"BTC", // "quotePrecision":8, // "baseCommissionPrecision":8, // "quoteCommissionPrecision":8, // "orderTypes":["LIMIT","LIMIT_MAKER","MARKET","STOP_LOSS_LIMIT","TAKE_PROFIT_LIMIT"], // "icebergAllowed":true, // "ocoAllowed":true, // "quoteOrderQtyMarketAllowed":true, // "allowTrailingStop":false, // "isSpotTradingAllowed":true, // "isMarginTradingAllowed":true, // "filters":[ // {"filterType":"PRICE_FILTER","minPrice":"0.00000100","maxPrice":"100000.00000000","tickSize":"0.00000100"}, // {"filterType":"PERCENT_PRICE","multiplierUp":"5","multiplierDown":"0.2","avgPriceMins":5}, // {"filterType":"LOT_SIZE","minQty":"0.00100000","maxQty":"100000.00000000","stepSize":"0.00100000"}, // {"filterType":"MIN_NOTIONAL","minNotional":"0.00010000","applyToMarket":true,"avgPriceMins":5}, // {"filterType":"ICEBERG_PARTS","limit":10}, // {"filterType":"MARKET_LOT_SIZE","minQty":"0.00000000","maxQty":"63100.00000000","stepSize":"0.00000000"}, // {"filterType":"MAX_NUM_ORDERS","maxNumOrders":200}, // {"filterType":"MAX_NUM_ALGO_ORDERS","maxNumAlgoOrders":5} // ], // "permissions":["SPOT","MARGIN"]} // }, // ], // } // // cross & isolated pairs response: // // [ // { // symbol: "BTCUSDT", // base: "BTC", // quote: "USDT", // isMarginTrade: true, // isBuyAllowed: true, // isSellAllowed: true, // id: "376870555451677893", // doesn't exist in isolated // }, // ] // // futures/usdt-margined (fapi) // // { // "timezone":"UTC", // "serverTime":1575417244353, // "rateLimits":[ // {"rateLimitType":"REQUEST_WEIGHT","interval":"MINUTE","intervalNum":1,"limit":1200}, // {"rateLimitType":"ORDERS","interval":"MINUTE","intervalNum":1,"limit":1200} // ], // "exchangeFilters":[], // "symbols":[ // { // "symbol":"BTCUSDT", // "status":"TRADING", // "maintMarginPercent":"2.5000", // "requiredMarginPercent":"5.0000", // "baseAsset":"BTC", // "quoteAsset":"USDT", // "pricePrecision":2, // "quantityPrecision":3, // "baseAssetPrecision":8, // "quotePrecision":8, // "filters":[ // {"minPrice":"0.01","maxPrice":"100000","filterType":"PRICE_FILTER","tickSize":"0.01"}, // {"stepSize":"0.001","filterType":"LOT_SIZE","maxQty":"1000","minQty":"0.001"}, // {"stepSize":"0.001","filterType":"MARKET_LOT_SIZE","maxQty":"1000","minQty":"0.001"}, // {"limit":200,"filterType":"MAX_NUM_ORDERS"}, // {"multiplierDown":"0.8500","multiplierUp":"1.1500","multiplierDecimal":"4","filterType":"PERCENT_PRICE"} // ], // "orderTypes":["LIMIT","MARKET","STOP"], // "timeInForce":["GTC","IOC","FOK","GTX"] // } // ] // } // // delivery/coin-margined (dapi) // // { // "timezone": "UTC", // "serverTime": 1597667052958, // "rateLimits": [ // {"rateLimitType":"REQUEST_WEIGHT","interval":"MINUTE","intervalNum":1,"limit":6000}, // {"rateLimitType":"ORDERS","interval":"MINUTE","intervalNum":1,"limit":6000} // ], // "exchangeFilters": [], // "symbols": [ // { // "symbol": "BTCUSD_200925", // "pair": "BTCUSD", // "contractType": "CURRENT_QUARTER", // "deliveryDate": 1601020800000, // "onboardDate": 1590739200000, // "contractStatus": "TRADING", // "contractSize": 100, // "marginAsset": "BTC", // "maintMarginPercent": "2.5000", // "requiredMarginPercent": "5.0000", // "baseAsset": "BTC", // "quoteAsset": "USD", // "pricePrecision": 1, // "quantityPrecision": 0, // "baseAssetPrecision": 8, // "quotePrecision": 8, // "equalQtyPrecision": 4, // "filters": [ // {"minPrice":"0.1","maxPrice":"100000","filterType":"PRICE_FILTER","tickSize":"0.1"}, // {"stepSize":"1","filterType":"LOT_SIZE","maxQty":"100000","minQty":"1"}, // {"stepSize":"0","filterType":"MARKET_LOT_SIZE","maxQty":"100000","minQty":"1"}, // {"limit":200,"filterType":"MAX_NUM_ORDERS"}, // {"multiplierDown":"0.9500","multiplierUp":"1.0500","multiplierDecimal":"4","filterType":"PERCENT_PRICE"} // ], // "orderTypes": ["LIMIT","MARKET","STOP","STOP_MARKET","TAKE_PROFIT","TAKE_PROFIT_MARKET","TRAILING_STOP_MARKET"], // "timeInForce": ["GTC","IOC","FOK","GTX"] // }, // { // "symbol": "BTCUSD_PERP", // "pair": "BTCUSD", // "contractType": "PERPETUAL", // "deliveryDate": 4133404800000, // "onboardDate": 1596006000000, // "contractStatus": "TRADING", // "contractSize": 100, // "marginAsset": "BTC", // "maintMarginPercent": "2.5000", // "requiredMarginPercent": "5.0000", // "baseAsset": "BTC", // "quoteAsset": "USD", // "pricePrecision": 1, // "quantityPrecision": 0, // "baseAssetPrecision": 8, // "quotePrecision": 8, // "equalQtyPrecision": 4, // "filters": [ // {"minPrice":"0.1","maxPrice":"100000","filterType":"PRICE_FILTER","tickSize":"0.1"}, // {"stepSize":"1","filterType":"LOT_SIZE","maxQty":"100000","minQty":"1"}, // {"stepSize":"1","filterType":"MARKET_LOT_SIZE","maxQty":"100000","minQty":"1"}, // {"limit":200,"filterType":"MAX_NUM_ORDERS"}, // {"multiplierDown":"0.8500","multiplierUp":"1.1500","multiplierDecimal":"4","filterType":"PERCENT_PRICE"} // ], // "orderTypes": ["LIMIT","MARKET","STOP","STOP_MARKET","TAKE_PROFIT","TAKE_PROFIT_MARKET","TRAILING_STOP_MARKET"], // "timeInForce": ["GTC","IOC","FOK","GTX"] // } // ] // } // // options (eapi) // // { // "timezone": "UTC", // "serverTime": 1675912490405, // "optionContracts": [ // { // "id": 1, // "baseAsset": "SOL", // "quoteAsset": "USDT", // "underlying": "SOLUSDT", // "settleAsset": "USDT" // }, // ... // ], // "optionAssets": [ // {"id":1,"name":"USDT"} // ], // "optionSymbols": [ // { // "contractId": 3, // "expiryDate": 1677225600000, // "filters": [ // {"filterType":"PRICE_FILTER","minPrice":"724.6","maxPrice":"919.2","tickSize":"0.1"}, // {"filterType":"LOT_SIZE","minQty":"0.01","maxQty":"1000","stepSize":"0.01"} // ], // "id": 2474, // "symbol": "ETH-230224-800-C", // "side": "CALL", // "strikePrice": "800.00000000", // "underlying": "ETHUSDT", // "unit": 1, // "makerFeeRate": "0.00020000", // "takerFeeRate": "0.00020000", // "minQty": "0.01", // "maxQty": "1000", // "initialMargin": "0.15000000", // "maintenanceMargin": "0.07500000", // "minInitialMargin": "0.10000000", // "minMaintenanceMargin": "0.05000000", // "priceScale": 1, // "quantityScale": 2, // "quoteAsset": "USDT" // }, // ... // ], // "rateLimits": [ // {"rateLimitType":"REQUEST_WEIGHT","interval":"MINUTE","intervalNum":1,"limit":400}, // {"rateLimitType":"ORDERS","interval":"MINUTE","intervalNum":1,"limit":100}, // {"rateLimitType":"ORDERS","interval":"SECOND","intervalNum":10,"limit":30} // ] // } // if IsTrue(GetValue(this.Options, "adjustForTimeDifference")) { retRes348912 := (<-this.LoadTimeDifference()) PanicOnError(retRes348912) } var result interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(markets)); i++ { AppendToArray(&result,this.ParseMarket(GetValue(markets, i))) } ch <- result return nil }() return ch } func (this *binance) ParseMarket(market interface{}) interface{} { var swap interface{} = false var future interface{} = false var option interface{} = false var underlying interface{} = this.SafeString(market, "underlying") var id interface{} = this.SafeString(market, "symbol") var optionParts interface{} = Split(id, "-") var optionBase interface{} = this.SafeString(optionParts, 0) var lowercaseId interface{} = this.SafeStringLower(market, "symbol") var baseId interface{} = this.SafeString(market, "baseAsset", optionBase) var quoteId interface{} = this.SafeString(market, "quoteAsset") var base interface{} = this.SafeCurrencyCode(baseId) var quote interface{} = this.SafeCurrencyCode(quoteId) var contractType interface{} = this.SafeString(market, "contractType") var contract interface{} = (InOp(market, "contractType")) var expiry interface{} = this.SafeInteger2(market, "deliveryDate", "expiryDate") var settleId interface{} = this.SafeString(market, "marginAsset") if IsTrue(IsTrue((IsEqual(contractType, "PERPETUAL"))) || IsTrue((IsEqual(expiry, 4133404800000)))) { expiry = nil swap = true } else if IsTrue(!IsEqual(underlying, nil)) { contract = true option = true settleId = Ternary(IsTrue((IsEqual(settleId, nil))), "USDT", settleId) } else if IsTrue(!IsEqual(expiry, nil)) { future = true } var settle interface{} = this.SafeCurrencyCode(settleId) var spot interface{} = !IsTrue(contract) var filters interface{} = this.SafeList(market, "filters", []interface{}{}) var filtersByType interface{} = this.IndexBy(filters, "filterType") var status interface{} = this.SafeString2(market, "status", "contractStatus") var contractSize interface{} = nil var fees interface{} = this.Fees var linear interface{} = nil var inverse interface{} = nil var symbol interface{} = Add(Add(base, "/"), quote) var strike interface{} = nil if IsTrue(contract) { if IsTrue(swap) { symbol = Add(Add(symbol, ":"), settle) } else if IsTrue(future) { symbol = Add(Add(Add(Add(symbol, ":"), settle), "-"), this.Yymmdd(expiry)) } else if IsTrue(option) { strike = this.NumberToString(this.ParseToNumeric(this.SafeString(market, "strikePrice"))) symbol = Add(Add(Add(Add(Add(Add(Add(Add(symbol, ":"), settle), "-"), this.Yymmdd(expiry)), "-"), strike), "-"), this.SafeString(optionParts, 3)) } contractSize = this.SafeNumber2(market, "contractSize", "unit", this.ParseNumber("1")) linear = IsEqual(settle, quote) inverse = IsEqual(settle, base) var feesType interface{} = Ternary(IsTrue(linear), "linear", "inverse") fees = this.SafeDict(this.Fees, feesType, map[string]interface{} {}) } var active interface{} = (IsEqual(status, "TRADING")) if IsTrue(spot) { var permissions interface{} = this.SafeList(market, "permissions", []interface{}{}) for j := 0; IsLessThan(j, GetArrayLength(permissions)); j++ { if IsTrue(IsEqual(GetValue(permissions, j), "TRD_GRP_003")) { active = false break } } } var isMarginTradingAllowed interface{} = this.SafeBool(market, "isMarginTradingAllowed", false) var marginModes interface{} = nil if IsTrue(spot) { var hasCrossMargin interface{} = this.InArray(id, GetValue(this.Options, "crossMarginPairsData")) var hasIsolatedMargin interface{} = this.InArray(id, GetValue(this.Options, "isolatedMarginPairsData")) marginModes = map[string]interface{} { "cross": hasCrossMargin, "isolated": hasIsolatedMargin, } } else if IsTrue(IsTrue(linear) || IsTrue(inverse)) { marginModes = map[string]interface{} { "cross": true, "isolated": true, } } var unifiedType interface{} = nil if IsTrue(spot) { unifiedType = "spot" } else if IsTrue(swap) { unifiedType = "swap" } else if IsTrue(future) { unifiedType = "future" } else if IsTrue(option) { unifiedType = "option" active = nil } var parsedStrike interface{} = nil if IsTrue(!IsEqual(strike, nil)) { parsedStrike = this.ParseToNumeric(strike) } var entry interface{} = map[string]interface{} { "id": id, "lowercaseId": lowercaseId, "symbol": symbol, "base": base, "quote": quote, "settle": settle, "baseId": baseId, "quoteId": quoteId, "settleId": settleId, "type": unifiedType, "spot": spot, "margin": IsTrue(spot) && IsTrue(isMarginTradingAllowed), "marginModes": marginModes, "swap": swap, "future": future, "option": option, "active": active, "contract": contract, "linear": linear, "inverse": inverse, "taker": GetValue(GetValue(fees, "trading"), "taker"), "maker": GetValue(GetValue(fees, "trading"), "maker"), "contractSize": contractSize, "expiry": expiry, "expiryDatetime": this.Iso8601(expiry), "strike": parsedStrike, "optionType": this.SafeStringLower(market, "side"), "precision": map[string]interface{} { "amount": this.ParseNumber(this.ParsePrecision(this.SafeString2(market, "quantityPrecision", "quantityScale"))), "price": this.ParseNumber(this.ParsePrecision(this.SafeString2(market, "pricePrecision", "priceScale"))), "base": this.ParseNumber(this.ParsePrecision(this.SafeString(market, "baseAssetPrecision"))), "quote": this.ParseNumber(this.ParsePrecision(this.SafeString(market, "quotePrecision"))), }, "limits": map[string]interface{} { "leverage": map[string]interface{} { "min": nil, "max": nil, }, "amount": map[string]interface{} { "min": this.SafeNumber(market, "minQty"), "max": this.SafeNumber(market, "maxQty"), }, "price": map[string]interface{} { "min": nil, "max": nil, }, "cost": map[string]interface{} { "min": nil, "max": nil, }, }, "info": market, "created": this.SafeInteger(market, "onboardDate"), } if IsTrue(InOp(filtersByType, "PRICE_FILTER")) { var filter interface{} = this.SafeDict(filtersByType, "PRICE_FILTER", map[string]interface{} {}) // PRICE_FILTER reports zero values for maxPrice // since they updated filter types in November 2018 // https://github.com/ccxt/ccxt/issues/4286 // therefore limits['price']['max'] doesn't have any meaningful value except undefined AddElementToObject(GetValue(entry, "limits"), "price", map[string]interface{} { "min": this.SafeNumber(filter, "minPrice"), "max": this.SafeNumber(filter, "maxPrice"), }) AddElementToObject(GetValue(entry, "precision"), "price", this.SafeNumber(filter, "tickSize")) } if IsTrue(InOp(filtersByType, "LOT_SIZE")) { var filter interface{} = this.SafeDict(filtersByType, "LOT_SIZE", map[string]interface{} {}) AddElementToObject(GetValue(entry, "precision"), "amount", this.SafeNumber(filter, "stepSize")) AddElementToObject(GetValue(entry, "limits"), "amount", map[string]interface{} { "min": this.SafeNumber(filter, "minQty"), "max": this.SafeNumber(filter, "maxQty"), }) } if IsTrue(InOp(filtersByType, "MARKET_LOT_SIZE")) { var filter interface{} = this.SafeDict(filtersByType, "MARKET_LOT_SIZE", map[string]interface{} {}) AddElementToObject(GetValue(entry, "limits"), "market", map[string]interface{} { "min": this.SafeNumber(filter, "minQty"), "max": this.SafeNumber(filter, "maxQty"), }) } if IsTrue(IsTrue((InOp(filtersByType, "MIN_NOTIONAL"))) || IsTrue((InOp(filtersByType, "NOTIONAL")))) { var filter interface{} = this.SafeDict2(filtersByType, "MIN_NOTIONAL", "NOTIONAL", map[string]interface{} {}) AddElementToObject(GetValue(GetValue(entry, "limits"), "cost"), "min", this.SafeNumber2(filter, "minNotional", "notional")) AddElementToObject(GetValue(GetValue(entry, "limits"), "cost"), "max", this.SafeNumber(filter, "maxNotional")) } return entry } func (this *binance) ParseBalanceHelper(entry interface{}) interface{} { var account interface{} = this.Account() AddElementToObject(account, "used", this.SafeString(entry, "locked")) AddElementToObject(account, "free", this.SafeString(entry, "free")) var interest interface{} = this.SafeString(entry, "interest") var debt interface{} = this.SafeString(entry, "borrowed") AddElementToObject(account, "debt", Precise.StringAdd(debt, interest)) return account } func (this *binance) ParseBalanceCustom(response interface{}, optionalArgs ...interface{}) interface{} { typeVar := GetArg(optionalArgs, 0, nil) _ = typeVar marginMode := GetArg(optionalArgs, 1, nil) _ = marginMode isPortfolioMargin := GetArg(optionalArgs, 2, false) _ = isPortfolioMargin var result interface{} = map[string]interface{} { "info": response, } var timestamp interface{} = nil var isolated interface{} = IsEqual(marginMode, "isolated") var cross interface{} = IsTrue((IsEqual(typeVar, "margin"))) || IsTrue((IsEqual(marginMode, "cross"))) if IsTrue(isPortfolioMargin) { for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) var account interface{} = this.Account() var currencyId interface{} = this.SafeString(entry, "asset") var code interface{} = this.SafeCurrencyCode(currencyId) if IsTrue(IsEqual(typeVar, "linear")) { AddElementToObject(account, "free", this.SafeString(entry, "umWalletBalance")) AddElementToObject(account, "used", this.SafeString(entry, "umUnrealizedPNL")) } else if IsTrue(IsEqual(typeVar, "inverse")) { AddElementToObject(account, "free", this.SafeString(entry, "cmWalletBalance")) AddElementToObject(account, "used", this.SafeString(entry, "cmUnrealizedPNL")) } else if IsTrue(cross) { var borrowed interface{} = this.SafeString(entry, "crossMarginBorrowed") var interest interface{} = this.SafeString(entry, "crossMarginInterest") AddElementToObject(account, "debt", Precise.StringAdd(borrowed, interest)) AddElementToObject(account, "free", this.SafeString(entry, "crossMarginFree")) AddElementToObject(account, "used", this.SafeString(entry, "crossMarginLocked")) AddElementToObject(account, "total", this.SafeString(entry, "crossMarginAsset")) } else { var usedLinear interface{} = this.SafeString(entry, "umUnrealizedPNL") var usedInverse interface{} = this.SafeString(entry, "cmUnrealizedPNL") var totalUsed interface{} = Precise.StringAdd(usedLinear, usedInverse) var totalWalletBalance interface{} = this.SafeString(entry, "totalWalletBalance") AddElementToObject(account, "total", Precise.StringAdd(totalUsed, totalWalletBalance)) } AddElementToObject(result, code, account) } } else if IsTrue(!IsTrue(isolated) && IsTrue((IsTrue((IsEqual(typeVar, "spot"))) || IsTrue(cross)))) { timestamp = this.SafeInteger(response, "updateTime") var balances interface{} = this.SafeList2(response, "balances", "userAssets", []interface{}{}) for i := 0; IsLessThan(i, GetArrayLength(balances)); i++ { var balance interface{} = GetValue(balances, 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")) if IsTrue(cross) { var debt interface{} = this.SafeString(balance, "borrowed") var interest interface{} = this.SafeString(balance, "interest") AddElementToObject(account, "debt", Precise.StringAdd(debt, interest)) } AddElementToObject(result, code, account) } } else if IsTrue(isolated) { var assets interface{} = this.SafeList(response, "assets") for i := 0; IsLessThan(i, GetArrayLength(assets)); i++ { var asset interface{} = GetValue(assets, i) var marketId interface{} = this.SafeString(asset, "symbol") var symbol interface{} = this.SafeSymbol(marketId, nil, nil, "spot") var base interface{} = this.SafeDict(asset, "baseAsset", map[string]interface{} {}) var quote interface{} = this.SafeDict(asset, "quoteAsset", map[string]interface{} {}) var baseCode interface{} = this.SafeCurrencyCode(this.SafeString(base, "asset")) var quoteCode interface{} = this.SafeCurrencyCode(this.SafeString(quote, "asset")) var subResult interface{} = map[string]interface{} {} AddElementToObject(subResult, baseCode, this.ParseBalanceHelper(base)) AddElementToObject(subResult, quoteCode, this.ParseBalanceHelper(quote)) AddElementToObject(result, symbol, this.SafeBalance(subResult)) } } else if IsTrue(IsEqual(typeVar, "savings")) { var positionAmountVos interface{} = this.SafeList(response, "positionAmountVos", []interface{}{}) for i := 0; IsLessThan(i, GetArrayLength(positionAmountVos)); i++ { var entry interface{} = GetValue(positionAmountVos, i) var currencyId interface{} = this.SafeString(entry, "asset") var code interface{} = this.SafeCurrencyCode(currencyId) var account interface{} = this.Account() var usedAndTotal interface{} = this.SafeString(entry, "amount") AddElementToObject(account, "total", usedAndTotal) AddElementToObject(account, "used", usedAndTotal) AddElementToObject(result, code, account) } } else if IsTrue(IsEqual(typeVar, "funding")) { for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) var account interface{} = this.Account() var currencyId interface{} = this.SafeString(entry, "asset") var code interface{} = this.SafeCurrencyCode(currencyId) AddElementToObject(account, "free", this.SafeString(entry, "free")) var frozen interface{} = this.SafeString(entry, "freeze") var withdrawing interface{} = this.SafeString(entry, "withdrawing") var locked interface{} = this.SafeString(entry, "locked") AddElementToObject(account, "used", Precise.StringAdd(frozen, Precise.StringAdd(locked, withdrawing))) AddElementToObject(result, code, account) } } else { var balances interface{} = response if !IsTrue(IsArray(response)) { balances = this.SafeList(response, "assets", []interface{}{}) } for i := 0; IsLessThan(i, GetArrayLength(balances)); i++ { var balance interface{} = GetValue(balances, 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, "availableBalance")) AddElementToObject(account, "used", this.SafeString(balance, "initialMargin")) AddElementToObject(account, "total", this.SafeString2(balance, "marginBalance", "balance")) AddElementToObject(result, code, account) } } AddElementToObject(result, "timestamp", timestamp) AddElementToObject(result, "datetime", this.Iso8601(timestamp)) return Ternary(IsTrue(isolated), result, this.SafeBalance(result)) } /** * @method * @name binance#fetchBalance * @description query for balance and get the amount of funds available for trading or funds locked in orders * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#account-information-user_data // spot * @see https://developers.binance.com/docs/margin_trading/account/Query-Cross-Margin-Account-Details // cross margin * @see https://developers.binance.com/docs/margin_trading/account/Query-Isolated-Margin-Account-Info // isolated margin * @see https://developers.binance.com/docs/wallet/asset/funding-wallet // funding * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Futures-Account-Balance-V2 // swap * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Futures-Account-Balance // future * @see https://developers.binance.com/docs/derivatives/option/account/Option-Account-Information // option * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Account-Balance // portfolio margin * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.type] 'future', 'delivery', 'savings', 'funding', or 'spot' or 'papi' * @param {string} [params.marginMode] 'cross' or 'isolated', for margin trading, uses this.options.defaultMarginMode if not passed, defaults to undefined/None/null * @param {string[]|undefined} [params.symbols] unified market symbols, only used in isolated margin mode * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch the balance for a portfolio margin account * @param {string} [params.subType] 'linear' or 'inverse' * @returns {object} a [balance structure]{@link https://docs.ccxt.com/#/?id=balance-structure} */ func (this *binance) 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 retRes38258 := (<-this.LoadMarkets()) PanicOnError(retRes38258) var defaultType interface{} = this.SafeString2(this.Options, "fetchBalance", "defaultType", "spot") var typeVar interface{} = this.SafeString(params, "type", defaultType) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchBalance", nil, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchBalance", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var marginMode interface{} = nil var query interface{} = nil marginModequeryVariable := this.HandleMarginModeAndParams("fetchBalance", params); marginMode = GetValue(marginModequeryVariable,0); query = GetValue(marginModequeryVariable,1) query = this.Omit(query, "type") var response interface{} = nil var request interface{} = map[string]interface{} {} if IsTrue(IsTrue(isPortfolioMargin) || IsTrue((IsEqual(typeVar, "papi")))) { if IsTrue(this.IsLinear(typeVar, subType)) { typeVar = "linear" } else if IsTrue(this.IsInverse(typeVar, subType)) { typeVar = "inverse" } isPortfolioMargin = true response = (<-this.PapiGetBalance(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(this.IsLinear(typeVar, subType)) { typeVar = "linear" var useV2 interface{} = nil useV2paramsVariable := this.HandleOptionAndParams(params, "fetchBalance", "useV2", false); useV2 = GetValue(useV2paramsVariable,0); params = GetValue(useV2paramsVariable,1) params = this.Extend(request, query) if !IsTrue(useV2) { response = (<-this.FapiPrivateV3GetAccount(params)) PanicOnError(response) } else { response = (<-this.FapiPrivateV2GetAccount(params)) PanicOnError(response) } } else if IsTrue(this.IsInverse(typeVar, subType)) { typeVar = "inverse" response = (<-this.DapiPrivateGetAccount(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(IsEqual(marginMode, "isolated")) { var paramSymbols interface{} = this.SafeList(params, "symbols") query = this.Omit(query, "symbols") if IsTrue(!IsEqual(paramSymbols, nil)) { var symbols interface{} = "" if IsTrue(IsArray(paramSymbols)) { symbols = this.MarketId(GetValue(paramSymbols, 0)) for i := 1; IsLessThan(i, GetArrayLength(paramSymbols)); i++ { var symbol interface{} = GetValue(paramSymbols, i) var id interface{} = this.MarketId(symbol) symbols = Add(symbols, Add(",", id)) } } else { symbols = paramSymbols } AddElementToObject(request, "symbols", symbols) } response = (<-this.SapiGetMarginIsolatedAccount(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(IsTrue((IsEqual(typeVar, "margin"))) || IsTrue((IsEqual(marginMode, "cross")))) { response = (<-this.SapiGetMarginAccount(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "savings")) { response = (<-this.SapiGetLendingUnionAccount(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "funding")) { response = (<-this.SapiPostAssetGetFundingAsset(this.Extend(request, query))) PanicOnError(response) } else { response = (<-this.PrivateGetAccount(this.Extend(request, query))) PanicOnError(response) } // // spot // // { // "makerCommission": 10, // "takerCommission": 10, // "buyerCommission": 0, // "sellerCommission": 0, // "canTrade": true, // "canWithdraw": true, // "canDeposit": true, // "updateTime": 1575357359602, // "accountType": "MARGIN", // "balances": [ // { asset: "BTC", free: "0.00219821", locked: "0.00000000" }, // ] // } // // margin (cross) // // { // "borrowEnabled":true, // "marginLevel":"999.00000000", // "totalAssetOfBtc":"0.00000000", // "totalLiabilityOfBtc":"0.00000000", // "totalNetAssetOfBtc":"0.00000000", // "tradeEnabled":true, // "transferEnabled":true, // "userAssets":[ // {"asset":"MATIC","borrowed":"0.00000000","free":"0.00000000","interest":"0.00000000","locked":"0.00000000","netAsset":"0.00000000"}, // {"asset":"VET","borrowed":"0.00000000","free":"0.00000000","interest":"0.00000000","locked":"0.00000000","netAsset":"0.00000000"}, // {"asset":"USDT","borrowed":"0.00000000","free":"0.00000000","interest":"0.00000000","locked":"0.00000000","netAsset":"0.00000000"} // ], // } // // margin (isolated) // // { // "info": { // "assets": [ // { // "baseAsset": { // "asset": "1INCH", // "borrowEnabled": true, // "borrowed": "0", // "free": "0", // "interest": "0", // "locked": "0", // "netAsset": "0", // "netAssetOfBtc": "0", // "repayEnabled": true, // "totalAsset": "0" // }, // "quoteAsset": { // "asset": "USDT", // "borrowEnabled": true, // "borrowed": "0", // "free": "11", // "interest": "0", // "locked": "0", // "netAsset": "11", // "netAssetOfBtc": "0.00054615", // "repayEnabled": true, // "totalAsset": "11" // }, // "symbol": "1INCHUSDT", // "isolatedCreated": true, // "marginLevel": "999", // "marginLevelStatus": "EXCESSIVE", // "marginRatio": "5", // "indexPrice": "0.59184331", // "liquidatePrice": "0", // "liquidateRate": "0", // "tradeEnabled": true, // "enabled": true // }, // ] // } // } // // futures (fapi) // // fapiPrivateV3GetAccount // // { // "feeTier":0, // "canTrade":true, // "canDeposit":true, // "canWithdraw":true, // "updateTime":0, // "totalInitialMargin":"0.00000000", // "totalMaintMargin":"0.00000000", // "totalWalletBalance":"0.00000000", // "totalUnrealizedProfit":"0.00000000", // "totalMarginBalance":"0.00000000", // "totalPositionInitialMargin":"0.00000000", // "totalOpenOrderInitialMargin":"0.00000000", // "totalCrossWalletBalance":"0.00000000", // "totalCrossUnPnl":"0.00000000", // "availableBalance":"0.00000000", // "maxWithdrawAmount":"0.00000000", // "assets":[ // { // "asset":"BNB", // "walletBalance":"0.01000000", // "unrealizedProfit":"0.00000000", // "marginBalance":"0.01000000", // "maintMargin":"0.00000000", // "initialMargin":"0.00000000", // "positionInitialMargin":"0.00000000", // "openOrderInitialMargin":"0.00000000", // "maxWithdrawAmount":"0.01000000", // "crossWalletBalance":"0.01000000", // "crossUnPnl":"0.00000000", // "availableBalance":"0.01000000" // } // ], // "positions":[ // { // "symbol":"BTCUSDT", // "initialMargin":"0", // "maintMargin":"0", // "unrealizedProfit":"0.00000000", // "positionInitialMargin":"0", // "openOrderInitialMargin":"0", // "leverage":"21", // "isolated":false, // "entryPrice":"0.00000", // "maxNotional":"5000000", // "positionSide":"BOTH" // }, // ] // } // // fapiPrivateV2GetBalance // // [ // { // "accountAlias":"FzFzXquXXqoC", // "asset":"BNB", // "balance":"0.01000000", // "crossWalletBalance":"0.01000000", // "crossUnPnl":"0.00000000", // "availableBalance":"0.01000000", // "maxWithdrawAmount":"0.01000000" // } // ] // // binance pay // // [ // { // "asset": "BUSD", // "free": "1129.83", // "locked": "0", // "freeze": "0", // "withdrawing": "0" // } // ] // // portfolio margin // // [ // { // "asset": "USDT", // "totalWalletBalance": "66.9923261", // "crossMarginAsset": "35.9697141", // "crossMarginBorrowed": "0.0", // "crossMarginFree": "35.9697141", // "crossMarginInterest": "0.0", // "crossMarginLocked": "0.0", // "umWalletBalance": "31.022612", // "umUnrealizedPNL": "0.0", // "cmWalletBalance": "0.0", // "cmUnrealizedPNL": "0.0", // "updateTime": 0, // "negativeBalance": "0.0" // }, // ] // ch <- this.ParseBalanceCustom(response, typeVar, marginMode, isPortfolioMargin) return nil }() return ch } /** * @method * @name binance#fetchOrderBook * @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#order-book // spot * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Order-Book // swap * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Order-Book // future * @see https://developers.binance.com/docs/derivatives/option/market-data/Order-Book // option * @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 *binance) 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 retRes40838 := (<-this.LoadMarkets()) PanicOnError(retRes40838) 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) // default 100, max 5000, see https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#order-book } var response interface{} = nil if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPublicGetDepth(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "linear")) { response = (<-this.FapiPublicGetDepth(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPublicGetDepth(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PublicGetDepth(this.Extend(request, params))) PanicOnError(response) } // // future // // { // "lastUpdateId":333598053905, // "E":1618631511986, // "T":1618631511964, // "bids":[ // ["2493.56","20.189"], // ["2493.54","1.000"], // ["2493.51","0.005"] // ], // "asks":[ // ["2493.57","0.877"], // ["2493.62","0.063"], // ["2493.71","12.054"], // ] // } // // options (eapi) // // { // "bids": [ // ["108.7","16.08"], // ["106","21.29"], // ["82.4","0.02"] // ], // "asks": [ // ["111.4","19.52"], // ["119.9","17.6"], // ["141.2","31"] // ], // "T": 1676771382078, // "u": 1015939 // } // var timestamp interface{} = this.SafeInteger(response, "T") var orderbook interface{} = this.ParseOrderBook(response, symbol, timestamp) AddElementToObject(orderbook, "nonce", this.SafeInteger2(response, "lastUpdateId", "u")) ch <- orderbook return nil }() return ch } func (this *binance) ParseTicker(ticker interface{}, optionalArgs ...interface{}) interface{} { // markPrices // // { // "symbol": "BTCUSDT", // "markPrice": "11793.63104562", // mark price // "indexPrice": "11781.80495970", // index price // "estimatedSettlePrice": "11781.16138815", // Estimated Settle Price, only useful in the last hour before the settlement starts. // "lastFundingRate": "0.00038246", // This is the lastest estimated funding rate // "nextFundingTime": 1597392000000, // "interestRate": "0.00010000", // "time": 1597370495002 // } // // { // "symbol": "ETHBTC", // "priceChange": "0.00068700", // "priceChangePercent": "2.075", // "weightedAvgPrice": "0.03342681", // "prevClosePrice": "0.03310300", // "lastPrice": "0.03378900", // "lastQty": "0.07700000", // "bidPrice": "0.03378900", // "bidQty": "7.16800000", // "askPrice": "0.03379000", // "askQty": "24.00000000", // "openPrice": "0.03310200", // "highPrice": "0.03388900", // "lowPrice": "0.03306900", // "volume": "205478.41000000", // "quoteVolume": "6868.48826294", // "openTime": 1601469986932, // "closeTime": 1601556386932, // "firstId": 196098772, // "lastId": 196186315, // "count": 87544 // } // // coinm // // { // "baseVolume": "214549.95171161", // "closeTime": "1621965286847", // "count": "1283779", // "firstId": "152560106", // "highPrice": "39938.3", // "lastId": "153843955", // "lastPrice": "37993.4", // "lastQty": "1", // "lowPrice": "36457.2", // "openPrice": "37783.4", // "openTime": "1621878840000", // "pair": "BTCUSD", // "priceChange": "210.0", // "priceChangePercent": "0.556", // "symbol": "BTCUSD_PERP", // "volume": "81990451", // "weightedAvgPrice": "38215.08713747" // } // // eapi: fetchTicker, fetchTickers // // { // "symbol": "ETH-230510-1825-C", // "priceChange": "-5.1", // "priceChangePercent": "-0.1854", // "lastPrice": "22.4", // "lastQty": "0", // "open": "27.5", // "high": "34.1", // "low": "22.4", // "volume": "6.83", // "amount": "201.44", // "bidPrice": "21.9", // "askPrice": "22.4", // "openTime": 1683614771898, // "closeTime": 1683695017784, // "firstTradeId": 12, // "tradeCount": 22, // "strikePrice": "1825", // "exercisePrice": "1845.95341176" // } // // spot bidsAsks // // { // "symbol":"ETHBTC", // "bidPrice":"0.07466800", // "bidQty":"5.31990000", // "askPrice":"0.07466900", // "askQty":"10.93540000" // } // // usdm bidsAsks // // { // "symbol":"BTCUSDT", // "bidPrice":"21321.90", // "bidQty":"33.592", // "askPrice":"21322.00", // "askQty":"1.427", // "time":"1673899207538" // } // // coinm bidsAsks // // { // "symbol":"BTCUSD_PERP", // "pair":"BTCUSD", // "bidPrice":"21301.2", // "bidQty":"188", // "askPrice":"21301.3", // "askQty":"10302", // "time":"1673899278514" // } // market := GetArg(optionalArgs, 0, nil) _ = market var timestamp interface{} = this.SafeInteger2(ticker, "closeTime", "time") var marketType interface{} = nil if IsTrue((InOp(ticker, "time"))) { marketType = "contract" } if IsTrue(IsEqual(marketType, nil)) { marketType = Ternary(IsTrue((InOp(ticker, "bidQty"))), "spot", "contract") } var marketId interface{} = this.SafeString(ticker, "symbol") var symbol interface{} = this.SafeSymbol(marketId, market, nil, marketType) var last interface{} = this.SafeString(ticker, "lastPrice") var wAvg interface{} = this.SafeString(ticker, "weightedAvgPrice") var isCoinm interface{} = (InOp(ticker, "baseVolume")) var baseVolume interface{} = nil var quoteVolume interface{} = nil if IsTrue(isCoinm) { baseVolume = this.SafeString(ticker, "baseVolume") // 'volume' field in inverse markets is not quoteVolume, but traded amount (per contracts) quoteVolume = Precise.StringMul(baseVolume, wAvg) } else { baseVolume = this.SafeString(ticker, "volume") quoteVolume = this.SafeString2(ticker, "quoteVolume", "amount") } return this.SafeTicker(map[string]interface{} { "symbol": symbol, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "high": this.SafeString2(ticker, "highPrice", "high"), "low": this.SafeString2(ticker, "lowPrice", "low"), "bid": this.SafeString(ticker, "bidPrice"), "bidVolume": this.SafeString(ticker, "bidQty"), "ask": this.SafeString(ticker, "askPrice"), "askVolume": this.SafeString(ticker, "askQty"), "vwap": wAvg, "open": this.SafeString2(ticker, "openPrice", "open"), "close": last, "last": last, "previousClose": this.SafeString(ticker, "prevClosePrice"), "change": this.SafeString(ticker, "priceChange"), "percentage": this.SafeString(ticker, "priceChangePercent"), "average": nil, "baseVolume": baseVolume, "quoteVolume": quoteVolume, "markPrice": this.SafeString(ticker, "markPrice"), "indexPrice": this.SafeString(ticker, "indexPrice"), "info": ticker, }, market) } /** * @method * @name binance#fetchStatus * @description the latest known information on the availability of the exchange API * @see https://developers.binance.com/docs/wallet/others/system-status * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [status structure]{@link https://docs.ccxt.com/#/?id=exchange-status-structure} */ func (this *binance) FetchStatus(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.SapiGetSystemStatus(params)) PanicOnError(response) // // { // "status": 0, // 0: normal,1:system maintenance // "msg": "normal" // "normal", "system_maintenance" // } // var statusRaw interface{} = this.SafeString(response, "status") ch <- map[string]interface{} { "status": this.SafeString(map[string]interface{} { "0": "ok", "1": "maintenance", }, statusRaw, statusRaw), "updated": nil, "eta": nil, "url": nil, "info": response, } return nil }() return ch } /** * @method * @name binance#fetchTicker * @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#24hr-ticker-price-change-statistics // spot * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#rolling-window-price-change-statistics // spot * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/24hr-Ticker-Price-Change-Statistics // swap * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/24hr-Ticker-Price-Change-Statistics // future * @see https://developers.binance.com/docs/derivatives/option/market-data/24hr-Ticker-Price-Change-Statistics // option * @param {string} symbol unified symbol of the market to fetch the ticker for * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.rolling] (spot only) default false, if true, uses the rolling 24 hour ticker endpoint /api/v3/ticker * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ func (this *binance) 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 retRes43498 := (<-this.LoadMarkets()) PanicOnError(retRes43498) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } var response interface{} = nil if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPublicGetTicker(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "linear")) { response = (<-this.FapiPublicGetTicker24hr(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPublicGetTicker24hr(this.Extend(request, params))) PanicOnError(response) } else { var rolling interface{} = this.SafeBool(params, "rolling", false) params = this.Omit(params, "rolling") if IsTrue(rolling) { response = (<-this.PublicGetTicker(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PublicGetTicker24hr(this.Extend(request, params))) PanicOnError(response) } } if IsTrue(IsArray(response)) { var firstTicker interface{} = this.SafeDict(response, 0, map[string]interface{} {}) ch <- this.ParseTicker(firstTicker, market) return nil } ch <- this.ParseTicker(response, market) return nil }() return ch } /** * @method * @name binance#fetchBidsAsks * @description fetches the bid and ask price and volume for multiple markets * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#symbol-order-book-ticker // spot * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Symbol-Order-Book-Ticker // swap * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Symbol-Order-Book-Ticker // future * @param {string[]|undefined} symbols unified symbols of the markets to fetch the bids and asks for, all markets are returned if not assigned * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ func (this *binance) FetchBidsAsks(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 retRes43908 := (<-this.LoadMarkets()) PanicOnError(retRes43908) symbols = this.MarketSymbols(symbols, nil, true, true, true) var market interface{} = this.GetMarketFromSymbols(symbols) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchBidsAsks", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchBidsAsks", market, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { response = (<-this.FapiPublicGetTickerBookTicker(params)) PanicOnError(response) } else if IsTrue(this.IsInverse(typeVar, subType)) { response = (<-this.DapiPublicGetTickerBookTicker(params)) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "spot")) { var request interface{} = map[string]interface{} {} if IsTrue(!IsEqual(symbols, nil)) { AddElementToObject(request, "symbols", this.Json(this.MarketIds(symbols))) } response = (<-this.PublicGetTickerBookTicker(this.Extend(request, params))) PanicOnError(response) } else { panic(NotSupported(Add(Add(Add(this.Id, " fetchBidsAsks() does not support "), typeVar), " markets yet"))) } ch <- this.ParseTickers(response, symbols) return nil }() return ch } /** * @method * @name binance#fetchLastPrices * @description fetches the last price for multiple markets * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#symbol-price-ticker // spot * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Symbol-Price-Ticker // swap * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Symbol-Price-Ticker // future * @param {string[]|undefined} symbols unified symbols of the markets to fetch the last prices * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a dictionary of lastprices structures */ func (this *binance) FetchLastPrices(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 retRes44278 := (<-this.LoadMarkets()) PanicOnError(retRes44278) symbols = this.MarketSymbols(symbols, nil, true, true, true) var market interface{} = this.GetMarketFromSymbols(symbols) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchLastPrices", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchLastPrices", market, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { response = (<-this.FapiPublicV2GetTickerPrice(params)) PanicOnError(response) } else if IsTrue(this.IsInverse(typeVar, subType)) { response = (<-this.DapiPublicGetTickerPrice(params)) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "spot")) { response = (<-this.PublicGetTickerPrice(params)) PanicOnError(response) } else { panic(NotSupported(Add(Add(Add(this.Id, " fetchLastPrices() does not support "), typeVar), " markets yet"))) } ch <- this.ParseLastPrices(response, symbols) return nil }() return ch } func (this *binance) ParseLastPrice(entry interface{}, optionalArgs ...interface{}) interface{} { // // spot // // { // "symbol": "LTCBTC", // "price": "4.00000200" // } // // usdm (swap/future) // // { // "symbol": "BTCUSDT", // "price": "6000.01", // "time": 1589437530011 // Transaction time // } // // // coinm (swap/future) // // { // "symbol": "BTCUSD_200626", // symbol ("BTCUSD_200626", "BTCUSD_PERP", etc..) // "ps": "BTCUSD", // pair // "price": "9647.8", // "time": 1591257246176 // } // market := GetArg(optionalArgs, 0, nil) _ = market var timestamp interface{} = this.SafeInteger(entry, "time") var typeVar interface{} = Ternary(IsTrue((IsEqual(timestamp, nil))), "spot", "swap") var marketId interface{} = this.SafeString(entry, "symbol") market = this.SafeMarket(marketId, market, nil, typeVar) return map[string]interface{} { "symbol": GetValue(market, "symbol"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "price": this.SafeNumberOmitZero(entry, "price"), "side": nil, "info": entry, } } /** * @method * @name binance#fetchTickers * @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#24hr-ticker-price-change-statistics // spot * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/24hr-Ticker-Price-Change-Statistics // swap * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/24hr-Ticker-Price-Change-Statistics // future * @see https://developers.binance.com/docs/derivatives/option/market-data/24hr-Ticker-Price-Change-Statistics // option * @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 * @param {string} [params.subType] "linear" or "inverse" * @param {string} [params.type] 'spot', 'option', use params["subType"] for swap and future markets * @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ func (this *binance) 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 retRes45328 := (<-this.LoadMarkets()) PanicOnError(retRes45328) symbols = this.MarketSymbols(symbols, nil, true, true, true) var market interface{} = this.GetMarketFromSymbols(symbols) 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(this.IsLinear(typeVar, subType)) { response = (<-this.FapiPublicGetTicker24hr(params)) PanicOnError(response) } else if IsTrue(this.IsInverse(typeVar, subType)) { response = (<-this.DapiPublicGetTicker24hr(params)) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "spot")) { var request interface{} = map[string]interface{} {} if IsTrue(!IsEqual(symbols, nil)) { AddElementToObject(request, "symbols", this.Json(this.MarketIds(symbols))) } response = (<-this.PublicGetTicker24hr(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.EapiPublicGetTicker(params)) PanicOnError(response) } else { panic(NotSupported(Add(Add(Add(this.Id, " fetchTickers() does not support "), typeVar), " markets yet"))) } ch <- this.ParseTickers(response, symbols) return nil }() return ch } /** * @method * @name binance#fetchMarkPrice * @description fetches mark price for the market * @see https://binance-docs.github.io/apidocs/futures/en/#mark-price * @see https://binance-docs.github.io/apidocs/delivery/en/#index-price-and-mark-price * @param {string} symbol unified symbol of the market to fetch the ticker for * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ func (this *binance) 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 retRes45708 := (<-this.LoadMarkets()) PanicOnError(retRes45708) var market interface{} = this.Market(symbol) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchMarkPrice", market, params, "swap"); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) 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(this.IsLinear(typeVar, subType)) { response = (<-this.FapiPublicGetPremiumIndex(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(this.IsInverse(typeVar, subType)) { response = (<-this.DapiPublicGetPremiumIndex(this.Extend(request, params))) PanicOnError(response) } else { panic(NotSupported(Add(Add(Add(this.Id, " fetchMarkPrice() does not support "), typeVar), " markets yet"))) } if IsTrue(IsArray(response)) { ch <- this.ParseTicker(this.SafeDict(response, 0, map[string]interface{} {}), market) return nil } ch <- this.ParseTicker(response, market) return nil }() return ch } /** * @method * @name binance#fetchMarkPrices * @description fetches mark prices for multiple markets * @see https://binance-docs.github.io/apidocs/futures/en/#mark-price * @see https://binance-docs.github.io/apidocs/delivery/en/#index-price-and-mark-price * @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 * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ func (this *binance) 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 retRes46058 := (<-this.LoadMarkets()) PanicOnError(retRes46058) symbols = this.MarketSymbols(symbols, nil, true, true, true) var market interface{} = this.GetMarketFromSymbols(symbols) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchMarkPrices", market, params, "swap"); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) 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(this.IsLinear(typeVar, subType)) { response = (<-this.FapiPublicGetPremiumIndex(params)) PanicOnError(response) } else if IsTrue(this.IsInverse(typeVar, subType)) { response = (<-this.DapiPublicGetPremiumIndex(params)) PanicOnError(response) } else { panic(NotSupported(Add(Add(Add(this.Id, " fetchMarkPrices() does not support "), typeVar), " markets yet"))) } ch <- this.ParseTickers(response, symbols) return nil }() return ch } func (this *binance) ParseOHLCV(ohlcv interface{}, optionalArgs ...interface{}) interface{} { // when api method = publicGetKlines || fapiPublicGetKlines || dapiPublicGetKlines // [ // 1591478520000, // open time // "0.02501300", // open // "0.02501800", // high // "0.02500000", // low // "0.02500000", // close // "22.19000000", // volume // 1591478579999, // close time // "0.55490906", // quote asset volume, base asset volume for dapi // 40, // number of trades // "10.92900000", // taker buy base asset volume // "0.27336462", // taker buy quote asset volume // "0" // ignore // ] // // when api method = fapiPublicGetMarkPriceKlines || fapiPublicGetIndexPriceKlines // [ // [ // 1591256460000, // Open time // "9653.29201333", // Open // "9654.56401333", // High // "9653.07367333", // Low // "9653.07367333", // Close (or latest price) // "0", // Ignore // 1591256519999, // Close time // "0", // Ignore // 60, // Number of bisic data // "0", // Ignore // "0", // Ignore // "0" // Ignore // ] // ] // // options // // { // "open": "32.2", // "high": "32.2", // "low": "32.2", // "close": "32.2", // "volume": "0", // "interval": "5m", // "tradeCount": 0, // "takerVolume": "0", // "takerAmount": "0", // "amount": "0", // "openTime": 1677096900000, // "closeTime": 1677097200000 // } // market := GetArg(optionalArgs, 0, nil) _ = market var inverse interface{} = this.SafeBool(market, "inverse") var volumeIndex interface{} = Ternary(IsTrue(inverse), 7, 5) return []interface{}{this.SafeInteger2(ohlcv, 0, "openTime"), this.SafeNumber2(ohlcv, 1, "open"), this.SafeNumber2(ohlcv, 2, "high"), this.SafeNumber2(ohlcv, 3, "low"), this.SafeNumber2(ohlcv, 4, "close"), this.SafeNumber2(ohlcv, volumeIndex, "volume")} } /** * @method * @name binance#fetchOHLCV * @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#klinecandlestick-data * @see https://developers.binance.com/docs/derivatives/option/market-data/Kline-Candlestick-Data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Kline-Candlestick-Data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Premium-Index-Kline-Data * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Kline-Candlestick-Data * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Index-Price-Kline-Candlestick-Data * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Mark-Price-Kline-Candlestick-Data * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Premium-Index-Kline-Data * @param {string} symbol unified symbol of the market to fetch OHLCV data for * @param {string} timeframe the length of time each candle represents * @param {int} [since] timestamp in ms of the earliest candle to fetch * @param {int} [limit] the maximum amount of candles to fetch * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.price] "mark" or "index" for mark price and index price candles * @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 *binance) 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 retRes47128 := (<-this.LoadMarkets()) PanicOnError(retRes47128) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOHLCV", "paginate", false); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes471619 := (<-this.FetchPaginatedCallDeterministic("fetchOHLCV", symbol, since, limit, timeframe, params, 1000)) PanicOnError(retRes471619) ch <- retRes471619 return nil } var market interface{} = this.Market(symbol) // binance docs say that the default limit 500, max 1500 for futures, max 1000 for spot markets // the reality is that the time range wider than 500 candles won't work right var defaultLimit interface{} = 500 var maxLimit interface{} = 1500 var price interface{} = this.SafeString(params, "price") var until interface{} = this.SafeInteger(params, "until") params = this.Omit(params, []interface{}{"price", "until"}) if IsTrue(IsTrue(IsTrue(!IsEqual(since, nil)) && IsTrue(!IsEqual(until, nil))) && IsTrue(IsEqual(limit, nil))) { limit = maxLimit } limit = Ternary(IsTrue((IsEqual(limit, nil))), defaultLimit, mathMin(limit, maxLimit)) var request interface{} = map[string]interface{} { "interval": this.SafeString(this.Timeframes, timeframe, timeframe), "limit": limit, } var marketId interface{} = GetValue(market, "id") if IsTrue(IsEqual(price, "index")) { var parts interface{} = Split(marketId, "_") var pair interface{} = this.SafeString(parts, 0) AddElementToObject(request, "pair", pair) // Index price takes this argument instead of symbol } else { AddElementToObject(request, "symbol", marketId) } // const duration = this.parseTimeframe (timeframe); if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) // // It didn't work before without the endTime // https://github.com/ccxt/ccxt/issues/8454 // if IsTrue(GetValue(market, "inverse")) { if IsTrue(IsGreaterThan(since, 0)) { var duration interface{} = this.ParseTimeframe(timeframe) var endTime interface{} = this.Sum(since, Subtract(Multiply(Multiply(limit, duration), 1000), 1)) var now interface{} = this.Milliseconds() AddElementToObject(request, "endTime", mathMin(now, endTime)) } } } if IsTrue(!IsEqual(until, nil)) { AddElementToObject(request, "endTime", until) } var response interface{} = nil if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPublicGetKlines(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(price, "mark")) { if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPublicGetMarkPriceKlines(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPublicGetMarkPriceKlines(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(IsEqual(price, "index")) { if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPublicGetIndexPriceKlines(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPublicGetIndexPriceKlines(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(IsEqual(price, "premiumIndex")) { if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPublicGetPremiumIndexKlines(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPublicGetPremiumIndexKlines(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "linear")) { response = (<-this.FapiPublicGetKlines(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPublicGetKlines(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PublicGetKlines(this.Extend(request, params))) PanicOnError(response) } // // [ // [1591478520000,"0.02501300","0.02501800","0.02500000","0.02500000","22.19000000",1591478579999,"0.55490906",40,"10.92900000","0.27336462","0"], // [1591478580000,"0.02499600","0.02500900","0.02499400","0.02500300","21.34700000",1591478639999,"0.53370468",24,"7.53800000","0.18850725","0"], // [1591478640000,"0.02500800","0.02501100","0.02500300","0.02500800","154.14200000",1591478699999,"3.85405839",97,"5.32300000","0.13312641","0"], // ] // // options (eapi) // // [ // { // "open": "32.2", // "high": "32.2", // "low": "32.2", // "close": "32.2", // "volume": "0", // "interval": "5m", // "tradeCount": 0, // "takerVolume": "0", // "takerAmount": "0", // "amount": "0", // "openTime": 1677096900000, // "closeTime": 1677097200000 // } // ] // var candles interface{} = this.ParseOHLCVs(response, market, timeframe, since, limit) ch <- candles return nil }() return ch } func (this *binance) ParseTrade(trade interface{}, optionalArgs ...interface{}) interface{} { market := GetArg(optionalArgs, 0, nil) _ = market if IsTrue(InOp(trade, "isDustTrade")) { return this.ParseDustTrade(trade, market) } // // aggregate trades // https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list // // { // "a": 26129, // Aggregate tradeId // "p": "0.01633102", // Price // "q": "4.70443515", // Quantity // "f": 27781, // First tradeId // "l": 27781, // Last tradeId // "T": 1498793709153, // Timestamp // "m": true, // Was the buyer the maker? // "M": true // Was the trade the best price match? // } // // REST: aggregate trades for swap & future (both linear and inverse) // // { // "a": "269772814", // "p": "25864.1", // "q": "3", // "f": "662149354", // "l": "662149355", // "T": "1694209776022", // "m": false, // } // // recent public trades and old public trades // https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#recent-trades-list // https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#old-trade-lookup-market_data // // { // "id": 28457, // "price": "4.00000100", // "qty": "12.00000000", // "time": 1499865549590, // "isBuyerMaker": true, // "isBestMatch": true // } // // private trades // https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-trade-list-user_data // // { // "symbol": "BNBBTC", // "id": 28457, // "orderId": 100234, // "price": "4.00000100", // "qty": "12.00000000", // "commission": "10.10000000", // "commissionAsset": "BNB", // "time": 1499865549590, // "isBuyer": true, // "isMaker": false, // "isBestMatch": true // } // // futures trades // // { // "accountId": 20, // "buyer": False, // "commission": "-0.07819010", // "commissionAsset": "USDT", // "counterPartyId": 653, // "id": 698759, // "maker": False, // "orderId": 25851813, // "price": "7819.01", // "qty": "0.002", // "quoteQty": "0.01563", // "realizedPnl": "-0.91539999", // "side": "SELL", // "symbol": "BTCUSDT", // "time": 1569514978020 // } // { // "symbol": "BTCUSDT", // "id": 477128891, // "orderId": 13809777875, // "side": "SELL", // "price": "38479.55", // "qty": "0.001", // "realizedPnl": "-0.00009534", // "marginAsset": "USDT", // "quoteQty": "38.47955", // "commission": "-0.00076959", // "commissionAsset": "USDT", // "time": 1612733566708, // "positionSide": "BOTH", // "maker": true, // "buyer": false // } // // { respType: FULL } // // { // "price": "4000.00000000", // "qty": "1.00000000", // "commission": "4.00000000", // "commissionAsset": "USDT", // "tradeId": "1234", // } // // options: fetchMyTrades // // { // "id": 1125899906844226012, // "tradeId": 73, // "orderId": 4638761100843040768, // "symbol": "ETH-230211-1500-C", // "price": "18.70000000", // "quantity": "-0.57000000", // "fee": "0.17305890", // "realizedProfit": "-3.53400000", // "side": "SELL", // "type": "LIMIT", // "volatility": "0.30000000", // "liquidity": "MAKER", // "time": 1676085216845, // "priceScale": 1, // "quantityScale": 2, // "optionSide": "CALL", // "quoteAsset": "USDT" // } // // options: fetchTrades // // { // "id": 1, // "symbol": "ETH-230216-1500-C", // "price": "35.5", // "qty": "0.03", // "quoteQty": "1.065", // "side": 1, // "time": 1676366446072 // } // // fetchMyTrades: linear portfolio margin // // { // "symbol": "BTCUSDT", // "id": 4575108247, // "orderId": 261942655610, // "side": "SELL", // "price": "47263.40", // "qty": "0.010", // "realizedPnl": "27.38400000", // "marginAsset": "USDT", // "quoteQty": "472.63", // "commission": "0.18905360", // "commissionAsset": "USDT", // "time": 1707530039409, // "buyer": false, // "maker": false, // "positionSide": "LONG" // } // // fetchMyTrades: inverse portfolio margin // // { // "symbol": "ETHUSD_PERP", // "id": 701907838, // "orderId": 71548909034, // "pair": "ETHUSD", // "side": "SELL", // "price": "2498.15", // "qty": "1", // "realizedPnl": "0.00012517", // "marginAsset": "ETH", // "baseQty": "0.00400296", // "commission": "0.00000160", // "commissionAsset": "ETH", // "time": 1707530317519, // "positionSide": "LONG", // "buyer": false, // "maker": false // } // // fetchMyTrades: spot margin portfolio margin // // { // "symbol": "ADAUSDT", // "id": 470227543, // "orderId": 4421170947, // "price": "0.53880000", // "qty": "10.00000000", // "quoteQty": "5.38800000", // "commission": "0.00538800", // "commissionAsset": "USDT", // "time": 1707545780522, // "isBuyer": false, // "isMaker": false, // "isBestMatch": true // } // var timestamp interface{} = this.SafeInteger2(trade, "T", "time") var amount interface{} = this.SafeString2(trade, "q", "qty") amount = this.SafeString(trade, "quantity", amount) var marketId interface{} = this.SafeString(trade, "symbol") var isSpotTrade interface{} = IsTrue(IsTrue(IsTrue((InOp(trade, "isIsolated"))) || IsTrue((InOp(trade, "M")))) || IsTrue((InOp(trade, "orderListId")))) || IsTrue((InOp(trade, "isMaker"))) var marketType interface{} = Ternary(IsTrue(isSpotTrade), "spot", "contract") market = this.SafeMarket(marketId, market, nil, marketType) var symbol interface{} = GetValue(market, "symbol") var side interface{} = nil var buyerMaker interface{} = this.SafeBool2(trade, "m", "isBuyerMaker") var takerOrMaker interface{} = nil if IsTrue(!IsEqual(buyerMaker, nil)) { side = Ternary(IsTrue(buyerMaker), "sell", "buy") // this is reversed intentionally } else if IsTrue(InOp(trade, "side")) { side = this.SafeStringLower(trade, "side") } else { if IsTrue(InOp(trade, "isBuyer")) { side = Ternary(IsTrue(GetValue(trade, "isBuyer")), "buy", "sell") // this is a true side } } var fee interface{} = nil if IsTrue(InOp(trade, "commission")) { fee = map[string]interface{} { "cost": this.SafeString(trade, "commission"), "currency": this.SafeCurrencyCode(this.SafeString(trade, "commissionAsset")), } } if IsTrue(InOp(trade, "isMaker")) { takerOrMaker = Ternary(IsTrue(GetValue(trade, "isMaker")), "maker", "taker") } if IsTrue(InOp(trade, "maker")) { takerOrMaker = Ternary(IsTrue(GetValue(trade, "maker")), "maker", "taker") } if IsTrue(IsTrue((InOp(trade, "optionSide"))) || IsTrue(GetValue(market, "option"))) { var settle interface{} = this.SafeCurrencyCode(this.SafeString(trade, "quoteAsset", "USDT")) takerOrMaker = this.SafeStringLower(trade, "liquidity") if IsTrue(InOp(trade, "fee")) { fee = map[string]interface{} { "cost": this.SafeString(trade, "fee"), "currency": settle, } } if IsTrue(IsTrue((!IsEqual(side, "buy"))) && IsTrue((!IsEqual(side, "sell")))) { side = Ternary(IsTrue((IsEqual(side, "1"))), "buy", "sell") } if IsTrue(InOp(trade, "optionSide")) { if IsTrue(!IsEqual(side, "buy")) { amount = Precise.StringMul("-1", amount) } } } return this.SafeTrade(map[string]interface{} { "info": trade, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "symbol": symbol, "id": this.SafeStringN(trade, []interface{}{"t", "a", "tradeId", "id"}), "order": this.SafeString(trade, "orderId"), "type": this.SafeStringLower(trade, "type"), "side": side, "takerOrMaker": takerOrMaker, "price": this.SafeString2(trade, "p", "price"), "amount": amount, "cost": this.SafeString2(trade, "quoteQty", "baseQty"), "fee": fee, }, market) } /** * @method * @name binance#fetchTrades * @description get the list of most recent trades for a particular symbol * Default fetchTradesMethod * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#compressedaggregate-trades-list // publicGetAggTrades (spot) * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Compressed-Aggregate-Trades-List // fapiPublicGetAggTrades (swap) * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Compressed-Aggregate-Trades-List // dapiPublicGetAggTrades (future) * @see https://developers.binance.com/docs/derivatives/option/market-data/Recent-Trades-List // eapiPublicGetTrades (option) * Other fetchTradesMethod * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#recent-trades-list // publicGetTrades (spot) * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Recent-Trades-List // fapiPublicGetTrades (swap) * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Recent-Trades-List // dapiPublicGetTrades (future) * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#old-trade-lookup // publicGetHistoricalTrades (spot) * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Old-Trades-Lookup // fapiPublicGetHistoricalTrades (swap) * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Old-Trades-Lookup // dapiPublicGetHistoricalTrades (future) * @see https://developers.binance.com/docs/derivatives/option/market-data/Old-Trades-Lookup // eapiPublicGetHistoricalTrades (option) * @param {string} symbol unified symbol of the market to fetch trades for * @param {int} [since] only used when fetchTradesMethod is 'publicGetAggTrades', 'fapiPublicGetAggTrades', or 'dapiPublicGetAggTrades' * @param {int} [limit] default 500, max 1000 * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.until] only used when fetchTradesMethod is 'publicGetAggTrades', 'fapiPublicGetAggTrades', or 'dapiPublicGetAggTrades' * @param {int} [params.fetchTradesMethod] 'publicGetAggTrades' (spot default), 'fapiPublicGetAggTrades' (swap default), 'dapiPublicGetAggTrades' (future default), 'eapiPublicGetTrades' (option default), 'publicGetTrades', 'fapiPublicGetTrades', 'dapiPublicGetTrades', 'publicGetHistoricalTrades', 'fapiPublicGetHistoricalTrades', 'dapiPublicGetHistoricalTrades', 'eapiPublicGetHistoricalTrades' * @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) * * EXCHANGE SPECIFIC PARAMETERS * @param {int} [params.fromId] trade id to fetch from, default gets most recent trades, not used when fetchTradesMethod is 'publicGetTrades', 'fapiPublicGetTrades', 'dapiPublicGetTrades', or 'eapiPublicGetTrades' * @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades} */ func (this *binance) 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 retRes51178 := (<-this.LoadMarkets()) PanicOnError(retRes51178) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchTrades", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes512119 := (<-this.FetchPaginatedCallDynamic("fetchTrades", symbol, since, limit, params)) PanicOnError(retRes512119) ch <- retRes512119 return nil } var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } if !IsTrue(GetValue(market, "option")) { if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) // https://github.com/ccxt/ccxt/issues/6400 // https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list AddElementToObject(request, "endTime", this.Sum(since, 3600000)) } var until interface{} = this.SafeInteger(params, "until") if IsTrue(!IsEqual(until, nil)) { AddElementToObject(request, "endTime", until) } } var method interface{} = this.SafeString(this.Options, "fetchTradesMethod") method = this.SafeString2(params, "fetchTradesMethod", "method", method) if IsTrue(!IsEqual(limit, nil)) { var isFutureOrSwap interface{} = (IsTrue(GetValue(market, "swap")) || IsTrue(GetValue(market, "future"))) var isHistoricalEndpoint interface{} = IsTrue((!IsEqual(method, nil))) && IsTrue((IsGreaterThanOrEqual(GetIndexOf(method, "GetHistoricalTrades"), 0))) var maxLimitForContractHistorical interface{} = Ternary(IsTrue(isHistoricalEndpoint), 500, 1000) AddElementToObject(request, "limit", Ternary(IsTrue(isFutureOrSwap), mathMin(limit, maxLimitForContractHistorical), limit)) // default = 500, maximum = 1000 } params = this.Omit(params, []interface{}{"until", "fetchTradesMethod"}) var response interface{} = nil if IsTrue(IsTrue(GetValue(market, "option")) || IsTrue(IsEqual(method, "eapiPublicGetTrades"))) { response = (<-this.EapiPublicGetTrades(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsTrue(GetValue(market, "linear")) || IsTrue(IsEqual(method, "fapiPublicGetAggTrades"))) { response = (<-this.FapiPublicGetAggTrades(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsTrue(GetValue(market, "inverse")) || IsTrue(IsEqual(method, "dapiPublicGetAggTrades"))) { response = (<-this.DapiPublicGetAggTrades(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PublicGetAggTrades(this.Extend(request, params))) PanicOnError(response) } // // Caveats: // - default limit (500) applies only if no other parameters set, trades up // to the maximum limit may be returned to satisfy other parameters // - if both limit and time window is set and time window contains more // trades than the limit then the last trades from the window are returned // - "tradeId" accepted and returned by this method is "aggregate" trade id // which is different from actual trade id // - setting both fromId and time window results in error // // aggregate trades // // [ // { // "a": 26129, // Aggregate tradeId // "p": "0.01633102", // Price // "q": "4.70443515", // Quantity // "f": 27781, // First tradeId // "l": 27781, // Last tradeId // "T": 1498793709153, // Timestamp // "m": true, // Was the buyer the maker? // "M": true // Was the trade the best price match? // } // ] // // inverse (swap & future) // // [ // { // "a": "269772814", // "p": "25864.1", // "q": "3", // "f": "662149354", // "l": "662149355", // "T": "1694209776022", // "m": false, // }, // ] // // recent public trades and historical public trades // // [ // { // "id": 28457, // "price": "4.00000100", // "qty": "12.00000000", // "time": 1499865549590, // "isBuyerMaker": true, // "isBestMatch": true // } // ] // // options (eapi) // // [ // { // "id": 1, // "symbol": "ETH-230216-1500-C", // "price": "35.5", // "qty": "0.03", // "quoteQty": "1.065", // "side": 1, // "time": 1676366446072 // }, // ] // ch <- this.ParseTrades(response, market, since, limit) return nil }() return ch } /** * @method * @name binance#editSpotOrder * @ignore * @description edit a trade order * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#cancel-an-existing-order-and-send-a-new-order-trade * @param {string} id cancel order id * @param {string} symbol unified symbol of the market to create an order in * @param {string} type 'market' or 'limit' or 'STOP_LOSS' or 'STOP_LOSS_LIMIT' or 'TAKE_PROFIT' or 'TAKE_PROFIT_LIMIT' or 'STOP' * @param {string} side 'buy' or 'sell' * @param {float} amount how much of currency you want to trade in units of base currency * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.marginMode] 'cross' or 'isolated', for spot margin trading * @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) EditSpotOrder(id interface{}, 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 retRes52488 := (<-this.LoadMarkets()) PanicOnError(retRes52488) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "spot")) { panic(NotSupported(Add(Add(Add(this.Id, " editSpotOrder() does not support "), GetValue(market, "type")), " orders"))) } var payload interface{} = this.EditSpotOrderRequest(id, symbol, typeVar, side, amount, price, params) response:= (<-this.PrivatePostOrderCancelReplace(payload)) PanicOnError(response) // // spot // // { // "cancelResult": "SUCCESS", // "newOrderResult": "SUCCESS", // "cancelResponse": { // "symbol": "BTCUSDT", // "origClientOrderId": "web_3f6286480b194b079870ac75fb6978b7", // "orderId": 16383156620, // "orderListId": -1, // "clientOrderId": "Azt6foVTTgHPNhqBf41TTt", // "price": "14000.00000000", // "origQty": "0.00110000", // "executedQty": "0.00000000", // "cummulativeQuoteQty": "0.00000000", // "status": "CANCELED", // "timeInForce": "GTC", // "type": "LIMIT", // "side": "BUY" // }, // "newOrderResponse": { // "symbol": "BTCUSDT", // "orderId": 16383176297, // "orderListId": -1, // "clientOrderId": "x-R4BD3S8222ecb58eb9074fb1be018c", // "transactTime": 1670891847932, // "price": "13500.00000000", // "origQty": "0.00085000", // "executedQty": "0.00000000", // "cummulativeQuoteQty": "0.00000000", // "status": "NEW", // "timeInForce": "GTC", // "type": "LIMIT", // "side": "BUY", // "fills": [] // } // } // var data interface{} = this.SafeDict(response, "newOrderResponse") ch <- this.ParseOrder(data, market) return nil }() return ch } func (this *binance) EditSpotOrderRequest(id interface{}, symbol interface{}, typeVar interface{}, side interface{}, amount interface{}, optionalArgs ...interface{}) interface{} { /** * @method * @ignore * @name binance#editSpotOrderRequest * @description helper function to build request for editSpotOrder * @param {string} id order id to be edited * @param {string} symbol unified symbol of the market to create an order in * @param {string} type 'market' or 'limit' or 'STOP_LOSS' or 'STOP_LOSS_LIMIT' or 'TAKE_PROFIT' or 'TAKE_PROFIT_LIMIT' or 'STOP' * @param {string} side 'buy' or 'sell' * @param {float} amount how much of currency you want to trade in units of base currency * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders * @param {object} params extra parameters specific to the exchange API endpoint * @param {string} [params.marginMode] 'cross' or 'isolated', for spot margin trading * @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 clientOrderId interface{} = this.SafeStringN(params, []interface{}{"newClientOrderId", "clientOrderId", "origClientOrderId"}) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), "side": ToUpper(side), } var initialUppercaseType interface{} = ToUpper(typeVar) var uppercaseType interface{} = initialUppercaseType var postOnly interface{} = this.IsPostOnly(IsEqual(initialUppercaseType, "MARKET"), IsEqual(initialUppercaseType, "LIMIT_MAKER"), params) if IsTrue(postOnly) { uppercaseType = "LIMIT_MAKER" } AddElementToObject(request, "type", uppercaseType) var triggerPrice interface{} = this.SafeNumber2(params, "stopPrice", "triggerPrice") if IsTrue(!IsEqual(triggerPrice, nil)) { if IsTrue(IsEqual(uppercaseType, "MARKET")) { uppercaseType = "STOP_LOSS" } else if IsTrue(IsEqual(uppercaseType, "LIMIT")) { uppercaseType = "STOP_LOSS_LIMIT" } } var validOrderTypes interface{} = this.SafeList(GetValue(market, "info"), "orderTypes") if !IsTrue(this.InArray(uppercaseType, validOrderTypes)) { if IsTrue(!IsEqual(initialUppercaseType, uppercaseType)) { panic(InvalidOrder(Add(Add(Add(Add(Add(this.Id, " triggerPrice parameter is not allowed for "), symbol), " "), typeVar), " orders"))) } else { panic(InvalidOrder(Add(Add(Add(Add(Add(this.Id, " "), typeVar), " is not a valid order type for the "), symbol), " market"))) } } if IsTrue(IsEqual(clientOrderId, nil)) { var broker interface{} = this.SafeDict(this.Options, "broker") if IsTrue(!IsEqual(broker, nil)) { var brokerId interface{} = this.SafeString(broker, "spot") if IsTrue(!IsEqual(brokerId, nil)) { AddElementToObject(request, "newClientOrderId", Add(brokerId, this.Uuid22())) } } } else { AddElementToObject(request, "newClientOrderId", clientOrderId) } AddElementToObject(request, "newOrderRespType", this.SafeValue(GetValue(this.Options, "newOrderRespType"), typeVar, "RESULT")) // 'ACK' for order id, 'RESULT' for full order or 'FULL' for order with fills var timeInForceIsRequired interface{} = false var priceIsRequired interface{} = false var triggerPriceIsRequired interface{} = false var quantityIsRequired interface{} = false if IsTrue(IsEqual(uppercaseType, "MARKET")) { var quoteOrderQty interface{} = this.SafeBool(this.Options, "quoteOrderQty", true) if IsTrue(quoteOrderQty) { var quoteOrderQtyNew interface{} = this.SafeValue2(params, "quoteOrderQty", "cost") var precision interface{} = GetValue(GetValue(market, "precision"), "price") if IsTrue(!IsEqual(quoteOrderQtyNew, nil)) { AddElementToObject(request, "quoteOrderQty", this.DecimalToPrecision(quoteOrderQtyNew, TRUNCATE, precision, this.PrecisionMode)) } else if IsTrue(!IsEqual(price, nil)) { var amountString interface{} = this.NumberToString(amount) var priceString interface{} = this.NumberToString(price) var quoteOrderQuantity interface{} = Precise.StringMul(amountString, priceString) AddElementToObject(request, "quoteOrderQty", this.DecimalToPrecision(quoteOrderQuantity, TRUNCATE, precision, this.PrecisionMode)) } else { quantityIsRequired = true } } else { quantityIsRequired = true } } else if IsTrue(IsEqual(uppercaseType, "LIMIT")) { priceIsRequired = true timeInForceIsRequired = true quantityIsRequired = true } else if IsTrue(IsTrue((IsEqual(uppercaseType, "STOP_LOSS"))) || IsTrue((IsEqual(uppercaseType, "TAKE_PROFIT")))) { triggerPriceIsRequired = true quantityIsRequired = true } else if IsTrue(IsTrue((IsEqual(uppercaseType, "STOP_LOSS_LIMIT"))) || IsTrue((IsEqual(uppercaseType, "TAKE_PROFIT_LIMIT")))) { quantityIsRequired = true triggerPriceIsRequired = true priceIsRequired = true timeInForceIsRequired = true } else if IsTrue(IsEqual(uppercaseType, "LIMIT_MAKER")) { priceIsRequired = true quantityIsRequired = true } if IsTrue(quantityIsRequired) { AddElementToObject(request, "quantity", this.AmountToPrecision(symbol, amount)) } if IsTrue(priceIsRequired) { if IsTrue(IsEqual(price, nil)) { panic(InvalidOrder(Add(Add(Add(this.Id, " editOrder() requires a price argument for a "), typeVar), " order"))) } AddElementToObject(request, "price", this.PriceToPrecision(symbol, price)) } if IsTrue(IsTrue(timeInForceIsRequired) && IsTrue((IsEqual(this.SafeString(params, "timeInForce"), nil)))) { AddElementToObject(request, "timeInForce", GetValue(this.Options, "defaultTimeInForce")) // 'GTC' = Good To Cancel (default), 'IOC' = Immediate Or Cancel } if IsTrue(triggerPriceIsRequired) { if IsTrue(IsEqual(triggerPrice, nil)) { panic(InvalidOrder(Add(Add(Add(this.Id, " editOrder() requires a triggerPrice extra param for a "), typeVar), " order"))) } else { AddElementToObject(request, "stopPrice", this.PriceToPrecision(symbol, triggerPrice)) } } AddElementToObject(request, "cancelReplaceMode", "STOP_ON_FAILURE") // If the cancel request fails, the new order placement will not be attempted. var cancelId interface{} = this.SafeString2(params, "cancelNewClientOrderId", "cancelOrigClientOrderId") if IsTrue(IsEqual(cancelId, nil)) { AddElementToObject(request, "cancelOrderId", id) // user can provide either cancelOrderId, cancelOrigClientOrderId or cancelOrigClientOrderId } // remove timeInForce from params because PO is only used by this.isPostOnly and it's not a valid value for Binance if IsTrue(IsEqual(this.SafeString(params, "timeInForce"), "PO")) { params = this.Omit(params, []interface{}{"timeInForce"}) } params = this.Omit(params, []interface{}{"quoteOrderQty", "cost", "stopPrice", "newClientOrderId", "clientOrderId", "postOnly"}) return this.Extend(request, params) } func (this *binance) EditContractOrderRequest(id interface{}, symbol interface{}, typeVar interface{}, side interface{}, amount interface{}, optionalArgs ...interface{}) interface{} { price := GetArg(optionalArgs, 0, nil) _ = price params := GetArg(optionalArgs, 1, map[string]interface{} {}) _ = params var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "contract")) { panic(NotSupported(Add(Add(Add(this.Id, " editContractOrder() does not support "), GetValue(market, "type")), " orders"))) } var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), "side": ToUpper(side), "orderId": id, "quantity": this.AmountToPrecision(symbol, amount), } var clientOrderId interface{} = this.SafeStringN(params, []interface{}{"newClientOrderId", "clientOrderId", "origClientOrderId"}) if IsTrue(!IsEqual(price, nil)) { AddElementToObject(request, "price", this.PriceToPrecision(symbol, price)) } if IsTrue(!IsEqual(clientOrderId, nil)) { AddElementToObject(request, "origClientOrderId", clientOrderId) } params = this.Omit(params, []interface{}{"clientOrderId", "newClientOrderId"}) return request } /** * @method * @name binance#editContractOrder * @description edit a trade order * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Order * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Modify-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Modify-UM-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Modify-CM-Order * @param {string} id cancel 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 currency you want to trade in units of base currency * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to edit an order in a portfolio margin account * @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) EditContractOrder(id interface{}, 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 retRes54668 := (<-this.LoadMarkets()) PanicOnError(retRes54668) var market interface{} = this.Market(symbol) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "editContractOrder", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) if IsTrue(IsTrue(GetValue(market, "linear")) || IsTrue(isPortfolioMargin)) { if IsTrue(IsTrue((IsEqual(price, nil))) && !IsTrue((InOp(params, "priceMatch")))) { panic(ArgumentsRequired(Add(this.Id, " editOrder() requires a price argument for portfolio margin and linear orders"))) } } var request interface{} = this.EditContractOrderRequest(id, symbol, typeVar, side, amount, price, params) var response interface{} = nil if IsTrue(GetValue(market, "linear")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiPutUmOrder(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPrivatePutOrder(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "inverse")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiPutCmOrder(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivatePutOrder(this.Extend(request, params))) PanicOnError(response) } } // // swap and future // // { // "orderId": 151007482392, // "symbol": "BTCUSDT", // "status": "NEW", // "clientOrderId": "web_pCCGp9AIHjziKLlpGpXI", // "price": "25000", // "avgPrice": "0.00000", // "origQty": "0.001", // "executedQty": "0", // "cumQty": "0", // "cumQuote": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "0", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "updateTime": 1684300587845 // } // ch <- this.ParseOrder(response, market) return nil }() return ch } /** * @method * @name binance#editOrder * @description edit a trade order * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#cancel-an-existing-order-and-send-a-new-order-trade * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Order * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Modify-Order * @param {string} id cancel 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 currency you want to trade in units of base currency * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 retRes55378 := (<-this.LoadMarkets()) PanicOnError(retRes55378) var market interface{} = this.Market(symbol) if IsTrue(GetValue(market, "option")) { panic(NotSupported(Add(Add(Add(this.Id, " editOrder() does not support "), GetValue(market, "type")), " orders"))) } if IsTrue(GetValue(market, "spot")) { retRes554319 := (<-this.EditSpotOrder(id, symbol, typeVar, side, amount, price, params)) PanicOnError(retRes554319) ch <- retRes554319 return nil } else { retRes554519 := (<-this.EditContractOrder(id, symbol, typeVar, side, amount, price, params)) PanicOnError(retRes554519) ch <- retRes554519 return nil } return nil }() return ch } /** * @method * @name binance#editOrders * @description edit a list of trade orders * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Multiple-Orders * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Modify-Multiple-Orders * @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) EditOrders(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 retRes55608 := (<-this.LoadMarkets()) PanicOnError(retRes55608) var ordersRequests interface{} = []interface{}{} var orderSymbols interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(orders)); i++ { var rawOrder interface{} = GetValue(orders, i) var marketId interface{} = this.SafeString(rawOrder, "symbol") AppendToArray(&orderSymbols,marketId) var id interface{} = this.SafeString(rawOrder, "id") var typeVar interface{} = this.SafeString(rawOrder, "type") var side interface{} = this.SafeString(rawOrder, "side") var amount interface{} = this.SafeValue(rawOrder, "amount") var price interface{} = this.SafeValue(rawOrder, "price") var orderParams interface{} = this.SafeDict(rawOrder, "params", map[string]interface{} {}) var isPortfolioMargin interface{} = nil isPortfolioMarginorderParamsVariable := this.HandleOptionAndParams2(orderParams, "editOrders", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginorderParamsVariable,0); orderParams = GetValue(isPortfolioMarginorderParamsVariable,1) if IsTrue(isPortfolioMargin) { panic(NotSupported(Add(this.Id, " editOrders() does not support portfolio margin orders"))) } var orderRequest interface{} = this.EditContractOrderRequest(id, marketId, typeVar, side, amount, price, orderParams) AppendToArray(&ordersRequests,orderRequest) } orderSymbols = this.MarketSymbols(orderSymbols, nil, false, true, true) var market interface{} = this.Market(GetValue(orderSymbols, 0)) if IsTrue(IsTrue(GetValue(market, "spot")) || IsTrue(GetValue(market, "option"))) { panic(NotSupported(Add(Add(Add(this.Id, " editOrders() does not support "), GetValue(market, "type")), " orders"))) } var response interface{} = nil var request interface{} = map[string]interface{} { "batchOrders": ordersRequests, } request = this.Extend(request, params) if IsTrue(GetValue(market, "linear")) { response = (<-this.FapiPrivatePutBatchOrders(request)) PanicOnError(response) } else if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPrivatePutBatchOrders(request)) PanicOnError(response) } // // [ // { // "code": -4005, // "msg": "Quantity greater than max quantity." // }, // { // "orderId": 650640530, // "symbol": "LTCUSDT", // "status": "NEW", // "clientOrderId": "x-xcKtGhcu32184eb13585491289bbaf", // "price": "54.00", // "avgPrice": "0.00", // "origQty": "0.100", // "executedQty": "0.000", // "cumQty": "0.000", // "cumQuote": "0.00000", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "0.00", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "priceMatch": "NONE", // "selfTradePreventionMode": "NONE", // "goodTillDate": 0, // "updateTime": 1698073926929 // } // ] // ch <- this.ParseOrders(response) return nil }() return ch } func (this *binance) ParseOrderStatus(status interface{}) interface{} { var statuses interface{} = map[string]interface{} { "NEW": "open", "PARTIALLY_FILLED": "open", "ACCEPTED": "open", "FILLED": "closed", "CANCELED": "canceled", "CANCELLED": "canceled", "PENDING_CANCEL": "canceling", "REJECTED": "rejected", "EXPIRED": "expired", "EXPIRED_IN_MATCH": "expired", } return this.SafeString(statuses, status, status) } func (this *binance) ParseOrder(order interface{}, optionalArgs ...interface{}) interface{} { // // spot // // { // "symbol": "LTCBTC", // "orderId": 1, // "clientOrderId": "myOrder1", // "price": "0.1", // "origQty": "1.0", // "executedQty": "0.0", // "cummulativeQuoteQty": "0.0", // "status": "NEW", // "timeInForce": "GTC", // "type": "LIMIT", // "side": "BUY", // "stopPrice": "0.0", // "icebergQty": "0.0", // "time": 1499827319559, // "updateTime": 1499827319559, // "isWorking": true // } // // spot: editOrder // // { // "symbol": "BTCUSDT", // "orderId": 16383176297, // "orderListId": -1, // "clientOrderId": "x-R4BD3S8222ecb58eb9074fb1be018c", // "transactTime": 1670891847932, // "price": "13500.00000000", // "origQty": "0.00085000", // "executedQty": "0.00000000", // "cummulativeQuoteQty": "0.00000000", // "status": "NEW", // "timeInForce": "GTC", // "type": "LIMIT", // "side": "BUY", // "fills": [] // } // // swap and future: editOrder // // { // "orderId": 151007482392, // "symbol": "BTCUSDT", // "status": "NEW", // "clientOrderId": "web_pCCGp9AIHjziKLlpGpXI", // "price": "25000", // "avgPrice": "0.00000", // "origQty": "0.001", // "executedQty": "0", // "cumQty": "0", // "cumQuote": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "0", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "updateTime": 1684300587845 // } // // futures // // { // "symbol": "BTCUSDT", // "orderId": 1, // "clientOrderId": "myOrder1", // "price": "0.1", // "origQty": "1.0", // "executedQty": "1.0", // "cumQuote": "10.0", // "status": "NEW", // "timeInForce": "GTC", // "type": "LIMIT", // "side": "BUY", // "stopPrice": "0.0", // "updateTime": 1499827319559 // } // // createOrder with { "newOrderRespType": "FULL" } // // { // "symbol": "BTCUSDT", // "orderId": 5403233939, // "orderListId": -1, // "clientOrderId": "x-R4BD3S825e669e75b6c14f69a2c43e", // "transactTime": 1617151923742, // "price": "0.00000000", // "origQty": "0.00050000", // "executedQty": "0.00050000", // "cummulativeQuoteQty": "29.47081500", // "status": "FILLED", // "timeInForce": "GTC", // "type": "MARKET", // "side": "BUY", // "fills": [ // { // "price": "58941.63000000", // "qty": "0.00050000", // "commission": "0.00007050", // "commissionAsset": "BNB", // "tradeId": 737466631 // } // ] // } // // delivery // // { // "orderId": "18742727411", // "symbol": "ETHUSD_PERP", // "pair": "ETHUSD", // "status": "FILLED", // "clientOrderId": "x-xcKtGhcu3e2d1503fdd543b3b02419", // "price": "0", // "avgPrice": "4522.14", // "origQty": "1", // "executedQty": "1", // "cumBase": "0.00221134", // "timeInForce": "GTC", // "type": "MARKET", // "reduceOnly": false, // "closePosition": false, // "side": "SELL", // "positionSide": "BOTH", // "stopPrice": "0", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "MARKET", // "time": "1636061952660", // "updateTime": "1636061952660" // } // // option: createOrder, fetchOrder, fetchOpenOrders, fetchOrders // // { // "orderId": 4728833085436977152, // "symbol": "ETH-230211-1500-C", // "price": "10.0", // "quantity": "1.00", // "executedQty": "0.00", // "fee": "0", // "side": "BUY", // "type": "LIMIT", // "timeInForce": "GTC", // "reduceOnly": false, // "postOnly": false, // "createTime": 1676083034462, // "updateTime": 1676083034462, // "status": "ACCEPTED", // "avgPrice": "0", // "source": "API", // "clientOrderId": "", // "priceScale": 1, // "quantityScale": 2, // "optionSide": "CALL", // "quoteAsset": "USDT", // "lastTrade": {"id":"69","time":"1676084430567","price":"24.9","qty":"1.00"}, // "mmp": false // } // // cancelOrders/createOrders // // { // "code": -4005, // "msg": "Quantity greater than max quantity." // } // // createOrder, fetchOpenOrders, fetchOrder, cancelOrder, fetchOrders: portfolio margin linear swap and future // // { // "symbol": "BTCUSDT", // "side": "BUY", // "executedQty": "0.000", // "orderId": 258649539704, // "goodTillDate": 0, // "avgPrice": "0", // "origQty": "0.010", // "clientOrderId": "x-xcKtGhcu02573c6f15e544e990057b", // "positionSide": "BOTH", // "cumQty": "0.000", // "updateTime": 1707110415436, // "type": "LIMIT", // "reduceOnly": false, // "price": "35000.00", // "cumQuote": "0.00000", // "selfTradePreventionMode": "NONE", // "timeInForce": "GTC", // "status": "NEW" // } // // createOrder, fetchOpenOrders, fetchOrder, cancelOrder, fetchOrders: portfolio margin inverse swap and future // // { // "symbol": "ETHUSD_PERP", // "side": "BUY", // "cumBase": "0", // "executedQty": "0", // "orderId": 71275227732, // "avgPrice": "0.00", // "origQty": "1", // "clientOrderId": "x-xcKtGhcuca5af3acfb5044198c5398", // "positionSide": "BOTH", // "cumQty": "0", // "updateTime": 1707110994334, // "type": "LIMIT", // "pair": "ETHUSD", // "reduceOnly": false, // "price": "2000", // "timeInForce": "GTC", // "status": "NEW" // } // // createOrder, fetchOpenOrders, fetchOpenOrder: portfolio margin linear swap and future conditional // // { // "newClientStrategyId": "x-xcKtGhcu27f109953d6e4dc0974006", // "strategyId": 3645916, // "strategyStatus": "NEW", // "strategyType": "STOP", // "origQty": "0.010", // "price": "35000.00", // "reduceOnly": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "45000.00", // "symbol": "BTCUSDT", // "timeInForce": "GTC", // "bookTime": 1707112625879, // "updateTime": 1707112625879, // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "goodTillDate": 0, // "selfTradePreventionMode": "NONE" // } // // createOrder, fetchOpenOrders: portfolio margin inverse swap and future conditional // // { // "newClientStrategyId": "x-xcKtGhcuc6b86f053bb34933850739", // "strategyId": 1423462, // "strategyStatus": "NEW", // "strategyType": "STOP", // "origQty": "1", // "price": "2000", // "reduceOnly": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "3000", // "symbol": "ETHUSD_PERP", // "timeInForce": "GTC", // "bookTime": 1707113098840, // "updateTime": 1707113098840, // "workingType": "CONTRACT_PRICE", // "priceProtect": false // } // // createOrder, cancelAllOrders, cancelOrder: portfolio margin spot margin // // { // "clientOrderId": "x-R4BD3S82e9ef29d8346440f0b28b86", // "cummulativeQuoteQty": "0.00000000", // "executedQty": "0.00000000", // "fills": [], // "orderId": 24684460474, // "origQty": "0.00100000", // "price": "35000.00000000", // "selfTradePreventionMode": "EXPIRE_MAKER", // "side": "BUY", // "status": "NEW", // "symbol": "BTCUSDT", // "timeInForce": "GTC", // "transactTime": 1707113538870, // "type": "LIMIT" // } // // fetchOpenOrders, fetchOrder, fetchOrders: portfolio margin spot margin // // { // "symbol": "BTCUSDT", // "orderId": 24700763749, // "clientOrderId": "x-R4BD3S826f724c2a4af6425f98c7b6", // "price": "35000.00000000", // "origQty": "0.00100000", // "executedQty": "0.00000000", // "cummulativeQuoteQty": "0.00000000", // "status": "NEW", // "timeInForce": "GTC", // "type": "LIMIT", // "side": "BUY", // "stopPrice": "0.00000000", // "icebergQty": "0.00000000", // "time": 1707199187679, // "updateTime": 1707199187679, // "isWorking": true, // "accountId": 200180970, // "selfTradePreventionMode": "EXPIRE_MAKER", // "preventedMatchId": null, // "preventedQuantity": null // } // // cancelOrder: portfolio margin linear and inverse swap conditional // // { // "strategyId": 3733211, // "newClientStrategyId": "x-xcKtGhcuaf166172ed504cd1bc0396", // "strategyType": "STOP", // "strategyStatus": "CANCELED", // "origQty": "0.010", // "price": "35000.00", // "reduceOnly": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "50000.00", // ignored with trailing orders // "symbol": "BTCUSDT", // "timeInForce": "GTC", // "activatePrice": null, // only return with trailing orders // "priceRate": null, // only return with trailing orders // "bookTime": 1707270098774, // "updateTime": 1707270119261, // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "goodTillDate": 0, // "selfTradePreventionMode": "NONE" // } // // fetchOrders: portfolio margin linear and inverse swap conditional // // { // "newClientStrategyId": "x-xcKtGhcuaf166172ed504cd1bc0396", // "strategyId": 3733211, // "strategyStatus": "CANCELLED", // "strategyType": "STOP", // "origQty": "0.010", // "price": "35000", // "orderId": 0, // "reduceOnly": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "50000", // "symbol": "BTCUSDT", // "type": "LIMIT", // "bookTime": 1707270098774, // "updateTime": 1707270119261, // "timeInForce": "GTC", // "triggerTime": 0, // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "goodTillDate": 0, // "selfTradePreventionMode": "NONE" // } // // fetchOpenOrder: linear swap // // { // "orderId": 3697213934, // "symbol": "BTCUSDT", // "status": "NEW", // "clientOrderId": "x-xcKtGhcufb20c5a7761a4aa09aa156", // "price": "33000.00", // "avgPrice": "0.00000", // "origQty": "0.010", // "executedQty": "0.000", // "cumQuote": "0.00000", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "0.00", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "priceMatch": "NONE", // "selfTradePreventionMode": "NONE", // "goodTillDate": 0, // "time": 1707892893502, // "updateTime": 1707892893515 // } // // fetchOpenOrder: inverse swap // // { // "orderId": 597368542, // "symbol": "BTCUSD_PERP", // "pair": "BTCUSD", // "status": "NEW", // "clientOrderId": "x-xcKtGhcubbde7ba93b1a4ab881eff3", // "price": "35000", // "avgPrice": "0", // "origQty": "1", // "executedQty": "0", // "cumBase": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "0", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "time": 1707893453199, // "updateTime": 1707893453199 // } // // fetchOpenOrder: linear portfolio margin // // { // "orderId": 264895013409, // "symbol": "BTCUSDT", // "status": "NEW", // "clientOrderId": "x-xcKtGhcu6278f1adbdf14f74ab432e", // "price": "35000", // "avgPrice": "0", // "origQty": "0.010", // "executedQty": "0", // "cumQuote": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "side": "BUY", // "positionSide": "LONG", // "origType": "LIMIT", // "time": 1707893839364, // "updateTime": 1707893839364, // "goodTillDate": 0, // "selfTradePreventionMode": "NONE" // } // // fetchOpenOrder: inverse portfolio margin // // { // "orderId": 71790316950, // "symbol": "ETHUSD_PERP", // "pair": "ETHUSD", // "status": "NEW", // "clientOrderId": "x-xcKtGhcuec11030474204ab08ba2c2", // "price": "2500", // "avgPrice": "0", // "origQty": "1", // "executedQty": "0", // "cumBase": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "side": "BUY", // "positionSide": "LONG", // "origType": "LIMIT", // "time": 1707894181694, // "updateTime": 1707894181694 // } // // fetchOpenOrder: inverse portfolio margin conditional // // { // "newClientStrategyId": "x-xcKtGhcu2da9c765294b433994ffce", // "strategyId": 1423501, // "strategyStatus": "NEW", // "strategyType": "STOP", // "origQty": "1", // "price": "2500", // "reduceOnly": false, // "side": "BUY", // "positionSide": "LONG", // "stopPrice": "4000", // "symbol": "ETHUSD_PERP", // "bookTime": 1707894782679, // "updateTime": 1707894782679, // "timeInForce": "GTC", // "workingType": "CONTRACT_PRICE", // "priceProtect": false // } // market := GetArg(optionalArgs, 0, nil) _ = market var code interface{} = this.SafeString(order, "code") if IsTrue(!IsEqual(code, nil)) { // cancelOrders/createOrders might have a partial success return this.SafeOrder(map[string]interface{} { "info": order, "status": "rejected", }, market) } var status interface{} = this.ParseOrderStatus(this.SafeString2(order, "status", "strategyStatus")) var marketId interface{} = this.SafeString(order, "symbol") var isContract interface{} = IsTrue((InOp(order, "positionSide"))) || IsTrue((InOp(order, "cumQuote"))) var marketType interface{} = Ternary(IsTrue(isContract), "contract", "spot") var symbol interface{} = this.SafeSymbol(marketId, market, nil, marketType) var filled interface{} = this.SafeString(order, "executedQty", "0") var timestamp interface{} = this.SafeIntegerN(order, []interface{}{"time", "createTime", "workingTime", "transactTime", "updateTime"}) // order of the keys matters here var lastTradeTimestamp interface{} = nil if IsTrue(IsTrue((InOp(order, "transactTime"))) || IsTrue((InOp(order, "updateTime")))) { var timestampValue interface{} = this.SafeInteger2(order, "updateTime", "transactTime") if IsTrue(IsEqual(status, "open")) { if IsTrue(Precise.StringGt(filled, "0")) { lastTradeTimestamp = timestampValue } } else if IsTrue(IsEqual(status, "closed")) { lastTradeTimestamp = timestampValue } } var lastUpdateTimestamp interface{} = this.SafeInteger2(order, "transactTime", "updateTime") var average interface{} = this.SafeString(order, "avgPrice") var price interface{} = this.SafeString(order, "price") var amount interface{} = this.SafeString2(order, "origQty", "quantity") // - Spot/Margin market: cummulativeQuoteQty // - Futures market: cumQuote. // Note this is not the actual cost, since Binance futures uses leverage to calculate margins. var cost interface{} = this.SafeString2(order, "cummulativeQuoteQty", "cumQuote") cost = this.SafeString(order, "cumBase", cost) var typeVar interface{} = this.SafeStringLower(order, "type") var side interface{} = this.SafeStringLower(order, "side") var fills interface{} = this.SafeList(order, "fills", []interface{}{}) var timeInForce interface{} = this.SafeString(order, "timeInForce") if IsTrue(IsEqual(timeInForce, "GTX")) { // GTX means "Good Till Crossing" and is an equivalent way of saying Post Only timeInForce = "PO" } var postOnly interface{} = IsTrue((IsEqual(typeVar, "limit_maker"))) || IsTrue((IsEqual(timeInForce, "PO"))) if IsTrue(IsEqual(typeVar, "limit_maker")) { typeVar = "limit" } var stopPriceString interface{} = this.SafeString(order, "stopPrice") var triggerPrice interface{} = this.ParseNumber(this.OmitZero(stopPriceString)) var feeCost interface{} = this.SafeNumber(order, "fee") var fee interface{} = nil if IsTrue(!IsEqual(feeCost, nil)) { fee = map[string]interface{} { "currency": this.SafeString(order, "quoteAsset"), "cost": feeCost, "rate": nil, } } return this.SafeOrder(map[string]interface{} { "info": order, "id": this.SafeString2(order, "strategyId", "orderId"), "clientOrderId": this.SafeString2(order, "clientOrderId", "newClientStrategyId"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "lastTradeTimestamp": lastTradeTimestamp, "lastUpdateTimestamp": lastUpdateTimestamp, "symbol": symbol, "type": typeVar, "timeInForce": timeInForce, "postOnly": postOnly, "reduceOnly": this.SafeBool(order, "reduceOnly"), "side": side, "price": price, "triggerPrice": triggerPrice, "amount": amount, "cost": cost, "average": average, "filled": filled, "remaining": nil, "status": status, "fee": fee, "trades": fills, }, market) } /** * @method * @name binance#createOrders * @description *contract only* create a list of trade orders * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Place-Multiple-Orders * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Place-Multiple-Orders * @see https://developers.binance.com/docs/derivatives/option/trade/Place-Multiple-Orders * @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 retRes62268 := (<-this.LoadMarkets()) PanicOnError(retRes62268) var ordersRequests interface{} = []interface{}{} var orderSymbols interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(orders)); i++ { var rawOrder interface{} = GetValue(orders, i) var marketId interface{} = this.SafeString(rawOrder, "symbol") AppendToArray(&orderSymbols,marketId) var typeVar interface{} = this.SafeString(rawOrder, "type") var side interface{} = this.SafeString(rawOrder, "side") var amount interface{} = this.SafeValue(rawOrder, "amount") var price interface{} = this.SafeValue(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) } orderSymbols = this.MarketSymbols(orderSymbols, nil, false, true, true) var market interface{} = this.Market(GetValue(orderSymbols, 0)) if IsTrue(GetValue(market, "spot")) { panic(NotSupported(Add(Add(Add(this.Id, " createOrders() does not support "), GetValue(market, "type")), " orders"))) } var response interface{} = nil var request interface{} = map[string]interface{} { "batchOrders": ordersRequests, } request = this.Extend(request, params) if IsTrue(GetValue(market, "linear")) { response = (<-this.FapiPrivatePostBatchOrders(request)) PanicOnError(response) } else if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPrivatePostBatchOrders(request)) PanicOnError(response) } else { response = (<-this.DapiPrivatePostBatchOrders(request)) PanicOnError(response) } // // [ // { // "code": -4005, // "msg": "Quantity greater than max quantity." // }, // { // "orderId": 650640530, // "symbol": "LTCUSDT", // "status": "NEW", // "clientOrderId": "x-xcKtGhcu32184eb13585491289bbaf", // "price": "54.00", // "avgPrice": "0.00", // "origQty": "0.100", // "executedQty": "0.000", // "cumQty": "0.000", // "cumQuote": "0.00000", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "0.00", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "priceMatch": "NONE", // "selfTradePreventionMode": "NONE", // "goodTillDate": 0, // "updateTime": 1698073926929 // } // ] // ch <- this.ParseOrders(response) return nil }() return ch } /** * @method * @name binance#createOrder * @description create a trade order * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/public-api-endpoints#test-new-order-trade * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Order * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/New-Order * @see https://developers.binance.com/docs/derivatives/option/trade/New-Order * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#sor * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#test-new-order-using-sor-trade * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-UM-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-CM-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-Margin-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-UM-Conditional-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-CM-Conditional-Order * @param {string} symbol unified symbol of the market to create an order in * @param {string} type 'market' or 'limit' or 'STOP_LOSS' or 'STOP_LOSS_LIMIT' or 'TAKE_PROFIT' or 'TAKE_PROFIT_LIMIT' or 'STOP' * @param {string} side 'buy' or 'sell' * @param {float} amount how much of you want to trade in units of the base currency * @param {float} [price] the price that 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.reduceOnly] for swap and future reduceOnly is a string 'true' or 'false' that cant be sent with close position set to true or in hedge mode. For spot margin and option reduceOnly is a boolean. * @param {string} [params.marginMode] 'cross' or 'isolated', for spot margin trading * @param {boolean} [params.sor] *spot only* whether to use SOR (Smart Order Routing) or not, default is false * @param {boolean} [params.test] *spot only* whether to use the test endpoint or not, default is false * @param {float} [params.trailingPercent] the percent to trail away from the current market price * @param {float} [params.trailingTriggerPrice] the price to trigger a trailing order, default uses the price argument * @param {float} [params.triggerPrice] the price that a trigger order is triggered at * @param {float} [params.stopLossPrice] the price that a stop loss order is triggered at * @param {float} [params.takeProfitPrice] the price that a take profit order is triggered at * @param {boolean} [params.portfolioMargin] set to true if you would like to create an order in a portfolio margin account * @param {string} [params.selfTradePrevention] set unified value for stp (see .features for available values) * @param {float} [params.icebergAmount] set iceberg amount for limit orders * @param {string} [params.stopLossOrTakeProfit] 'stopLoss' or 'takeProfit', required for spot trailing orders * @param {string} [params.positionSide] *swap and portfolio margin only* "BOTH" for one-way mode, "LONG" for buy side of hedged mode, "SHORT" for sell side of hedged mode * @param {bool} [params.hedged] *swap and portfolio margin only* true for hedged mode, false for one way mode, default is false * @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 retRes63358 := (<-this.LoadMarkets()) PanicOnError(retRes63358) var market interface{} = this.Market(symbol) var marketType interface{} = this.SafeString(params, "type", GetValue(market, "type")) var marginMode interface{} = nil marginModeparamsVariable := this.HandleMarginModeAndParams("createOrder", params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "createOrder", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var triggerPrice interface{} = this.SafeString2(params, "triggerPrice", "stopPrice") var stopLossPrice interface{} = this.SafeString(params, "stopLossPrice") var takeProfitPrice interface{} = this.SafeString(params, "takeProfitPrice") var trailingPercent interface{} = this.SafeString2(params, "trailingPercent", "callbackRate") var isTrailingPercentOrder interface{} = !IsEqual(trailingPercent, nil) var isStopLoss interface{} = !IsEqual(stopLossPrice, nil) var isTakeProfit interface{} = !IsEqual(takeProfitPrice, nil) var isConditional interface{} = IsTrue(IsTrue(IsTrue((!IsEqual(triggerPrice, nil))) || IsTrue(isTrailingPercentOrder)) || IsTrue(isStopLoss)) || IsTrue(isTakeProfit) var sor interface{} = this.SafeBool2(params, "sor", "SOR", false) var test interface{} = this.SafeBool(params, "test", false) params = this.Omit(params, []interface{}{"sor", "SOR", "test"}) if IsTrue(isPortfolioMargin) { AddElementToObject(params, "portfolioMargin", isPortfolioMargin) } var request interface{} = this.CreateOrderRequest(symbol, typeVar, side, amount, price, params) var response interface{} = nil if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPrivatePostOrder(request)) PanicOnError(response) } else if IsTrue(sor) { if IsTrue(test) { response = (<-this.PrivatePostSorOrderTest(request)) PanicOnError(response) } else { response = (<-this.PrivatePostSorOrder(request)) PanicOnError(response) } } else if IsTrue(GetValue(market, "linear")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiPostUmConditionalOrder(request)) PanicOnError(response) } else { response = (<-this.PapiPostUmOrder(request)) PanicOnError(response) } } else { response = (<-this.FapiPrivatePostOrder(request)) PanicOnError(response) } } else if IsTrue(GetValue(market, "inverse")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiPostCmConditionalOrder(request)) PanicOnError(response) } else { response = (<-this.PapiPostCmOrder(request)) PanicOnError(response) } } else { response = (<-this.DapiPrivatePostOrder(request)) PanicOnError(response) } } else if IsTrue(IsTrue(IsTrue(IsEqual(marketType, "margin")) || IsTrue(!IsEqual(marginMode, nil))) || IsTrue(isPortfolioMargin)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiPostMarginOrder(request)) PanicOnError(response) } else { response = (<-this.SapiPostMarginOrder(request)) PanicOnError(response) } } else { if IsTrue(test) { response = (<-this.PrivatePostOrderTest(request)) PanicOnError(response) } else { response = (<-this.PrivatePostOrder(request)) PanicOnError(response) } } ch <- this.ParseOrder(response, market) return nil }() return ch } func (this *binance) CreateOrderRequest(symbol interface{}, typeVar interface{}, side interface{}, amount interface{}, optionalArgs ...interface{}) interface{} { /** * @method * @ignore * @name binance#createOrderRequest * @description helper function to build the 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 that 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 marketType interface{} = this.SafeString(params, "type", GetValue(market, "type")) var clientOrderId interface{} = this.SafeString2(params, "newClientOrderId", "clientOrderId") var initialUppercaseType interface{} = ToUpper(typeVar) var isMarketOrder interface{} = IsEqual(initialUppercaseType, "MARKET") var isLimitOrder interface{} = IsEqual(initialUppercaseType, "LIMIT") var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), "side": ToUpper(side), } var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "createOrder", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var marginMode interface{} = nil marginModeparamsVariable := this.HandleMarginModeAndParams("createOrder", params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) var reduceOnly interface{} = this.SafeBool(params, "reduceOnly", false) if IsTrue(reduceOnly) { if IsTrue(IsTrue(IsEqual(marketType, "margin")) || IsTrue((!IsTrue(GetValue(market, "contract")) && IsTrue((!IsEqual(marginMode, nil)))))) { params = this.Omit(params, "reduceOnly") AddElementToObject(request, "sideEffectType", "AUTO_REPAY") } } var triggerPrice interface{} = this.SafeString2(params, "triggerPrice", "stopPrice") var stopLossPrice interface{} = this.SafeString(params, "stopLossPrice", triggerPrice) // fallback to stopLoss var takeProfitPrice interface{} = this.SafeString(params, "takeProfitPrice") var trailingDelta interface{} = this.SafeString(params, "trailingDelta") var trailingTriggerPrice interface{} = this.SafeString2(params, "trailingTriggerPrice", "activationPrice") var trailingPercent interface{} = this.SafeStringN(params, []interface{}{"trailingPercent", "callbackRate", "trailingDelta"}) var priceMatch interface{} = this.SafeString(params, "priceMatch") var isTrailingPercentOrder interface{} = !IsEqual(trailingPercent, nil) var isStopLoss interface{} = IsTrue(!IsEqual(stopLossPrice, nil)) || IsTrue(!IsEqual(trailingDelta, nil)) var isTakeProfit interface{} = !IsEqual(takeProfitPrice, nil) var isTriggerOrder interface{} = !IsEqual(triggerPrice, nil) var isConditional interface{} = IsTrue(IsTrue(IsTrue(isTriggerOrder) || IsTrue(isTrailingPercentOrder)) || IsTrue(isStopLoss)) || IsTrue(isTakeProfit) var isPortfolioMarginConditional interface{} = (IsTrue(isPortfolioMargin) && IsTrue(isConditional)) var isPriceMatch interface{} = !IsEqual(priceMatch, nil) var uppercaseType interface{} = ToUpper(typeVar) var stopPrice interface{} = nil if IsTrue(isTrailingPercentOrder) { if IsTrue(GetValue(market, "swap")) { uppercaseType = "TRAILING_STOP_MARKET" AddElementToObject(request, "callbackRate", trailingPercent) if IsTrue(!IsEqual(trailingTriggerPrice, nil)) { AddElementToObject(request, "activationPrice", this.PriceToPrecision(symbol, trailingTriggerPrice)) } } else { if IsTrue(isMarketOrder) { panic(InvalidOrder(Add(Add(Add(Add(Add(this.Id, " trailingPercent orders are not supported for "), symbol), " "), typeVar), " orders"))) } var stopLossOrTakeProfit interface{} = this.SafeString(params, "stopLossOrTakeProfit") params = this.Omit(params, "stopLossOrTakeProfit") if IsTrue(IsTrue(!IsEqual(stopLossOrTakeProfit, "stopLoss")) && IsTrue(!IsEqual(stopLossOrTakeProfit, "takeProfit"))) { panic(InvalidOrder(Add(Add(this.Id, symbol), " trailingPercent orders require a stopLossOrTakeProfit parameter of either stopLoss or takeProfit"))) } if IsTrue(IsEqual(stopLossOrTakeProfit, "stopLoss")) { uppercaseType = "STOP_LOSS_LIMIT" } else if IsTrue(IsEqual(stopLossOrTakeProfit, "takeProfit")) { uppercaseType = "TAKE_PROFIT_LIMIT" } if IsTrue(!IsEqual(trailingTriggerPrice, nil)) { stopPrice = this.PriceToPrecision(symbol, trailingTriggerPrice) } var trailingPercentConverted interface{} = Precise.StringMul(trailingPercent, "100") AddElementToObject(request, "trailingDelta", trailingPercentConverted) } } else if IsTrue(isStopLoss) { stopPrice = stopLossPrice if IsTrue(isMarketOrder) { // spot STOP_LOSS market orders are not a valid order type uppercaseType = Ternary(IsTrue(GetValue(market, "contract")), "STOP_MARKET", "STOP_LOSS") } else if IsTrue(isLimitOrder) { uppercaseType = Ternary(IsTrue(GetValue(market, "contract")), "STOP", "STOP_LOSS_LIMIT") } } else if IsTrue(isTakeProfit) { stopPrice = takeProfitPrice if IsTrue(isMarketOrder) { // spot TAKE_PROFIT market orders are not a valid order type uppercaseType = Ternary(IsTrue(GetValue(market, "contract")), "TAKE_PROFIT_MARKET", "TAKE_PROFIT") } else if IsTrue(isLimitOrder) { uppercaseType = Ternary(IsTrue(GetValue(market, "contract")), "TAKE_PROFIT", "TAKE_PROFIT_LIMIT") } } if IsTrue(GetValue(market, "option")) { if IsTrue(IsEqual(typeVar, "market")) { panic(InvalidOrder(Add(Add(Add(Add(Add(this.Id, " "), typeVar), " is not a valid order type for the "), symbol), " market"))) } } else { var validOrderTypes interface{} = this.SafeList(GetValue(market, "info"), "orderTypes") if !IsTrue(this.InArray(uppercaseType, validOrderTypes)) { if IsTrue(!IsEqual(initialUppercaseType, uppercaseType)) { panic(InvalidOrder(Add(Add(Add(Add(Add(this.Id, " triggerPrice parameter is not allowed for "), symbol), " "), typeVar), " orders"))) } else { panic(InvalidOrder(Add(Add(Add(Add(Add(this.Id, " "), typeVar), " is not a valid order type for the "), symbol), " market"))) } } } var clientOrderIdRequest interface{} = Ternary(IsTrue(isPortfolioMarginConditional), "newClientStrategyId", "newClientOrderId") if IsTrue(IsEqual(clientOrderId, nil)) { var broker interface{} = this.SafeDict(this.Options, "broker", map[string]interface{} {}) var defaultId interface{} = Ternary(IsTrue((GetValue(market, "contract"))), "x-xcKtGhcu", "x-R4BD3S82") var brokerId interface{} = this.SafeString(broker, marketType, defaultId) AddElementToObject(request, clientOrderIdRequest, Add(brokerId, this.Uuid22())) } else { AddElementToObject(request, clientOrderIdRequest, clientOrderId) } var postOnly interface{} = nil if !IsTrue(isPortfolioMargin) { postOnly = this.IsPostOnly(isMarketOrder, IsEqual(initialUppercaseType, "LIMIT_MAKER"), params) if IsTrue(IsTrue(GetValue(market, "spot")) || IsTrue(IsEqual(marketType, "margin"))) { // only supported for spot/margin api (all margin markets are spot markets) if IsTrue(postOnly) { uppercaseType = "LIMIT_MAKER" } if IsTrue(IsEqual(marginMode, "isolated")) { AddElementToObject(request, "isIsolated", true) } } } else { postOnly = this.IsPostOnly(isMarketOrder, IsEqual(initialUppercaseType, "LIMIT_MAKER"), params) if IsTrue(postOnly) { if !IsTrue(GetValue(market, "contract")) { uppercaseType = "LIMIT_MAKER" } else { AddElementToObject(request, "timeInForce", "GTX") } } } // handle newOrderRespType response type if IsTrue(IsTrue((IsTrue((IsEqual(marketType, "spot"))) || IsTrue((IsEqual(marketType, "margin"))))) && !IsTrue(isPortfolioMargin)) { AddElementToObject(request, "newOrderRespType", this.SafeString(GetValue(this.Options, "newOrderRespType"), typeVar, "FULL")) // 'ACK' for order id, 'RESULT' for full order or 'FULL' for order with fills } else { // swap, futures and options AddElementToObject(request, "newOrderRespType", "RESULT") // "ACK", "RESULT", default "ACK" } var typeRequest interface{} = Ternary(IsTrue(isPortfolioMarginConditional), "strategyType", "type") AddElementToObject(request, typeRequest, uppercaseType) // additional required fields depending on the order type var closePosition interface{} = this.SafeBool(params, "closePosition", false) var timeInForceIsRequired interface{} = false var priceIsRequired interface{} = false var triggerPriceIsRequired interface{} = false var quantityIsRequired interface{} = false // // spot/margin // // LIMIT timeInForce, quantity, price // MARKET quantity or quoteOrderQty // STOP_LOSS quantity, stopPrice // STOP_LOSS_LIMIT timeInForce, quantity, price, stopPrice // TAKE_PROFIT quantity, stopPrice // TAKE_PROFIT_LIMIT timeInForce, quantity, price, stopPrice // LIMIT_MAKER quantity, price // // futures // // LIMIT timeInForce, quantity, price // MARKET quantity // STOP/TAKE_PROFIT quantity, price, stopPrice // STOP_MARKET stopPrice // TAKE_PROFIT_MARKET stopPrice // TRAILING_STOP_MARKET callbackRate // if IsTrue(IsEqual(uppercaseType, "MARKET")) { if IsTrue(GetValue(market, "spot")) { var quoteOrderQty interface{} = this.SafeBool(this.Options, "quoteOrderQty", true) if IsTrue(quoteOrderQty) { var quoteOrderQtyNew interface{} = this.SafeString2(params, "quoteOrderQty", "cost") var precision interface{} = GetValue(GetValue(market, "precision"), "price") if IsTrue(!IsEqual(quoteOrderQtyNew, nil)) { AddElementToObject(request, "quoteOrderQty", this.DecimalToPrecision(quoteOrderQtyNew, TRUNCATE, precision, this.PrecisionMode)) } else if IsTrue(!IsEqual(price, nil)) { var amountString interface{} = this.NumberToString(amount) var priceString interface{} = this.NumberToString(price) var quoteOrderQuantity interface{} = Precise.StringMul(amountString, priceString) AddElementToObject(request, "quoteOrderQty", this.DecimalToPrecision(quoteOrderQuantity, TRUNCATE, precision, this.PrecisionMode)) } else { quantityIsRequired = true } } else { quantityIsRequired = true } } else { quantityIsRequired = true } } else if IsTrue(IsEqual(uppercaseType, "LIMIT")) { priceIsRequired = true timeInForceIsRequired = true quantityIsRequired = true } else if IsTrue(IsTrue((IsEqual(uppercaseType, "STOP_LOSS"))) || IsTrue((IsEqual(uppercaseType, "TAKE_PROFIT")))) { triggerPriceIsRequired = true quantityIsRequired = true if IsTrue(IsTrue(GetValue(market, "linear")) || IsTrue(GetValue(market, "inverse"))) { priceIsRequired = true } } else if IsTrue(IsTrue((IsEqual(uppercaseType, "STOP_LOSS_LIMIT"))) || IsTrue((IsEqual(uppercaseType, "TAKE_PROFIT_LIMIT")))) { quantityIsRequired = true triggerPriceIsRequired = true priceIsRequired = true timeInForceIsRequired = true } else if IsTrue(IsEqual(uppercaseType, "LIMIT_MAKER")) { priceIsRequired = true quantityIsRequired = true } else if IsTrue(IsEqual(uppercaseType, "STOP")) { quantityIsRequired = true triggerPriceIsRequired = true priceIsRequired = true } else if IsTrue(IsTrue((IsEqual(uppercaseType, "STOP_MARKET"))) || IsTrue((IsEqual(uppercaseType, "TAKE_PROFIT_MARKET")))) { if !IsTrue(closePosition) { quantityIsRequired = true } triggerPriceIsRequired = true } else if IsTrue(IsEqual(uppercaseType, "TRAILING_STOP_MARKET")) { if !IsTrue(closePosition) { quantityIsRequired = true } if IsTrue(IsEqual(trailingPercent, nil)) { panic(InvalidOrder(Add(Add(Add(this.Id, " createOrder() requires a trailingPercent param for a "), typeVar), " order"))) } } if IsTrue(quantityIsRequired) { // portfolio margin has a different amount precision if IsTrue(isPortfolioMargin) { AddElementToObject(request, "quantity", this.ParseToNumeric(amount)) } else { var marketAmountPrecision interface{} = this.SafeString(GetValue(market, "precision"), "amount") var isPrecisionAvailable interface{} = (!IsEqual(marketAmountPrecision, nil)) if IsTrue(isPrecisionAvailable) { AddElementToObject(request, "quantity", this.AmountToPrecision(symbol, amount)) } else { AddElementToObject(request, "quantity", this.ParseToNumeric(amount)) // some options don't have the precision available } } } if IsTrue(IsTrue(priceIsRequired) && !IsTrue(isPriceMatch)) { if IsTrue(IsEqual(price, nil)) { panic(InvalidOrder(Add(Add(Add(this.Id, " createOrder() requires a price argument for a "), typeVar), " order"))) } var pricePrecision interface{} = this.SafeString(GetValue(market, "precision"), "price") var isPricePrecisionAvailable interface{} = (!IsEqual(pricePrecision, nil)) if IsTrue(isPricePrecisionAvailable) { AddElementToObject(request, "price", this.PriceToPrecision(symbol, price)) } else { AddElementToObject(request, "price", this.ParseToNumeric(price)) // some options don't have the precision available } } if IsTrue(triggerPriceIsRequired) { if IsTrue(GetValue(market, "contract")) { if IsTrue(IsEqual(stopPrice, nil)) { panic(InvalidOrder(Add(Add(Add(this.Id, " createOrder() requires a triggerPrice extra param for a "), typeVar), " order"))) } } else { // check for delta price as well if IsTrue(IsTrue(IsTrue(IsEqual(trailingDelta, nil)) && IsTrue(IsEqual(stopPrice, nil))) && IsTrue(IsEqual(trailingPercent, nil))) { panic(InvalidOrder(Add(Add(Add(this.Id, " createOrder() requires a triggerPrice, trailingDelta or trailingPercent param for a "), typeVar), " order"))) } } if IsTrue(!IsEqual(stopPrice, nil)) { AddElementToObject(request, "stopPrice", this.PriceToPrecision(symbol, stopPrice)) } } if IsTrue(IsTrue(IsTrue(timeInForceIsRequired) && IsTrue((IsEqual(this.SafeString(params, "timeInForce"), nil)))) && IsTrue((IsEqual(this.SafeString(request, "timeInForce"), nil)))) { AddElementToObject(request, "timeInForce", this.SafeString(this.Options, "defaultTimeInForce")) // 'GTC' = Good To Cancel (default), 'IOC' = Immediate Or Cancel } if IsTrue(IsTrue(!IsTrue(isPortfolioMargin) && IsTrue(GetValue(market, "contract"))) && IsTrue(postOnly)) { AddElementToObject(request, "timeInForce", "GTX") } // remove timeInForce from params because PO is only used by this.isPostOnly and it's not a valid value for Binance if IsTrue(IsEqual(this.SafeString(params, "timeInForce"), "PO")) { params = this.Omit(params, "timeInForce") } var hedged interface{} = this.SafeBool(params, "hedged", false) if IsTrue(IsTrue(!IsTrue(GetValue(market, "spot")) && !IsTrue(GetValue(market, "option"))) && IsTrue(hedged)) { if IsTrue(reduceOnly) { params = this.Omit(params, "reduceOnly") side = Ternary(IsTrue((IsEqual(side, "buy"))), "sell", "buy") } AddElementToObject(request, "positionSide", Ternary(IsTrue((IsEqual(side, "buy"))), "LONG", "SHORT")) } // unified stp var selfTradePrevention interface{} = this.SafeString(params, "selfTradePrevention") if IsTrue(!IsEqual(selfTradePrevention, nil)) { if IsTrue(GetValue(market, "spot")) { AddElementToObject(request, "selfTradePreventionMode", ToUpper(selfTradePrevention)) // binance enums exactly match the unified ccxt enums (but needs uppercase) } } // unified iceberg var icebergAmount interface{} = this.SafeNumber(params, "icebergAmount") if IsTrue(!IsEqual(icebergAmount, nil)) { if IsTrue(GetValue(market, "spot")) { AddElementToObject(request, "icebergQty", this.AmountToPrecision(symbol, icebergAmount)) } } var requestParams interface{} = this.Omit(params, []interface{}{"type", "newClientOrderId", "clientOrderId", "postOnly", "stopLossPrice", "takeProfitPrice", "stopPrice", "triggerPrice", "trailingTriggerPrice", "trailingPercent", "quoteOrderQty", "cost", "test", "hedged", "selfTradePrevention", "icebergAmount"}) return this.Extend(request, requestParams) } /** * @method * @name binance#createMarketOrderWithCost * @description create a market order by providing the symbol, side and cost * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#new-order-trade * @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 *binance) 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 retRes67238 := (<-this.LoadMarkets()) PanicOnError(retRes67238) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "spot")) { panic(NotSupported(Add(this.Id, " createMarketOrderWithCost() supports spot orders only"))) } AddElementToObject(params, "cost", cost) retRes672915 := (<-this.CreateOrder(symbol, "market", side, cost, nil, params)) PanicOnError(retRes672915) ch <- retRes672915 return nil }() return ch } /** * @method * @name binance#createMarketBuyOrderWithCost * @description create a market buy order by providing the symbol and cost * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#new-order-trade * @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 *binance) 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 retRes67438 := (<-this.LoadMarkets()) PanicOnError(retRes67438) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "spot")) { panic(NotSupported(Add(this.Id, " createMarketBuyOrderWithCost() supports spot orders only"))) } AddElementToObject(params, "cost", cost) retRes674915 := (<-this.CreateOrder(symbol, "market", "buy", cost, nil, params)) PanicOnError(retRes674915) ch <- retRes674915 return nil }() return ch } /** * @method * @name binance#createMarketSellOrderWithCost * @description create a market sell order by providing the symbol and cost * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#new-order-trade * @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 *binance) 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 retRes67638 := (<-this.LoadMarkets()) PanicOnError(retRes67638) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "spot")) { panic(NotSupported(Add(this.Id, " createMarketSellOrderWithCost() supports spot orders only"))) } AddElementToObject(params, "quoteOrderQty", cost) retRes676915 := (<-this.CreateOrder(symbol, "market", "sell", cost, nil, params)) PanicOnError(retRes676915) ch <- retRes676915 return nil }() return ch } /** * @method * @name binance#fetchOrder * @description fetches information on an order made by the user * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#query-order-user_data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Query-Order * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Query-Order * @see https://developers.binance.com/docs/derivatives/option/trade/Query-Single-Order * @see https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-UM-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-CM-Order * @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 {string} [params.marginMode] 'cross' or 'isolated', for spot margin trading * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch an order in a portfolio margin account * @returns {object} An [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchOrder() requires a symbol argument"))) } retRes67948 := (<-this.LoadMarkets()) PanicOnError(retRes67948) var market interface{} = this.Market(symbol) var defaultType interface{} = this.SafeString2(this.Options, "fetchOrder", "defaultType", "spot") var typeVar interface{} = this.SafeString(params, "type", defaultType) var marginMode interface{} = nil marginModeparamsVariable := this.HandleMarginModeAndParams("fetchOrder", params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchOrder", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } var clientOrderId interface{} = this.SafeString2(params, "origClientOrderId", "clientOrderId") if IsTrue(!IsEqual(clientOrderId, nil)) { if IsTrue(GetValue(market, "option")) { AddElementToObject(request, "clientOrderId", clientOrderId) } else { AddElementToObject(request, "origClientOrderId", clientOrderId) } } else { AddElementToObject(request, "orderId", id) } params = this.Omit(params, []interface{}{"type", "clientOrderId", "origClientOrderId"}) var response interface{} = nil if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPrivateGetOrder(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "linear")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmOrder(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPrivateGetOrder(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "inverse")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmOrder(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivateGetOrder(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(IsTrue(IsTrue((IsEqual(typeVar, "margin"))) || IsTrue((!IsEqual(marginMode, nil)))) || IsTrue(isPortfolioMargin)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetMarginOrder(this.Extend(request, params))) PanicOnError(response) } else { if IsTrue(IsEqual(marginMode, "isolated")) { AddElementToObject(request, "isIsolated", true) } response = (<-this.SapiGetMarginOrder(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.PrivateGetOrder(this.Extend(request, params))) PanicOnError(response) } ch <- this.ParseOrder(response, market) return nil }() return ch } /** * @method * @name binance#fetchOrders * @description fetches information on multiple orders made by the user * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#all-orders-user_data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/All-Orders * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/All-Orders * @see https://developers.binance.com/docs/derivatives/option/trade/Query-Option-Order-History * @see https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-All-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Conditional-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Conditional-Orders * @param {string} symbol unified market symbol of the market orders were made in * @param {int} [since] the earliest time in ms to fetch orders for * @param {int} [limit] the maximum number of order structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.marginMode] 'cross' or 'isolated', for spot margin trading * @param {int} [params.until] the latest time in ms to fetch orders for * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch orders in a portfolio margin account * @param {boolean} [params.trigger] set to true if you would like to fetch portfolio margin account trigger or conditional orders * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchOrders() requires a symbol argument"))) } retRes68748 := (<-this.LoadMarkets()) PanicOnError(retRes68748) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOrders", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes687819 := (<-this.FetchPaginatedCallDynamic("fetchOrders", symbol, since, limit, params)) PanicOnError(retRes687819) ch <- retRes687819 return nil } var market interface{} = this.Market(symbol) var defaultType interface{} = this.SafeString2(this.Options, "fetchOrders", "defaultType", GetValue(market, "type")) var typeVar interface{} = this.SafeString(params, "type", defaultType) var marginMode interface{} = nil marginModeparamsVariable := this.HandleMarginModeAndParams("fetchOrders", params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchOrders", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var isConditional interface{} = this.SafeBoolN(params, []interface{}{"stop", "trigger", "conditional"}) params = this.Omit(params, []interface{}{"stop", "trigger", "conditional", "type"}) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } requestparamsVariable := this.HandleUntilOption("endTime", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } var response interface{} = nil if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPrivateGetHistoryOrders(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "linear")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiGetUmConditionalAllOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiGetUmAllOrders(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.FapiPrivateGetAllOrders(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "inverse")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiGetCmConditionalAllOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiGetCmAllOrders(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.DapiPrivateGetAllOrders(this.Extend(request, params))) PanicOnError(response) } } else { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetMarginAllOrders(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsTrue(IsEqual(typeVar, "margin")) || IsTrue(!IsEqual(marginMode, nil))) { if IsTrue(IsEqual(marginMode, "isolated")) { AddElementToObject(request, "isIsolated", true) } response = (<-this.SapiGetMarginAllOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PrivateGetAllOrders(this.Extend(request, params))) PanicOnError(response) } } // // spot // // [ // { // "symbol": "LTCBTC", // "orderId": 1, // "clientOrderId": "myOrder1", // "price": "0.1", // "origQty": "1.0", // "executedQty": "0.0", // "cummulativeQuoteQty": "0.0", // "status": "NEW", // "timeInForce": "GTC", // "type": "LIMIT", // "side": "BUY", // "stopPrice": "0.0", // "icebergQty": "0.0", // "time": 1499827319559, // "updateTime": 1499827319559, // "isWorking": true // } // ] // // futures // // [ // { // "symbol": "BTCUSDT", // "orderId": 1, // "clientOrderId": "myOrder1", // "price": "0.1", // "origQty": "1.0", // "executedQty": "1.0", // "cumQuote": "10.0", // "status": "NEW", // "timeInForce": "GTC", // "type": "LIMIT", // "side": "BUY", // "stopPrice": "0.0", // "updateTime": 1499827319559 // } // ] // // options // // [ // { // "orderId": 4728833085436977152, // "symbol": "ETH-230211-1500-C", // "price": "10.0", // "quantity": "1.00", // "executedQty": "0.00", // "fee": "0", // "side": "BUY", // "type": "LIMIT", // "timeInForce": "GTC", // "reduceOnly": false, // "postOnly": false, // "createTime": 1676083034462, // "updateTime": 1676083034462, // "status": "ACCEPTED", // "avgPrice": "0", // "source": "API", // "clientOrderId": "", // "priceScale": 1, // "quantityScale": 2, // "optionSide": "CALL", // "quoteAsset": "USDT", // "lastTrade": {"id":"69","time":"1676084430567","price":"24.9","qty":"1.00"}, // "mmp": false // } // ] // // inverse portfolio margin // // [ // { // "orderId": 71328442983, // "symbol": "ETHUSD_PERP", // "pair": "ETHUSD", // "status": "CANCELED", // "clientOrderId": "x-xcKtGhcu4b3e3d8515dd4dc5ba9ccc", // "price": "2000", // "avgPrice": "0.00", // "origQty": "1", // "executedQty": "0", // "cumBase": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "side": "BUY", // "origType": "LIMIT", // "time": 1707197843046, // "updateTime": 1707197941373, // "positionSide": "BOTH" // }, // ] // // linear portfolio margin // // [ // { // "orderId": 259235347005, // "symbol": "BTCUSDT", // "status": "CANCELED", // "clientOrderId": "x-xcKtGhcu402881c9103f42bdb4183b", // "price": "35000", // "avgPrice": "0.00000", // "origQty": "0.010", // "executedQty": "0", // "cumQuote": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "side": "BUY", // "origType": "LIMIT", // "time": 1707194702167, // "updateTime": 1707197804748, // "positionSide": "BOTH", // "selfTradePreventionMode": "NONE", // "goodTillDate": 0 // }, // ] // // conditional portfolio margin // // [ // { // "newClientStrategyId": "x-xcKtGhcuaf166172ed504cd1bc0396", // "strategyId": 3733211, // "strategyStatus": "CANCELLED", // "strategyType": "STOP", // "origQty": "0.010", // "price": "35000", // "orderId": 0, // "reduceOnly": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "50000", // "symbol": "BTCUSDT", // "type": "LIMIT", // "bookTime": 1707270098774, // "updateTime": 1707270119261, // "timeInForce": "GTC", // "triggerTime": 0, // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "goodTillDate": 0, // "selfTradePreventionMode": "NONE" // }, // ] // // spot margin portfolio margin // // [ // { // "symbol": "BTCUSDT", // "orderId": 24684460474, // "clientOrderId": "x-R4BD3S82e9ef29d8346440f0b28b86", // "price": "35000.00000000", // "origQty": "0.00100000", // "executedQty": "0.00000000", // "cummulativeQuoteQty": "0.00000000", // "status": "CANCELED", // "timeInForce": "GTC", // "type": "LIMIT", // "side": "BUY", // "stopPrice": "0.00000000", // "icebergQty": "0.00000000", // "time": 1707113538870, // "updateTime": 1707113797688, // "isWorking": true, // "accountId": 200180970, // "selfTradePreventionMode": "EXPIRE_MAKER", // "preventedMatchId": null, // "preventedQuantity": null // }, // ] // ch <- this.ParseOrders(response, market, since, limit) return nil }() return ch } /** * @method * @name binance#fetchOpenOrders * @description fetch all unfilled currently open orders * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#current-open-orders-user_data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Current-All-Open-Orders * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Current-All-Open-Orders * @see https://developers.binance.com/docs/derivatives/option/trade/Query-Current-Open-Option-Orders * @see https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Open-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-UM-Open-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-UM-Open-Conditional-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-CM-Open-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-CM-Open-Conditional-Orders * @param {string} symbol unified market symbol * @param {int} [since] the earliest time in ms to fetch open orders for * @param {int} [limit] the maximum number of open orders structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.marginMode] 'cross' or 'isolated', for spot margin trading * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch open orders in the portfolio margin account * @param {boolean} [params.trigger] set to true if you would like to fetch portfolio margin account conditional orders * @param {string} [params.subType] "linear" or "inverse" * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 retRes71418 := (<-this.LoadMarkets()) PanicOnError(retRes71418) var market interface{} = nil var typeVar interface{} = nil var request interface{} = map[string]interface{} {} var marginMode interface{} = nil marginModeparamsVariable := this.HandleMarginModeAndParams("fetchOpenOrders", params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchOpenOrders", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var isConditional interface{} = this.SafeBoolN(params, []interface{}{"stop", "trigger", "conditional"}) if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) AddElementToObject(request, "symbol", GetValue(market, "id")) var defaultType interface{} = this.SafeString2(this.Options, "fetchOpenOrders", "defaultType", "spot") var marketType interface{} = Ternary(IsTrue((InOp(market, "type"))), GetValue(market, "type"), defaultType) typeVar = this.SafeString(params, "type", marketType) } else if IsTrue(GetValue(this.Options, "warnOnFetchOpenOrdersWithoutSymbol")) { panic(ExchangeError(Add(Add(Add(this.Id, " fetchOpenOrders() WARNING: fetching open orders without specifying a symbol has stricter rate limits (10 times more for spot, 40 times more for other markets) compared to requesting with symbol argument. To acknowledge this warning, set "), this.Id), ".options[\"warnOnFetchOpenOrdersWithoutSymbol\"] = false to suppress this warning message."))) } else { var defaultType interface{} = this.SafeString2(this.Options, "fetchOpenOrders", "defaultType", "spot") typeVar = this.SafeString(params, "type", defaultType) } var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchOpenOrders", market, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) params = this.Omit(params, []interface{}{"type", "stop", "trigger", "conditional"}) var response interface{} = nil if IsTrue(IsEqual(typeVar, "option")) { if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } response = (<-this.EapiPrivateGetOpenOrders(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(this.IsLinear(typeVar, subType)) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiGetUmConditionalOpenOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiGetUmOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.FapiPrivateGetOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(this.IsInverse(typeVar, subType)) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiGetCmConditionalOpenOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiGetCmOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.DapiPrivateGetOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(IsTrue(IsTrue(IsEqual(typeVar, "margin")) || IsTrue(!IsEqual(marginMode, nil))) || IsTrue(isPortfolioMargin)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetMarginOpenOrders(this.Extend(request, params))) PanicOnError(response) } else { if IsTrue(IsEqual(marginMode, "isolated")) { AddElementToObject(request, "isIsolated", true) if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchOpenOrders() requires a symbol argument for isolated markets"))) } } response = (<-this.SapiGetMarginOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.PrivateGetOpenOrders(this.Extend(request, params))) PanicOnError(response) } ch <- this.ParseOrders(response, market, since, limit) return nil }() return ch } /** * @method * @name binance#fetchOpenOrder * @description fetch an open order by the id * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Query-Current-Open-Order * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Query-Current-Open-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-UM-Open-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-UM-Open-Conditional-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-CM-Open-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-CM-Open-Conditional-Order * @param {string} id order id * @param {string} symbol unified market symbol * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.trigger] set to true if you would like to fetch portfolio margin account stop or conditional orders * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch for a portfolio margin account * @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) FetchOpenOrder(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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchOpenOrder() requires a symbol argument"))) } retRes72338 := (<-this.LoadMarkets()) PanicOnError(retRes72338) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchOpenOrder", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var isConditional interface{} = this.SafeBoolN(params, []interface{}{"stop", "trigger", "conditional"}) params = this.Omit(params, []interface{}{"stop", "trigger", "conditional"}) var isPortfolioMarginConditional interface{} = (IsTrue(isPortfolioMargin) && IsTrue(isConditional)) var orderIdRequest interface{} = Ternary(IsTrue(isPortfolioMarginConditional), "strategyId", "orderId") AddElementToObject(request, orderIdRequest, id) var response interface{} = nil if IsTrue(GetValue(market, "linear")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiGetUmConditionalOpenOrder(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiGetUmOpenOrder(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.FapiPrivateGetOpenOrder(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "inverse")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiGetCmConditionalOpenOrder(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiGetCmOpenOrder(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.DapiPrivateGetOpenOrder(this.Extend(request, params))) PanicOnError(response) } } else { if IsTrue(GetValue(market, "option")) { panic(NotSupported(Add(this.Id, " fetchOpenOrder() does not support option markets"))) } else if IsTrue(GetValue(market, "spot")) { panic(NotSupported(Add(this.Id, " fetchOpenOrder() does not support spot markets"))) } } // // linear swap // // { // "orderId": 3697213934, // "symbol": "BTCUSDT", // "status": "NEW", // "clientOrderId": "x-xcKtGhcufb20c5a7761a4aa09aa156", // "price": "33000.00", // "avgPrice": "0.00000", // "origQty": "0.010", // "executedQty": "0.000", // "cumQuote": "0.00000", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "0.00", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "priceMatch": "NONE", // "selfTradePreventionMode": "NONE", // "goodTillDate": 0, // "time": 1707892893502, // "updateTime": 1707892893515 // } // // inverse swap // // { // "orderId": 597368542, // "symbol": "BTCUSD_PERP", // "pair": "BTCUSD", // "status": "NEW", // "clientOrderId": "x-xcKtGhcubbde7ba93b1a4ab881eff3", // "price": "35000", // "avgPrice": "0", // "origQty": "1", // "executedQty": "0", // "cumBase": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "BUY", // "positionSide": "BOTH", // "stopPrice": "0", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "time": 1707893453199, // "updateTime": 1707893453199 // } // // linear portfolio margin // // { // "orderId": 264895013409, // "symbol": "BTCUSDT", // "status": "NEW", // "clientOrderId": "x-xcKtGhcu6278f1adbdf14f74ab432e", // "price": "35000", // "avgPrice": "0", // "origQty": "0.010", // "executedQty": "0", // "cumQuote": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "side": "BUY", // "positionSide": "LONG", // "origType": "LIMIT", // "time": 1707893839364, // "updateTime": 1707893839364, // "goodTillDate": 0, // "selfTradePreventionMode": "NONE" // } // // inverse portfolio margin // // { // "orderId": 71790316950, // "symbol": "ETHUSD_PERP", // "pair": "ETHUSD", // "status": "NEW", // "clientOrderId": "x-xcKtGhcuec11030474204ab08ba2c2", // "price": "2500", // "avgPrice": "0", // "origQty": "1", // "executedQty": "0", // "cumBase": "0", // "timeInForce": "GTC", // "type": "LIMIT", // "reduceOnly": false, // "side": "BUY", // "positionSide": "LONG", // "origType": "LIMIT", // "time": 1707894181694, // "updateTime": 1707894181694 // } // // linear portfolio margin conditional // // { // "newClientStrategyId": "x-xcKtGhcu2205fde44418483ca21874", // "strategyId": 4084339, // "strategyStatus": "NEW", // "strategyType": "STOP", // "origQty": "0.010", // "price": "35000", // "reduceOnly": false, // "side": "BUY", // "positionSide": "LONG", // "stopPrice": "60000", // "symbol": "BTCUSDT", // "bookTime": 1707894490094, // "updateTime": 1707894490094, // "timeInForce": "GTC", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "goodTillDate": 0, // "selfTradePreventionMode": "NONE" // } // // inverse portfolio margin conditional // // { // "newClientStrategyId": "x-xcKtGhcu2da9c765294b433994ffce", // "strategyId": 1423501, // "strategyStatus": "NEW", // "strategyType": "STOP", // "origQty": "1", // "price": "2500", // "reduceOnly": false, // "side": "BUY", // "positionSide": "LONG", // "stopPrice": "4000", // "symbol": "ETHUSD_PERP", // "bookTime": 1707894782679, // "updateTime": 1707894782679, // "timeInForce": "GTC", // "workingType": "CONTRACT_PRICE", // "priceProtect": false // } // ch <- this.ParseOrder(response, market) return nil }() return ch } /** * @method * @name binance#fetchClosedOrders * @description fetches information on multiple closed orders made by the user * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#all-orders-user_data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/All-Orders * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/All-Orders * @see https://developers.binance.com/docs/derivatives/option/trade/Query-Option-Order-History * @see https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-All-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Conditional-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Conditional-Orders * @param {string} symbol unified market symbol of the market orders were made in * @param {int} [since] the earliest time in ms to fetch orders for * @param {int} [limit] the maximum number of order structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {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) * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch orders in a portfolio margin account * @param {boolean} [params.trigger] set to true if you would like to fetch portfolio margin account trigger or conditional orders * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchClosedOrders() requires a symbol argument"))) } orders:= (<-this.FetchOrders(symbol, since, nil, params)) PanicOnError(orders) var filteredOrders interface{} = this.FilterBy(orders, "status", "closed") ch <- this.FilterBySinceLimit(filteredOrders, since, limit) return nil }() return ch } /** * @method * @name binance#fetchCanceledOrders * @description fetches information on multiple canceled orders made by the user * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#all-orders-user_data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/All-Orders * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/All-Orders * @see https://developers.binance.com/docs/derivatives/option/trade/Query-Option-Order-History * @see https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-All-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Conditional-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Conditional-Orders * @param {string} symbol unified market symbol of the market the 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 {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) * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch orders in a portfolio margin account * @param {boolean} [params.trigger] set to true if you would like to fetch portfolio margin account trigger or conditional orders * @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchCanceledOrders() requires a symbol argument"))) } orders:= (<-this.FetchOrders(symbol, since, nil, params)) PanicOnError(orders) var filteredOrders interface{} = this.FilterBy(orders, "status", "canceled") ch <- this.FilterBySinceLimit(filteredOrders, since, limit) return nil }() return ch } /** * @method * @name binance#fetchCanceledAndClosedOrders * @description fetches information on multiple canceled orders made by the user * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#all-orders-user_data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/All-Orders * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/All-Orders * @see https://developers.binance.com/docs/derivatives/option/trade/Query-Option-Order-History * @see https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-All-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Conditional-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Conditional-Orders * @param {string} symbol unified market symbol of the market the 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 {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) * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch orders in a portfolio margin account * @param {boolean} [params.trigger] set to true if you would like to fetch portfolio margin account trigger or conditional orders * @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchCanceledAndClosedOrders() requires a symbol argument"))) } orders:= (<-this.FetchOrders(symbol, since, nil, params)) PanicOnError(orders) var canceledOrders interface{} = this.FilterBy(orders, "status", "canceled") var closedOrders interface{} = this.FilterBy(orders, "status", "closed") var filteredOrders interface{} = this.ArrayConcat(canceledOrders, closedOrders) var sortedOrders interface{} = this.SortBy(filteredOrders, "timestamp") ch <- this.FilterBySinceLimit(sortedOrders, since, limit) return nil }() return ch } /** * @method * @name binance#cancelOrder * @description cancels an open order * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#cancel-order-trade * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-Order * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Cancel-Order * @see https://developers.binance.com/docs/derivatives/option/trade/Cancel-Option-Order * @see https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-UM-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-CM-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-UM-Conditional-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-CM-Conditional-Order * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-Margin-Account-Order * @param {string} id order id * @param {string} symbol unified symbol of the market the order was made in * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to cancel an order in a portfolio margin account * @param {boolean} [params.trigger] set to true if you would like to cancel a portfolio margin account conditional order * @returns {object} An [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " cancelOrder() requires a symbol argument"))) } retRes75458 := (<-this.LoadMarkets()) PanicOnError(retRes75458) var market interface{} = this.Market(symbol) var defaultType interface{} = this.SafeString2(this.Options, "cancelOrder", "defaultType", "spot") var typeVar interface{} = this.SafeString(params, "type", defaultType) var marginMode interface{} = nil marginModeparamsVariable := this.HandleMarginModeAndParams("cancelOrder", params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "cancelOrder", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var isConditional interface{} = this.SafeBoolN(params, []interface{}{"stop", "trigger", "conditional"}) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } var clientOrderId interface{} = this.SafeStringN(params, []interface{}{"origClientOrderId", "clientOrderId", "newClientStrategyId"}) if IsTrue(!IsEqual(clientOrderId, nil)) { if IsTrue(GetValue(market, "option")) { AddElementToObject(request, "clientOrderId", clientOrderId) } else { if IsTrue(IsTrue(isPortfolioMargin) && IsTrue(isConditional)) { AddElementToObject(request, "newClientStrategyId", clientOrderId) } else { AddElementToObject(request, "origClientOrderId", clientOrderId) } } } else { if IsTrue(IsTrue(isPortfolioMargin) && IsTrue(isConditional)) { AddElementToObject(request, "strategyId", id) } else { AddElementToObject(request, "orderId", id) } } params = this.Omit(params, []interface{}{"type", "origClientOrderId", "clientOrderId", "newClientStrategyId", "stop", "trigger", "conditional"}) var response interface{} = nil if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPrivateDeleteOrder(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "linear")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiDeleteUmConditionalOrder(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiDeleteUmOrder(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.FapiPrivateDeleteOrder(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "inverse")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiDeleteCmConditionalOrder(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiDeleteCmOrder(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.DapiPrivateDeleteOrder(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(IsTrue(IsTrue((IsEqual(typeVar, "margin"))) || IsTrue((!IsEqual(marginMode, nil)))) || IsTrue(isPortfolioMargin)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiDeleteMarginOrder(this.Extend(request, params))) PanicOnError(response) } else { if IsTrue(IsEqual(marginMode, "isolated")) { AddElementToObject(request, "isIsolated", true) } response = (<-this.SapiDeleteMarginOrder(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.PrivateDeleteOrder(this.Extend(request, params))) PanicOnError(response) } ch <- this.ParseOrder(response, market) return nil }() return ch } /** * @method * @name binance#cancelAllOrders * @description cancel all open orders in a market * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#cancel-all-open-orders-on-a-symbol-trade * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-All-Open-Orders * @see https://developers.binance.com/docs/derivatives/option/trade/Cancel-all-Option-orders-on-specific-symbol * @see https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-All-Open-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-UM-Open-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-UM-Open-Conditional-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-CM-Open-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-CM-Open-Conditional-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-Margin-Account-All-Open-Orders-on-a-Symbol * @param {string} symbol unified market symbol of the market to cancel orders in * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.marginMode] 'cross' or 'isolated', for spot margin trading * @param {boolean} [params.portfolioMargin] set to true if you would like to cancel orders in a portfolio margin account * @param {boolean} [params.trigger] set to true if you would like to cancel portfolio margin account conditional orders * @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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"))) } retRes76388 := (<-this.LoadMarkets()) PanicOnError(retRes76388) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "cancelAllOrders", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var isConditional interface{} = this.SafeBoolN(params, []interface{}{"stop", "trigger", "conditional"}) var typeVar interface{} = this.SafeString(params, "type", GetValue(market, "type")) params = this.Omit(params, []interface{}{"type", "stop", "trigger", "conditional"}) var marginMode interface{} = nil marginModeparamsVariable := this.HandleMarginModeAndParams("cancelAllOrders", params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) var response interface{} = nil if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPrivateDeleteAllOpenOrders(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "linear")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiDeleteUmConditionalAllOpenOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiDeleteUmAllOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.FapiPrivateDeleteAllOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "inverse")) { if IsTrue(isPortfolioMargin) { if IsTrue(isConditional) { response = (<-this.PapiDeleteCmConditionalAllOpenOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiDeleteCmAllOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.DapiPrivateDeleteAllOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(IsTrue(IsTrue((IsEqual(typeVar, "margin"))) || IsTrue((!IsEqual(marginMode, nil)))) || IsTrue(isPortfolioMargin)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiDeleteMarginAllOpenOrders(this.Extend(request, params))) PanicOnError(response) } else { if IsTrue(IsEqual(marginMode, "isolated")) { AddElementToObject(request, "isIsolated", true) } response = (<-this.SapiDeleteMarginOpenOrders(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.PrivateDeleteOpenOrders(this.Extend(request, params))) PanicOnError(response) } if IsTrue(IsArray(response)) { ch <- this.ParseOrders(response, market) return nil } else { ch <- []interface{}{this.SafeOrder(map[string]interface{} { "info": response, })} return nil } return nil }() return ch } /** * @method * @name binance#cancelOrders * @description cancel multiple orders * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-Multiple-Orders * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Cancel-Multiple-Orders * @param {string[]} ids order ids * @param {string} [symbol] unified market symbol * @param {object} [params] extra parameters specific to the exchange API endpoint * * EXCHANGE SPECIFIC PARAMETERS * @param {string[]} [params.origClientOrderIdList] max length 10 e.g. ["my_id_1","my_id_2"], encode the double quotes. No space after comma * @param {int[]} [params.recvWindow] * @returns {object} an list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *binance) 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"))) } retRes78008 := (<-this.LoadMarkets()) PanicOnError(retRes78008) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "contract")) { panic(BadRequest(Add(this.Id, " cancelOrders is only supported for swap markets."))) } var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), "orderidlist": ids, } var response interface{} = nil if IsTrue(GetValue(market, "linear")) { response = (<-this.FapiPrivateDeleteBatchOrders(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPrivateDeleteBatchOrders(this.Extend(request, params))) PanicOnError(response) } // // [ // { // "clientOrderId": "myOrder1", // "cumQty": "0", // "cumQuote": "0", // "executedQty": "0", // "orderId": 283194212, // "origQty": "11", // "origType": "TRAILING_STOP_MARKET", // "price": "0", // "reduceOnly": false, // "side": "BUY", // "positionSide": "SHORT", // "status": "CANCELED", // "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET // "closePosition": false, // if Close-All // "symbol": "BTCUSDT", // "timeInForce": "GTC", // "type": "TRAILING_STOP_MARKET", // "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order // "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order // "updateTime": 1571110484038, // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // if conditional order trigger is protected // "priceMatch": "NONE", // price match mode // "selfTradePreventionMode": "NONE", // self trading preventation mode // "goodTillDate": 0 // order pre-set auot cancel time for TIF GTD order // }, // { // "code": -2011, // "msg": "Unknown order sent." // } // ] // ch <- this.ParseOrders(response, market) return nil }() return ch } /** * @method * @name binance#fetchOrderTrades * @description fetch all the trades made from a single order * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#account-trade-list-user_data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Account-Trade-List * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Account-Trade-List * @see https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Trade-List * @param {string} id order id * @param {string} symbol unified market symbol * @param {int} [since] the earliest time in ms to fetch trades for * @param {int} [limit] the maximum number of trades to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure} */ func (this *binance) FetchOrderTrades(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 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, " fetchOrderTrades() requires a symbol argument"))) } retRes78728 := (<-this.LoadMarkets()) PanicOnError(retRes78728) var market interface{} = this.Market(symbol) var typeVar interface{} = this.SafeString(params, "type", GetValue(market, "type")) params = this.Omit(params, "type") if IsTrue(!IsEqual(typeVar, "spot")) { panic(NotSupported(Add(this.Id, " fetchOrderTrades() supports spot markets only"))) } var request interface{} = map[string]interface{} { "orderId": id, } retRes788215 := (<-this.FetchMyTrades(symbol, since, limit, this.Extend(request, params))) PanicOnError(retRes788215) ch <- retRes788215 return nil }() return ch } /** * @method * @name binance#fetchMyTrades * @description fetch all trades made by the user * @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api#account-trade-list-user_data * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Account-Trade-List * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Account-Trade-List * @see https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Trade-List * @see https://developers.binance.com/docs/derivatives/option/trade/Account-Trade-List * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/UM-Account-Trade-List * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/CM-Account-Trade-List * @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 {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) * @param {int} [params.until] the latest time in ms to fetch entries for * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch trades for a portfolio margin account * @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure} */ func (this *binance) 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 retRes79068 := (<-this.LoadMarkets()) PanicOnError(retRes79068) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchMyTrades", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes791019 := (<-this.FetchPaginatedCallDynamic("fetchMyTrades", symbol, since, limit, params)) PanicOnError(retRes791019) ch <- retRes791019 return nil } var request interface{} = map[string]interface{} {} var market interface{} = nil var typeVar interface{} = nil var marginMode interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) AddElementToObject(request, "symbol", GetValue(market, "id")) } typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchMyTrades", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var endTime interface{} = this.SafeInteger2(params, "until", "endTime") if IsTrue(!IsEqual(since, nil)) { var startTime interface{} = since AddElementToObject(request, "startTime", startTime) // If startTime and endTime are both not sent, then the last 7 days' data will be returned. // The time between startTime and endTime cannot be longer than 7 days. // The parameter fromId cannot be sent with startTime or endTime. var currentTimestamp interface{} = this.Milliseconds() var oneWeek interface{} = Multiply(Multiply(Multiply(Multiply(7, 24), 60), 60), 1000) if IsTrue(IsGreaterThanOrEqual((Subtract(currentTimestamp, startTime)), oneWeek)) { if IsTrue(IsTrue((IsEqual(endTime, nil))) && IsTrue(GetValue(market, "linear"))) { endTime = this.Sum(startTime, oneWeek) endTime = mathMin(endTime, currentTimestamp) } } } if IsTrue(!IsEqual(endTime, nil)) { AddElementToObject(request, "endTime", endTime) params = this.Omit(params, []interface{}{"endTime", "until"}) } if IsTrue(!IsEqual(limit, nil)) { if IsTrue(IsTrue((IsEqual(typeVar, "option"))) || IsTrue(GetValue(market, "contract"))) { limit = mathMin(limit, 1000) // above 1000, returns error } AddElementToObject(request, "limit", limit) } var response interface{} = nil if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.EapiPrivateGetUserTrades(this.Extend(request, params))) PanicOnError(response) } else { if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchMyTrades() requires a symbol argument"))) } marginModeparamsVariable := this.HandleMarginModeAndParams("fetchMyTrades", params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchMyTrades", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) if IsTrue(IsTrue(IsEqual(typeVar, "spot")) || IsTrue(IsEqual(typeVar, "margin"))) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetMarginMyTrades(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsTrue((IsEqual(typeVar, "margin"))) || IsTrue((!IsEqual(marginMode, nil)))) { if IsTrue(IsEqual(marginMode, "isolated")) { AddElementToObject(request, "isIsolated", true) } response = (<-this.SapiGetMarginMyTrades(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PrivateGetMyTrades(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "linear")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmUserTrades(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPrivateGetUserTrades(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "inverse")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmUserTrades(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivateGetUserTrades(this.Extend(request, params))) PanicOnError(response) } } } // // spot trade // // [ // { // "symbol": "BNBBTC", // "id": 28457, // "orderId": 100234, // "price": "4.00000100", // "qty": "12.00000000", // "commission": "10.10000000", // "commissionAsset": "BNB", // "time": 1499865549590, // "isBuyer": true, // "isMaker": false, // "isBestMatch": true, // } // ] // // futures trade // // [ // { // "accountId": 20, // "buyer": False, // "commission": "-0.07819010", // "commissionAsset": "USDT", // "counterPartyId": 653, // "id": 698759, // "maker": False, // "orderId": 25851813, // "price": "7819.01", // "qty": "0.002", // "quoteQty": "0.01563", // "realizedPnl": "-0.91539999", // "side": "SELL", // "symbol": "BTCUSDT", // "time": 1569514978020 // } // ] // // options (eapi) // // [ // { // "id": 1125899906844226012, // "tradeId": 73, // "orderId": 4638761100843040768, // "symbol": "ETH-230211-1500-C", // "price": "18.70000000", // "quantity": "-0.57000000", // "fee": "0.17305890", // "realizedProfit": "-3.53400000", // "side": "SELL", // "type": "LIMIT", // "volatility": "0.30000000", // "liquidity": "MAKER", // "time": 1676085216845, // "priceScale": 1, // "quantityScale": 2, // "optionSide": "CALL", // "quoteAsset": "USDT" // } // ] // // linear portfolio margin // // [ // { // "symbol": "BTCUSDT", // "id": 4575108247, // "orderId": 261942655610, // "side": "SELL", // "price": "47263.40", // "qty": "0.010", // "realizedPnl": "27.38400000", // "marginAsset": "USDT", // "quoteQty": "472.63", // "commission": "0.18905360", // "commissionAsset": "USDT", // "time": 1707530039409, // "buyer": false, // "maker": false, // "positionSide": "LONG" // } // ] // // inverse portfolio margin // // [ // { // "symbol": "ETHUSD_PERP", // "id": 701907838, // "orderId": 71548909034, // "pair": "ETHUSD", // "side": "SELL", // "price": "2498.15", // "qty": "1", // "realizedPnl": "0.00012517", // "marginAsset": "ETH", // "baseQty": "0.00400296", // "commission": "0.00000160", // "commissionAsset": "ETH", // "time": 1707530317519, // "positionSide": "LONG", // "buyer": false, // "maker": false // } // ] // // spot margin portfolio margin // // [ // { // "symbol": "ADAUSDT", // "id": 470227543, // "orderId": 4421170947, // "price": "0.53880000", // "qty": "10.00000000", // "quoteQty": "5.38800000", // "commission": "0.00538800", // "commissionAsset": "USDT", // "time": 1707545780522, // "isBuyer": false, // "isMaker": false, // "isBestMatch": true // } // ] // ch <- this.ParseTrades(response, market, since, limit) return nil }() return ch } /** * @method * @name binance#fetchMyDustTrades * @description fetch all dust trades made by the user * @see https://developers.binance.com/docs/wallet/asset/dust-log * @param {string} symbol not used by binance fetchMyDustTrades () * @param {int} [since] the earliest time in ms to fetch my dust trades for * @param {int} [limit] the maximum number of dust trades to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.type] 'spot' or 'margin', default spot * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure} */ func (this *binance) FetchMyDustTrades(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) // // Binance provides an opportunity to trade insignificant (i.e. non-tradable and non-withdrawable) // token leftovers (of any asset) into `BNB` coin which in turn can be used to pay trading fees with it. // The corresponding trades history is called the `Dust Log` and can be requested via the following end-point: // https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#dustlog-user_data // 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 retRes81338 := (<-this.LoadMarkets()) PanicOnError(retRes81338) var request interface{} = map[string]interface{} {} if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) AddElementToObject(request, "endTime", this.Sum(since, 7776000000)) } var accountType interface{} = this.SafeStringUpper(params, "type") params = this.Omit(params, "type") if IsTrue(!IsEqual(accountType, nil)) { AddElementToObject(request, "accountType", accountType) } response:= (<-this.SapiGetAssetDribblet(this.Extend(request, params))) PanicOnError(response) // { // "total": "4", // "userAssetDribblets": [ // { // "operateTime": "1627575731000", // "totalServiceChargeAmount": "0.00001453", // "totalTransferedAmount": "0.00072693", // "transId": "70899815863", // "userAssetDribbletDetails": [ // { // "fromAsset": "LTC", // "amount": "0.000006", // "transferedAmount": "0.00000267", // "serviceChargeAmount": "0.00000005", // "operateTime": "1627575731000", // "transId": "70899815863" // }, // { // "fromAsset": "GBP", // "amount": "0.15949157", // "transferedAmount": "0.00072426", // "serviceChargeAmount": "0.00001448", // "operateTime": "1627575731000", // "transId": "70899815863" // } // ] // }, // ] // } var results interface{} = this.SafeList(response, "userAssetDribblets", []interface{}{}) var rows interface{} = this.SafeInteger(response, "total", 0) var data interface{} = []interface{}{} for i := 0; IsLessThan(i, rows); i++ { var logs interface{} = this.SafeList(GetValue(results, i), "userAssetDribbletDetails", []interface{}{}) for j := 0; IsLessThan(j, GetArrayLength(logs)); j++ { AddElementToObject(GetValue(logs, j), "isDustTrade", true) AppendToArray(&data,GetValue(logs, j)) } } var trades interface{} = this.ParseTrades(data, nil, since, limit) ch <- this.FilterBySinceLimit(trades, since, limit) return nil }() return ch } func (this *binance) ParseDustTrade(trade interface{}, optionalArgs ...interface{}) interface{} { // // { // "fromAsset": "USDT", // "amount": "0.009669", // "transferedAmount": "0.00002992", // "serviceChargeAmount": "0.00000059", // "operateTime": "1628076010000", // "transId": "71416578712", // "isDustTrade": true // } // market := GetArg(optionalArgs, 0, nil) _ = market var orderId interface{} = this.SafeString(trade, "transId") var timestamp interface{} = this.SafeInteger(trade, "operateTime") var currencyId interface{} = this.SafeString(trade, "fromAsset") var tradedCurrency interface{} = this.SafeCurrencyCode(currencyId) var bnb interface{} = this.Currency("BNB") var earnedCurrency interface{} = GetValue(bnb, "code") var applicantSymbol interface{} = Add(Add(earnedCurrency, "/"), tradedCurrency) var tradedCurrencyIsQuote interface{} = false if IsTrue(InOp(this.Markets, applicantSymbol)) { tradedCurrencyIsQuote = true } var feeCostString interface{} = this.SafeString(trade, "serviceChargeAmount") var fee interface{} = map[string]interface{} { "currency": earnedCurrency, "cost": this.ParseNumber(feeCostString), } var symbol interface{} = nil var amountString interface{} = nil var costString interface{} = nil var side interface{} = nil if IsTrue(tradedCurrencyIsQuote) { symbol = applicantSymbol amountString = this.SafeString(trade, "transferedAmount") costString = this.SafeString(trade, "amount") side = "buy" } else { symbol = Add(Add(tradedCurrency, "/"), earnedCurrency) amountString = this.SafeString(trade, "amount") costString = this.SafeString(trade, "transferedAmount") side = "sell" } var priceString interface{} = nil if IsTrue(!IsEqual(costString, nil)) { if IsTrue(amountString) { priceString = Precise.StringDiv(costString, amountString) } } var id interface{} = nil var amount interface{} = this.ParseNumber(amountString) var price interface{} = this.ParseNumber(priceString) var cost interface{} = this.ParseNumber(costString) var typeVar interface{} = nil var takerOrMaker interface{} = nil return map[string]interface{} { "id": id, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "symbol": symbol, "order": orderId, "type": typeVar, "takerOrMaker": takerOrMaker, "side": side, "amount": amount, "price": price, "cost": cost, "fee": fee, "info": trade, } } /** * @method * @name binance#fetchDeposits * @description fetch all deposits made to an account * @see https://developers.binance.com/docs/wallet/capital/deposite-history * @see https://developers.binance.com/docs/fiat/rest-api/Get-Fiat-Deposit-Withdraw-History * @param {string} code unified currency code * @param {int} [since] the earliest time in ms to fetch deposits for * @param {int} [limit] the maximum number of deposits structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {bool} [params.fiat] if true, only fiat deposits will be returned * @param {int} [params.until] the latest time in ms to fetch entries for * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure} */ func (this *binance) 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 retRes82768 := (<-this.LoadMarkets()) PanicOnError(retRes82768) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchDeposits", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes828019 := (<-this.FetchPaginatedCallDynamic("fetchDeposits", code, since, limit, params)) PanicOnError(retRes828019) ch <- retRes828019 return nil } var currency interface{} = nil var response interface{} = nil var request interface{} = map[string]interface{} {} var legalMoney interface{} = this.SafeDict(this.Options, "legalMoney", map[string]interface{} {}) var fiatOnly interface{} = this.SafeBool(params, "fiat", false) params = this.Omit(params, "fiatOnly") var until interface{} = this.SafeInteger(params, "until") params = this.Omit(params, "until") if IsTrue(IsTrue(fiatOnly) || IsTrue((InOp(legalMoney, code)))) { if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) } AddElementToObject(request, "transactionType", 0) if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "beginTime", since) } if IsTrue(!IsEqual(until, nil)) { AddElementToObject(request, "endTime", until) } raw:= (<-this.SapiGetFiatOrders(this.Extend(request, params))) PanicOnError(raw) response = this.SafeList(raw, "data", []interface{}{}) } else { if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) AddElementToObject(request, "coin", GetValue(currency, "id")) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) // max 3 months range https://github.com/ccxt/ccxt/issues/6495 var endTime interface{} = this.Sum(since, 7776000000) if IsTrue(!IsEqual(until, nil)) { endTime = mathMin(endTime, until) } AddElementToObject(request, "endTime", endTime) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } response = (<-this.SapiGetCapitalDepositHisrec(this.Extend(request, params))) PanicOnError(response) } for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { AddElementToObject(GetValue(response, i), "type", "deposit") } ch <- this.ParseTransactions(response, currency, since, limit) return nil }() return ch } /** * @method * @name binance#fetchWithdrawals * @description fetch all withdrawals made from an account * @see https://developers.binance.com/docs/wallet/capital/withdraw-history * @see https://developers.binance.com/docs/fiat/rest-api/Get-Fiat-Deposit-Withdraw-History * @param {string} code unified currency code * @param {int} [since] the earliest time in ms to fetch withdrawals for * @param {int} [limit] the maximum number of withdrawals structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {bool} [params.fiat] if true, only fiat withdrawals will be returned * @param {int} [params.until] the latest time in ms to fetch withdrawals for * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure} */ func (this *binance) 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 retRes83898 := (<-this.LoadMarkets()) PanicOnError(retRes83898) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchWithdrawals", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes839319 := (<-this.FetchPaginatedCallDynamic("fetchWithdrawals", code, since, limit, params)) PanicOnError(retRes839319) ch <- retRes839319 return nil } var legalMoney interface{} = this.SafeDict(this.Options, "legalMoney", map[string]interface{} {}) var fiatOnly interface{} = this.SafeBool(params, "fiat", false) params = this.Omit(params, "fiatOnly") var request interface{} = map[string]interface{} {} var until interface{} = this.SafeInteger(params, "until") if IsTrue(!IsEqual(until, nil)) { params = this.Omit(params, "until") AddElementToObject(request, "endTime", until) } var response interface{} = nil var currency interface{} = nil if IsTrue(IsTrue(fiatOnly) || IsTrue((InOp(legalMoney, code)))) { if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) } AddElementToObject(request, "transactionType", 1) if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "beginTime", since) } raw:= (<-this.SapiGetFiatOrders(this.Extend(request, params))) PanicOnError(raw) response = this.SafeList(raw, "data", []interface{}{}) } else { if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) AddElementToObject(request, "coin", GetValue(currency, "id")) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) // max 3 months range https://github.com/ccxt/ccxt/issues/6495 AddElementToObject(request, "endTime", this.Sum(since, 7776000000)) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } response = (<-this.SapiGetCapitalWithdrawHistory(this.Extend(request, params))) PanicOnError(response) } for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { AddElementToObject(GetValue(response, i), "type", "withdrawal") } ch <- this.ParseTransactions(response, currency, since, limit) return nil }() return ch } func (this *binance) ParseTransactionStatusByType(status interface{}, optionalArgs ...interface{}) interface{} { typeVar := GetArg(optionalArgs, 0, nil) _ = typeVar if IsTrue(IsEqual(typeVar, nil)) { return status } var statusesByType interface{} = map[string]interface{} { "deposit": map[string]interface{} { "0": "pending", "1": "ok", "6": "ok", "Processing": "pending", "Failed": "failed", "Successful": "ok", "Refunding": "canceled", "Refunded": "canceled", "Refund Failed": "failed", }, "withdrawal": map[string]interface{} { "0": "pending", "1": "canceled", "2": "pending", "3": "failed", "4": "pending", "5": "failed", "6": "ok", "Processing": "pending", "Failed": "failed", "Successful": "ok", "Refunding": "canceled", "Refunded": "canceled", "Refund Failed": "failed", }, } var statuses interface{} = this.SafeDict(statusesByType, typeVar, map[string]interface{} {}) return this.SafeString(statuses, status, status) } func (this *binance) ParseTransaction(transaction interface{}, optionalArgs ...interface{}) interface{} { // // fetchDeposits // // { // "amount": "4500", // "coin": "USDT", // "network": "BSC", // "status": 1, // "address": "0xc9c923c87347ca0f3451d6d308ce84f691b9f501", // "addressTag": "", // "txId": "Internal transfer 51376627901", // "insertTime": 1618394381000, // "transferType": 1, // "confirmTimes": "1/15" // } // // fetchWithdrawals // // { // "id": "69e53ad305124b96b43668ceab158a18", // "amount": "28.75", // "transactionFee": "0.25", // "coin": "XRP", // "status": 6, // "address": "r3T75fuLjX51mmfb5Sk1kMNuhBgBPJsjza", // "addressTag": "101286922", // "txId": "19A5B24ED0B697E4F0E9CD09FCB007170A605BC93C9280B9E6379C5E6EF0F65A", // "applyTime": "2021-04-15 12:09:16", // "network": "XRP", // "transferType": 0 // } // // fiat transaction // withdraw // { // "orderNo": "CJW684897551397171200", // "fiatCurrency": "GBP", // "indicatedAmount": "29.99", // "amount": "28.49", // "totalFee": "1.50", // "method": "bank transfer", // "status": "Successful", // "createTime": 1614898701000, // "updateTime": 1614898820000 // } // // deposit // { // "orderNo": "25ced37075c1470ba8939d0df2316e23", // "fiatCurrency": "EUR", // "transactionType": 0, // "indicatedAmount": "15.00", // "amount": "15.00", // "totalFee": "0.00", // "method": "card", // "status": "Failed", // "createTime": "1627501026000", // "updateTime": "1627501027000" // } // // withdraw // // { id: "9a67628b16ba4988ae20d329333f16bc" } // currency := GetArg(optionalArgs, 0, nil) _ = currency var id interface{} = this.SafeString2(transaction, "id", "orderNo") var address interface{} = this.SafeString(transaction, "address") var tag interface{} = this.SafeString(transaction, "addressTag") // set but unused if IsTrue(!IsEqual(tag, nil)) { if IsTrue(IsLessThan(GetLength(tag), 1)) { tag = nil } } var txid interface{} = this.SafeString(transaction, "txId") if IsTrue(IsTrue((!IsEqual(txid, nil))) && IsTrue((IsGreaterThanOrEqual(GetIndexOf(txid, "Internal transfer "), 0)))) { txid = Slice(txid, 18, nil) } var currencyId interface{} = this.SafeString2(transaction, "coin", "fiatCurrency") var code interface{} = this.SafeCurrencyCode(currencyId, currency) var timestamp interface{} = nil timestamp = this.SafeInteger2(transaction, "insertTime", "createTime") if IsTrue(IsEqual(timestamp, nil)) { timestamp = this.Parse8601(this.SafeString(transaction, "applyTime")) } var updated interface{} = this.SafeInteger2(transaction, "successTime", "updateTime") var typeVar interface{} = this.SafeString(transaction, "type") if IsTrue(IsEqual(typeVar, nil)) { var txType interface{} = this.SafeString(transaction, "transactionType") if IsTrue(!IsEqual(txType, nil)) { typeVar = Ternary(IsTrue((IsEqual(txType, "0"))), "deposit", "withdrawal") } var legalMoneyCurrenciesById interface{} = this.SafeDict(this.Options, "legalMoneyCurrenciesById") code = this.SafeString(legalMoneyCurrenciesById, code, code) } var status interface{} = this.ParseTransactionStatusByType(this.SafeString(transaction, "status"), typeVar) var amount interface{} = this.SafeNumber(transaction, "amount") var feeCost interface{} = this.SafeNumber2(transaction, "transactionFee", "totalFee") var fee interface{} = nil if IsTrue(!IsEqual(feeCost, nil)) { fee = map[string]interface{} { "currency": code, "cost": feeCost, } } var internalInteger interface{} = this.SafeInteger(transaction, "transferType") var internal interface{} = nil if IsTrue(!IsEqual(internalInteger, nil)) { internal = Ternary(IsTrue(internalInteger), true, false) } var network interface{} = this.SafeString(transaction, "network") return map[string]interface{} { "info": transaction, "id": id, "txid": txid, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "network": network, "address": address, "addressTo": address, "addressFrom": nil, "tag": tag, "tagTo": tag, "tagFrom": nil, "type": typeVar, "amount": amount, "currency": code, "status": status, "updated": updated, "internal": internal, "comment": nil, "fee": fee, } } func (this *binance) ParseTransferStatus(status interface{}) interface{} { var statuses interface{} = map[string]interface{} { "CONFIRMED": "ok", } return this.SafeString(statuses, status, status) } func (this *binance) ParseTransfer(transfer interface{}, optionalArgs ...interface{}) interface{} { // // transfer // // { // "tranId":13526853623 // } // // fetchTransfers // // { // "timestamp": 1614640878000, // "asset": "USDT", // "amount": "25", // "type": "MAIN_UMFUTURE", // "status": "CONFIRMED", // "tranId": 43000126248 // } // // { // "orderType": "C2C", // Enum:PAY(C2B Merchant Acquiring Payment), PAY_REFUND(C2B Merchant Acquiring Payment,refund), C2C(C2C Transfer Payment),CRYPTO_BOX(Crypto box), CRYPTO_BOX_RF(Crypto Box, refund), C2C_HOLDING(Transfer to new Binance user), C2C_HOLDING_RF(Transfer to new Binance user,refund), PAYOUT(B2C Disbursement Payment), REMITTANCE(Send cash) // "transactionId": "M_P_71505104267788288", // "transactionTime": 1610090460133, //trade timestamp // "amount": "23.72469206", //order amount(up to 8 decimal places), positive is income, negative is expenditure // "currency": "BNB", // "walletType": 1, //main wallet type, 1 for funding wallet, 2 for spot wallet, 3 for fiat wallet, 4 or 6 for card payment, 5 for earn wallet // "walletTypes": [1,2], //array format,there are multiple values when using combination payment // "fundsDetail": [ // details // { // "currency": "USDT", //asset // "amount": "1.2", // "walletAssetCost":[ //details of asset cost per wallet // {"1":"0.6"}, // {"2":"0.6"} // ] // }, // { // "currency": "ETH", // "amount": "0.0001", // "walletAssetCost":[ // {"1":"0.00005"}, // {"2":"0.00005"} // ] // } // ], // "payerInfo":{ // "name":"Jack", //nickname or merchant name // "type":"USER", //account type,USER for personal,MERCHANT for merchant // "binanceId":"12345678", //binance uid // "accountId":"67736251" //binance pay id // }, // "receiverInfo":{ // "name":"Alan", //nickname or merchant name // "type":"MERCHANT", //account type,USER for personal,MERCHANT for merchant // "email":"alan@binance.com", //email // "binanceId":"34355667", //binance uid // "accountId":"21326891", //binance pay id // "countryCode":"1", //International area code // "phoneNumber":"8057651210", // "mobileCode":"US", //country code // "extend":[ //extension field // "institutionName": "", // "cardNumber": "", // "digitalWalletId": "" // ] // } // } currency := GetArg(optionalArgs, 0, nil) _ = currency var id interface{} = this.SafeString2(transfer, "tranId", "transactionId") var currencyId interface{} = this.SafeString2(transfer, "asset", "currency") var code interface{} = this.SafeCurrencyCode(currencyId, currency) var amount interface{} = this.SafeNumber(transfer, "amount") var typeVar interface{} = this.SafeString(transfer, "type") var fromAccount interface{} = nil var toAccount interface{} = nil var accountsById interface{} = this.SafeDict(this.Options, "accountsById", map[string]interface{} {}) if IsTrue(!IsEqual(typeVar, nil)) { var parts interface{} = Split(typeVar, "_") fromAccount = this.SafeValue(parts, 0) toAccount = this.SafeValue(parts, 1) fromAccount = this.SafeString(accountsById, fromAccount, fromAccount) toAccount = this.SafeString(accountsById, toAccount, toAccount) } var walletType interface{} = this.SafeInteger(transfer, "walletType") if IsTrue(!IsEqual(walletType, nil)) { var payer interface{} = this.SafeDict(transfer, "payerInfo", map[string]interface{} {}) var receiver interface{} = this.SafeDict(transfer, "receiverInfo", map[string]interface{} {}) fromAccount = this.SafeString(payer, "accountId") toAccount = this.SafeString(receiver, "accountId") } var timestamp interface{} = this.SafeInteger2(transfer, "timestamp", "transactionTime") var status interface{} = this.ParseTransferStatus(this.SafeString(transfer, "status")) return map[string]interface{} { "info": transfer, "id": id, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "currency": code, "amount": amount, "fromAccount": fromAccount, "toAccount": toAccount, "status": status, } } func (this *binance) ParseIncome(income interface{}, optionalArgs ...interface{}) interface{} { // // { // "symbol": "ETHUSDT", // "incomeType": "FUNDING_FEE", // "income": "0.00134317", // "asset": "USDT", // "time": "1621584000000", // "info": "FUNDING_FEE", // "tranId": "4480321991774044580", // "tradeId": "" // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(income, "symbol") var currencyId interface{} = this.SafeString(income, "asset") var timestamp interface{} = this.SafeInteger(income, "time") return map[string]interface{} { "info": income, "symbol": this.SafeSymbol(marketId, market, nil, "swap"), "code": this.SafeCurrencyCode(currencyId), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "id": this.SafeString(income, "tranId"), "amount": this.SafeNumber(income, "income"), } } /** * @method * @name binance#transfer * @description transfer currency internally between wallets on the same account * @see https://developers.binance.com/docs/wallet/asset/user-universal-transfer * @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 * @param {string} [params.type] exchange specific transfer type * @param {string} [params.symbol] the unified symbol, required for isolated margin transfers * @returns {object} a [transfer structure]{@link https://docs.ccxt.com/#/?id=transfer-structure} */ func (this *binance) 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 retRes88308 := (<-this.LoadMarkets()) PanicOnError(retRes88308) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "asset": GetValue(currency, "id"), "amount": this.CurrencyToPrecision(code, amount), } AddElementToObject(request, "type", this.SafeString(params, "type")) params = this.Omit(params, "type") if IsTrue(IsEqual(GetValue(request, "type"), nil)) { var symbol interface{} = this.SafeString(params, "symbol") var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) params = this.Omit(params, "symbol") } var fromId interface{} = ToUpper(this.ConvertTypeToAccount(fromAccount)) var toId interface{} = ToUpper(this.ConvertTypeToAccount(toAccount)) var isolatedSymbol interface{} = nil if IsTrue(!IsEqual(market, nil)) { isolatedSymbol = GetValue(market, "id") } if IsTrue(IsEqual(fromId, "ISOLATED")) { if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(Add(this.Id, " transfer () requires params[\"symbol\"] when fromAccount is "), fromAccount))) } } if IsTrue(IsEqual(toId, "ISOLATED")) { if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(Add(this.Id, " transfer () requires params[\"symbol\"] when toAccount is "), toAccount))) } } var accountsById interface{} = this.SafeDict(this.Options, "accountsById", map[string]interface{} {}) var fromIsolated interface{} = !IsTrue((InOp(accountsById, fromId))) var toIsolated interface{} = !IsTrue((InOp(accountsById, toId))) if IsTrue(IsTrue(fromIsolated) && IsTrue((IsEqual(market, nil)))) { isolatedSymbol = fromId // allow user provide symbol as the from/to account } if IsTrue(IsTrue(toIsolated) && IsTrue((IsEqual(market, nil)))) { isolatedSymbol = toId } if IsTrue(IsTrue(fromIsolated) || IsTrue(toIsolated)) { var fromFuture interface{} = IsTrue(IsEqual(fromId, "UMFUTURE")) || IsTrue(IsEqual(fromId, "CMFUTURE")) var toFuture interface{} = IsTrue(IsEqual(toId, "UMFUTURE")) || IsTrue(IsEqual(toId, "CMFUTURE")) var fromSpot interface{} = IsEqual(fromId, "MAIN") var toSpot interface{} = IsEqual(toId, "MAIN") var funding interface{} = IsTrue(IsEqual(fromId, "FUNDING")) || IsTrue(IsEqual(toId, "FUNDING")) var option interface{} = IsTrue(IsEqual(fromId, "OPTION")) || IsTrue(IsEqual(toId, "OPTION")) var prohibitedWithIsolated interface{} = IsTrue(IsTrue(IsTrue(fromFuture) || IsTrue(toFuture)) || IsTrue(funding)) || IsTrue(option) if IsTrue(IsTrue((IsTrue(fromIsolated) || IsTrue(toIsolated))) && IsTrue(prohibitedWithIsolated)) { panic(BadRequest(Add(Add(Add(Add(this.Id, " transfer () does not allow transfers between "), fromAccount), " and "), toAccount))) } else if IsTrue(IsTrue(toSpot) && IsTrue(fromIsolated)) { fromId = "ISOLATED_MARGIN" AddElementToObject(request, "fromSymbol", isolatedSymbol) } else if IsTrue(IsTrue(fromSpot) && IsTrue(toIsolated)) { toId = "ISOLATED_MARGIN" AddElementToObject(request, "toSymbol", isolatedSymbol) } else { if IsTrue(IsTrue(fromIsolated) && IsTrue(toIsolated)) { AddElementToObject(request, "fromSymbol", fromId) AddElementToObject(request, "toSymbol", toId) fromId = "ISOLATEDMARGIN" toId = "ISOLATEDMARGIN" } else { if IsTrue(fromIsolated) { AddElementToObject(request, "fromSymbol", isolatedSymbol) fromId = "ISOLATEDMARGIN" } if IsTrue(toIsolated) { AddElementToObject(request, "toSymbol", isolatedSymbol) toId = "ISOLATEDMARGIN" } } } AddElementToObject(request, "type", Add(Add(fromId, "_"), toId)) } else { AddElementToObject(request, "type", Add(Add(fromId, "_"), toId)) } } response:= (<-this.SapiPostAssetTransfer(this.Extend(request, params))) PanicOnError(response) // // { // "tranId":13526853623 // } // ch <- this.ParseTransfer(response, currency) return nil }() return ch } /** * @method * @name binance#fetchTransfers * @description fetch a history of internal transfers made on an account * @see https://developers.binance.com/docs/wallet/asset/query-user-universal-transfer * @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 * @param {int} [params.until] the latest time in ms to fetch transfers for * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @param {boolean} [params.internal] default false, when true will fetch pay trade history * @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/#/?id=transfer-structure} */ func (this *binance) 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 retRes89328 := (<-this.LoadMarkets()) PanicOnError(retRes89328) var internal interface{} = this.SafeBool(params, "internal") params = this.Omit(params, "internal") var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchTransfers", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(IsTrue(paginate) && !IsTrue(internal)) { retRes893819 := (<-this.FetchPaginatedCallDynamic("fetchTransfers", code, since, limit, params)) PanicOnError(retRes893819) ch <- retRes893819 return nil } var currency interface{} = nil if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) } var request interface{} = map[string]interface{} {} var limitKey interface{} = "limit" if !IsTrue(internal) { var defaultType interface{} = this.SafeString2(this.Options, "fetchTransfers", "defaultType", "spot") var fromAccount interface{} = this.SafeString(params, "fromAccount", defaultType) var defaultTo interface{} = Ternary(IsTrue((IsEqual(fromAccount, "future"))), "spot", "future") var toAccount interface{} = this.SafeString(params, "toAccount", defaultTo) var typeVar interface{} = this.SafeString(params, "type") var accountsByType interface{} = this.SafeDict(this.Options, "accountsByType", map[string]interface{} {}) var fromId interface{} = this.SafeString(accountsByType, fromAccount) var toId interface{} = this.SafeString(accountsByType, toAccount) if IsTrue(IsEqual(typeVar, nil)) { if IsTrue(IsEqual(fromId, nil)) { var keys interface{} = ObjectKeys(accountsByType) panic(ExchangeError(Add(Add(this.Id, " fromAccount parameter must be one of "), Join(keys, ", ")))) } if IsTrue(IsEqual(toId, nil)) { var keys interface{} = ObjectKeys(accountsByType) panic(ExchangeError(Add(Add(this.Id, " toAccount parameter must be one of "), Join(keys, ", ")))) } typeVar = Add(Add(fromId, "_"), toId) } AddElementToObject(request, "type", typeVar) limitKey = "size" } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, limitKey, limit) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } var until interface{} = this.SafeInteger(params, "until") if IsTrue(!IsEqual(until, nil)) { params = this.Omit(params, "until") AddElementToObject(request, "endTime", until) } var response interface{} = nil if IsTrue(internal) { response = (<-this.SapiGetPayTransactions(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.SapiGetAssetTransfer(this.Extend(request, params))) PanicOnError(response) } var rows interface{} = this.SafeList2(response, "rows", "data", []interface{}{}) ch <- this.ParseTransfers(rows, currency, since, limit) return nil }() return ch } /** * @method * @name binance#fetchDepositAddress * @description fetch the deposit address for a currency associated with this account * @see https://developers.binance.com/docs/wallet/capital/deposite-address * @param {string} code unified currency code * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.network] network for fetch deposit address * @returns {object} an [address structure]{@link https://docs.ccxt.com/#/?id=address-structure} */ func (this *binance) 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 retRes90738 := (<-this.LoadMarkets()) PanicOnError(retRes90738) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "coin": GetValue(currency, "id"), } var networks interface{} = this.SafeDict(this.Options, "networks", map[string]interface{} {}) var network interface{} = this.SafeStringUpper(params, "network") // this line allows the user to specify either ERC20 or ETH network = this.SafeString(networks, network, network) // handle ERC20>ETH alias if IsTrue(!IsEqual(network, nil)) { AddElementToObject(request, "network", network) params = this.Omit(params, "network") } // has support for the 'network' parameter response:= (<-this.SapiGetCapitalDepositAddress(this.Extend(request, params))) PanicOnError(response) // // { // "currency": "XRP", // "address": "rEb8TK3gBgk5auZkwc6sHnwrGVJH8DuaLh", // "tag": "108618262", // "info": { // "coin": "XRP", // "address": "rEb8TK3gBgk5auZkwc6sHnwrGVJH8DuaLh", // "tag": "108618262", // "url": "https://bithomp.com/explorer/rEb8TK3gBgk5auZkwc6sHnwrGVJH8DuaLh" // } // } // ch <- this.ParseDepositAddress(response, currency) return nil }() return ch } func (this *binance) ParseDepositAddress(response interface{}, optionalArgs ...interface{}) interface{} { // // { // "currency": "XRP", // "address": "rEb8TK3gBgk5auZkwc6sHnwrGVJH8DuaLh", // "tag": "108618262", // "info": { // "coin": "XRP", // "address": "rEb8TK3gBgk5auZkwc6sHnwrGVJH8DuaLh", // "tag": "108618262", // "url": "https://bithomp.com/explorer/rEb8TK3gBgk5auZkwc6sHnwrGVJH8DuaLh" // } // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var info interface{} = this.SafeDict(response, "info", map[string]interface{} {}) var url interface{} = this.SafeString(info, "url") var address interface{} = this.SafeString(response, "address") var currencyId interface{} = this.SafeString(response, "currency") var code interface{} = this.SafeCurrencyCode(currencyId, currency) var impliedNetwork interface{} = nil if IsTrue(!IsEqual(url, nil)) { var reverseNetworks interface{} = this.SafeDict(this.Options, "reverseNetworks", map[string]interface{} {}) var parts interface{} = Split(url, "/") var topLevel interface{} = this.SafeString(parts, 2) if IsTrue(IsTrue((IsEqual(topLevel, "blockchair.com"))) || IsTrue((IsEqual(topLevel, "viewblock.io")))) { var subLevel interface{} = this.SafeString(parts, 3) if IsTrue(!IsEqual(subLevel, nil)) { topLevel = Add(Add(topLevel, "/"), subLevel) } } impliedNetwork = this.SafeString(reverseNetworks, topLevel) var impliedNetworks interface{} = this.SafeDict(this.Options, "impliedNetworks", map[string]interface{} { "ETH": map[string]interface{} { "ERC20": "ETH", }, "TRX": map[string]interface{} { "TRC20": "TRX", }, }) if IsTrue(InOp(impliedNetworks, code)) { var conversion interface{} = this.SafeDict(impliedNetworks, code, map[string]interface{} {}) impliedNetwork = this.SafeString(conversion, impliedNetwork, impliedNetwork) } } var tag interface{} = this.SafeString(response, "tag", "") if IsTrue(IsEqual(GetLength(tag), 0)) { tag = nil } this.CheckAddress(address) return map[string]interface{} { "info": response, "currency": code, "network": impliedNetwork, "address": address, "tag": tag, } } /** * @method * @name binance#fetchTransactionFees * @deprecated * @description please use fetchDepositWithdrawFees instead * @see https://developers.binance.com/docs/wallet/capital/all-coins-info * @param {string[]|undefined} codes not used by binance fetchTransactionFees () * @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 *binance) FetchTransactionFees(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 retRes91698 := (<-this.LoadMarkets()) PanicOnError(retRes91698) response:= (<-this.SapiGetCapitalConfigGetall(params)) PanicOnError(response) // // [ // { // "coin": "BAT", // "depositAllEnable": true, // "withdrawAllEnable": true, // "name": "Basic Attention Token", // "free": "0", // "locked": "0", // "freeze": "0", // "withdrawing": "0", // "ipoing": "0", // "ipoable": "0", // "storage": "0", // "isLegalMoney": false, // "trading": true, // "networkList": [ // { // "network": "BNB", // "coin": "BAT", // "withdrawIntegerMultiple": "0.00000001", // "isDefault": false, // "depositEnable": true, // "withdrawEnable": true, // "depositDesc": '', // "withdrawDesc": '', // "specialTips": "The name of this asset is Basic Attention Token (BAT). Both a MEMO and an Address are required to successfully deposit your BEP2 tokens to Binance.", // "name": "BEP2", // "resetAddressStatus": false, // "addressRegex": "^(bnb1)[0-9a-z]{38}$", // "memoRegex": "^[0-9A-Za-z\\-_]{1,120}$", // "withdrawFee": "0.27", // "withdrawMin": "0.54", // "withdrawMax": "10000000000", // "minConfirm": "1", // "unLockConfirm": "0" // }, // { // "network": "BSC", // "coin": "BAT", // "withdrawIntegerMultiple": "0.00000001", // "isDefault": false, // "depositEnable": true, // "withdrawEnable": true, // "depositDesc": '', // "withdrawDesc": '', // "specialTips": "The name of this asset is Basic Attention Token. Please ensure you are depositing Basic Attention Token (BAT) tokens under the contract address ending in 9766e.", // "name": "BEP20 (BSC)", // "resetAddressStatus": false, // "addressRegex": "^(0x)[0-9A-Fa-f]{40}$", // "memoRegex": '', // "withdrawFee": "0.27", // "withdrawMin": "0.54", // "withdrawMax": "10000000000", // "minConfirm": "15", // "unLockConfirm": "0" // }, // { // "network": "ETH", // "coin": "BAT", // "withdrawIntegerMultiple": "0.00000001", // "isDefault": true, // "depositEnable": true, // "withdrawEnable": true, // "depositDesc": '', // "withdrawDesc": '', // "specialTips": "The name of this asset is Basic Attention Token. Please ensure you are depositing Basic Attention Token (BAT) tokens under the contract address ending in 887ef.", // "name": "ERC20", // "resetAddressStatus": false, // "addressRegex": "^(0x)[0-9A-Fa-f]{40}$", // "memoRegex": '', // "withdrawFee": "27", // "withdrawMin": "54", // "withdrawMax": "10000000000", // "minConfirm": "12", // "unLockConfirm": "0" // } // ] // } // ] // var withdrawFees interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) var currencyId interface{} = this.SafeString(entry, "coin") var code interface{} = this.SafeCurrencyCode(currencyId) var networkList interface{} = this.SafeList(entry, "networkList", []interface{}{}) AddElementToObject(withdrawFees, code, map[string]interface{} {}) for j := 0; IsLessThan(j, GetArrayLength(networkList)); j++ { var networkEntry interface{} = GetValue(networkList, j) var networkId interface{} = this.SafeString(networkEntry, "network") var networkCode interface{} = this.SafeCurrencyCode(networkId) var fee interface{} = this.SafeNumber(networkEntry, "withdrawFee") AddElementToObject(GetValue(withdrawFees, code), networkCode, fee) } } ch <- map[string]interface{} { "withdraw": withdrawFees, "deposit": map[string]interface{} {}, "info": response, } return nil }() return ch } /** * @method * @name binance#fetchDepositWithdrawFees * @description fetch deposit and withdraw fees * @see https://developers.binance.com/docs/wallet/capital/all-coins-info * @param {string[]|undefined} codes not used by binance fetchDepositWithdrawFees () * @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 *binance) 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 retRes92848 := (<-this.LoadMarkets()) PanicOnError(retRes92848) response:= (<-this.SapiGetCapitalConfigGetall(params)) PanicOnError(response) // // [ // { // "coin": "BAT", // "depositAllEnable": true, // "withdrawAllEnable": true, // "name": "Basic Attention Token", // "free": "0", // "locked": "0", // "freeze": "0", // "withdrawing": "0", // "ipoing": "0", // "ipoable": "0", // "storage": "0", // "isLegalMoney": false, // "trading": true, // "networkList": [ // { // "network": "BNB", // "coin": "BAT", // "withdrawIntegerMultiple": "0.00000001", // "isDefault": false, // "depositEnable": true, // "withdrawEnable": true, // "depositDesc": '', // "withdrawDesc": '', // "specialTips": "The name of this asset is Basic Attention Token (BAT). Both a MEMO and an Address are required to successfully deposit your BEP2 tokens to Binance.", // "name": "BEP2", // "resetAddressStatus": false, // "addressRegex": "^(bnb1)[0-9a-z]{38}$", // "memoRegex": "^[0-9A-Za-z\\-_]{1,120}$", // "withdrawFee": "0.27", // "withdrawMin": "0.54", // "withdrawMax": "10000000000", // "minConfirm": "1", // "unLockConfirm": "0" // }, // ... // ] // } // ] // ch <- this.ParseDepositWithdrawFees(response, codes, "coin") return nil }() return ch } func (this *binance) ParseDepositWithdrawFee(fee interface{}, optionalArgs ...interface{}) interface{} { // // { // "coin": "BAT", // "depositAllEnable": true, // "withdrawAllEnable": true, // "name": "Basic Attention Token", // "free": "0", // "locked": "0", // "freeze": "0", // "withdrawing": "0", // "ipoing": "0", // "ipoable": "0", // "storage": "0", // "isLegalMoney": false, // "trading": true, // "networkList": [ // { // "network": "BNB", // "coin": "BAT", // "withdrawIntegerMultiple": "0.00000001", // "isDefault": false, // "depositEnable": true, // "withdrawEnable": true, // "depositDesc": '', // "withdrawDesc": '', // "specialTips": "The name of this asset is Basic Attention Token (BAT). Both a MEMO and an Address are required to successfully deposit your BEP2 tokens to Binance.", // "name": "BEP2", // "resetAddressStatus": false, // "addressRegex": "^(bnb1)[0-9a-z]{38}$", // "memoRegex": "^[0-9A-Za-z\\-_]{1,120}$", // "withdrawFee": "0.27", // "withdrawMin": "0.54", // "withdrawMax": "10000000000", // "minConfirm": "1", // "unLockConfirm": "0" // }, // ... // ] // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var networkList interface{} = this.SafeList(fee, "networkList", []interface{}{}) var result interface{} = this.DepositWithdrawFee(fee) for j := 0; IsLessThan(j, GetArrayLength(networkList)); j++ { var networkEntry interface{} = GetValue(networkList, j) var networkId interface{} = this.SafeString(networkEntry, "network") var networkCode interface{} = this.NetworkIdToCode(networkId) var withdrawFee interface{} = this.SafeNumber(networkEntry, "withdrawFee") var isDefault interface{} = this.SafeBool(networkEntry, "isDefault") if IsTrue(IsEqual(isDefault, true)) { AddElementToObject(result, "withdraw", map[string]interface{} { "fee": withdrawFee, "percentage": nil, }) } AddElementToObject(GetValue(result, "networks"), networkCode, map[string]interface{} { "withdraw": map[string]interface{} { "fee": withdrawFee, "percentage": nil, }, "deposit": map[string]interface{} { "fee": nil, "percentage": nil, }, }) } return result } /** * @method * @name binance#withdraw * @description make a withdrawal * @see https://developers.binance.com/docs/wallet/capital/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 * @returns {object} a [transaction structure]{@link https://docs.ccxt.com/#/?id=transaction-structure} */ func (this *binance) 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) retRes94158 := (<-this.LoadMarkets()) PanicOnError(retRes94158) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "coin": GetValue(currency, "id"), "address": address, "amount": this.CurrencyToPrecision(code, amount), } if IsTrue(!IsEqual(tag, nil)) { AddElementToObject(request, "addressTag", tag) } var networks interface{} = this.SafeDict(this.Options, "networks", map[string]interface{} {}) var network interface{} = this.SafeStringUpper(params, "network") // this line allows the user to specify either ERC20 or ETH network = this.SafeString(networks, network, network) // handle ERC20>ETH alias if IsTrue(!IsEqual(network, nil)) { AddElementToObject(request, "network", network) params = this.Omit(params, "network") } response:= (<-this.SapiPostCapitalWithdrawApply(this.Extend(request, params))) PanicOnError(response) // { id: '9a67628b16ba4988ae20d329333f16bc' } ch <- this.ParseTransaction(response, currency) return nil }() return ch } func (this *binance) ParseTradingFee(fee interface{}, optionalArgs ...interface{}) interface{} { // // spot // [ // { // "symbol": "BTCUSDT", // "makerCommission": "0.001", // "takerCommission": "0.001" // } // ] // // swap // { // "symbol": "BTCUSD_PERP", // "makerCommissionRate": "0.00015", // 0.015% // "takerCommissionRate": "0.00040" // 0.040% // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(fee, "symbol") var symbol interface{} = this.SafeSymbol(marketId, market, nil, "spot") return map[string]interface{} { "info": fee, "symbol": symbol, "maker": this.SafeNumber2(fee, "makerCommission", "makerCommissionRate"), "taker": this.SafeNumber2(fee, "takerCommission", "takerCommissionRate"), "percentage": nil, "tierBased": nil, } } /** * @method * @name binance#fetchTradingFee * @description fetch the trading fees for a market * @see https://developers.binance.com/docs/wallet/asset/trade-fee * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/User-Commission-Rate * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/User-Commission-Rate * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-User-Commission-Rate-for-UM * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-User-Commission-Rate-for-CM * @param {string} symbol unified market symbol * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch trading fees in a portfolio margin account * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a [fee structure]{@link https://docs.ccxt.com/#/?id=fee-structure} */ func (this *binance) 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 retRes94858 := (<-this.LoadMarkets()) PanicOnError(retRes94858) var market interface{} = this.Market(symbol) var typeVar interface{} = GetValue(market, "type") var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchTradingFee", market, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchTradingFee", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var isLinear interface{} = this.IsLinear(typeVar, subType) var isInverse interface{} = this.IsInverse(typeVar, subType) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } var response interface{} = nil if IsTrue(isLinear) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmCommissionRate(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPrivateGetCommissionRate(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(isInverse) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmCommissionRate(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivateGetCommissionRate(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.SapiGetAssetTradeFee(this.Extend(request, params))) PanicOnError(response) } // // spot // // [ // { // "symbol": "BTCUSDT", // "makerCommission": "0.001", // "takerCommission": "0.001" // } // ] // // swap // // { // "symbol": "BTCUSD_PERP", // "makerCommissionRate": "0.00015", // 0.015% // "takerCommissionRate": "0.00040" // 0.040% // } // var data interface{} = response if IsTrue(IsArray(data)) { data = this.SafeDict(data, 0, map[string]interface{} {}) } ch <- this.ParseTradingFee(data, market) return nil }() return ch } /** * @method * @name binance#fetchTradingFees * @description fetch the trading fees for multiple markets * @see https://developers.binance.com/docs/wallet/asset/trade-fee * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Information-V2 * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Account-Information * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Config * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a dictionary of [fee structures]{@link https://docs.ccxt.com/#/?id=fee-structure} indexed by market symbols */ func (this *binance) FetchTradingFees(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 retRes95528 := (<-this.LoadMarkets()) PanicOnError(retRes95528) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchTradingFees", nil, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchTradingFees", nil, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isSpotOrMargin interface{} = IsTrue((IsEqual(typeVar, "spot"))) || IsTrue((IsEqual(typeVar, "margin"))) var isLinear interface{} = this.IsLinear(typeVar, subType) var isInverse interface{} = this.IsInverse(typeVar, subType) var response interface{} = nil if IsTrue(isSpotOrMargin) { response = (<-this.SapiGetAssetTradeFee(params)) PanicOnError(response) } else if IsTrue(isLinear) { response = (<-this.FapiPrivateGetAccountConfig(params)) PanicOnError(response) } else if IsTrue(isInverse) { response = (<-this.DapiPrivateGetAccount(params)) PanicOnError(response) } // // sapi / spot // // [ // { // "symbol": "ZRXBNB", // "makerCommission": "0.001", // "takerCommission": "0.001" // }, // { // "symbol": "ZRXBTC", // "makerCommission": "0.001", // "takerCommission": "0.001" // }, // ] // // fapi / future / linear // // { // "feeTier": 0, // account commisssion tier // "canTrade": true, // if can trade // "canDeposit": true, // if can transfer in asset // "canWithdraw": true, // if can transfer out asset // "updateTime": 0, // "totalInitialMargin": "0.00000000", // total initial margin required with current mark price (useless with isolated positions), only for USDT asset // "totalMaintMargin": "0.00000000", // total maintenance margin required, only for USDT asset // "totalWalletBalance": "23.72469206", // total wallet balance, only for USDT asset // "totalUnrealizedProfit": "0.00000000", // total unrealized profit, only for USDT asset // "totalMarginBalance": "23.72469206", // total margin balance, only for USDT asset // "totalPositionInitialMargin": "0.00000000", // initial margin required for positions with current mark price, only for USDT asset // "totalOpenOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price, only for USDT asset // "totalCrossWalletBalance": "23.72469206", // crossed wallet balance, only for USDT asset // "totalCrossUnPnl": "0.00000000", // unrealized profit of crossed positions, only for USDT asset // "availableBalance": "23.72469206", // available balance, only for USDT asset // "maxWithdrawAmount": "23.72469206" // maximum amount for transfer out, only for USDT asset // ... // } // // dapi / delivery / inverse // // { // "canDeposit": true, // "canTrade": true, // "canWithdraw": true, // "feeTier": 2, // "updateTime": 0 // } // if IsTrue(isSpotOrMargin) { // // [ // { // "symbol": "ZRXBNB", // "makerCommission": "0.001", // "takerCommission": "0.001" // }, // { // "symbol": "ZRXBTC", // "makerCommission": "0.001", // "takerCommission": "0.001" // }, // ] // var result interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var fee interface{} = this.ParseTradingFee(GetValue(response, i)) var symbol interface{} = GetValue(fee, "symbol") AddElementToObject(result, symbol, fee) } ch <- result return nil } else if IsTrue(isLinear) { // // { // "feeTier": 0, // account commisssion tier // "canTrade": true, // if can trade // "canDeposit": true, // if can transfer in asset // "canWithdraw": true, // if can transfer out asset // "updateTime": 0, // "totalInitialMargin": "0.00000000", // total initial margin required with current mark price (useless with isolated positions), only for USDT asset // "totalMaintMargin": "0.00000000", // total maintenance margin required, only for USDT asset // "totalWalletBalance": "23.72469206", // total wallet balance, only for USDT asset // "totalUnrealizedProfit": "0.00000000", // total unrealized profit, only for USDT asset // "totalMarginBalance": "23.72469206", // total margin balance, only for USDT asset // "totalPositionInitialMargin": "0.00000000", // initial margin required for positions with current mark price, only for USDT asset // "totalOpenOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price, only for USDT asset // "totalCrossWalletBalance": "23.72469206", // crossed wallet balance, only for USDT asset // "totalCrossUnPnl": "0.00000000", // unrealized profit of crossed positions, only for USDT asset // "availableBalance": "23.72469206", // available balance, only for USDT asset // "maxWithdrawAmount": "23.72469206" // maximum amount for transfer out, only for USDT asset // ... // } // var symbols interface{} = ObjectKeys(this.Markets) var result interface{} = map[string]interface{} {} var feeTier interface{} = this.SafeInteger(response, "feeTier") var feeTiers interface{} = GetValue(GetValue(GetValue(this.Fees, "linear"), "trading"), "tiers") var maker interface{} = GetValue(GetValue(GetValue(feeTiers, "maker"), feeTier), 1) var taker interface{} = GetValue(GetValue(GetValue(feeTiers, "taker"), feeTier), 1) for i := 0; IsLessThan(i, GetArrayLength(symbols)); i++ { var symbol interface{} = GetValue(symbols, i) var market interface{} = GetValue(this.Markets, symbol) if IsTrue(GetValue(market, "linear")) { AddElementToObject(result, symbol, map[string]interface{} { "info": map[string]interface{} { "feeTier": feeTier, }, "symbol": symbol, "maker": maker, "taker": taker, }) } } ch <- result return nil } else if IsTrue(isInverse) { // // { // "canDeposit": true, // "canTrade": true, // "canWithdraw": true, // "feeTier": 2, // "updateTime": 0 // } // var symbols interface{} = ObjectKeys(this.Markets) var result interface{} = map[string]interface{} {} var feeTier interface{} = this.SafeInteger(response, "feeTier") var feeTiers interface{} = GetValue(GetValue(GetValue(this.Fees, "inverse"), "trading"), "tiers") var maker interface{} = GetValue(GetValue(GetValue(feeTiers, "maker"), feeTier), 1) var taker interface{} = GetValue(GetValue(GetValue(feeTiers, "taker"), feeTier), 1) for i := 0; IsLessThan(i, GetArrayLength(symbols)); i++ { var symbol interface{} = GetValue(symbols, i) var market interface{} = GetValue(this.Markets, symbol) if IsTrue(GetValue(market, "inverse")) { AddElementToObject(result, symbol, map[string]interface{} { "info": map[string]interface{} { "feeTier": feeTier, }, "symbol": symbol, "maker": maker, "taker": taker, }) } } ch <- result return nil } return nil }() return ch } /** * @method * @name binance#futuresTransfer * @ignore * @description transfer between futures account * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/New-Future-Account-Transfer * @param {string} code unified currency code * @param {float} amount the amount to transfer * @param {string} type 1 - transfer from spot account to USDT-Ⓜ futures account, 2 - transfer from USDT-Ⓜ futures account to spot account, 3 - transfer from spot account to COIN-Ⓜ futures account, 4 - transfer from COIN-Ⓜ futures account to spot account * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {float} params.recvWindow * @returns {object} a [transfer structure]{@link https://docs.ccxt.com/#/?id=futures-transfer-structure} */ func (this *binance) FuturesTransfer(code interface{}, amount interface{}, typeVar 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 if IsTrue(IsTrue((IsLessThan(typeVar, 1))) || IsTrue((IsGreaterThan(typeVar, 4)))) { panic(ArgumentsRequired(Add(this.Id, " type must be between 1 and 4"))) } retRes97338 := (<-this.LoadMarkets()) PanicOnError(retRes97338) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "asset": GetValue(currency, "id"), "amount": amount, "type": typeVar, } response:= (<-this.SapiPostFuturesTransfer(this.Extend(request, params))) PanicOnError(response) // // { // "tranId": 100000001 // } // ch <- this.ParseTransfer(response, currency) return nil }() return ch } /** * @method * @name binance#fetchFundingRate * @description fetch the current funding rate * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Index-Price-and-Mark-Price * @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 *binance) 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 retRes97608 := (<-this.LoadMarkets()) PanicOnError(retRes97608) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } var response interface{} = nil if IsTrue(GetValue(market, "linear")) { response = (<-this.FapiPublicGetPremiumIndex(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPublicGetPremiumIndex(this.Extend(request, params))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchFundingRate() supports linear and inverse contracts only"))) } if IsTrue(GetValue(market, "inverse")) { response = GetValue(response, 0) } // // { // "symbol": "BTCUSDT", // "markPrice": "45802.81129892", // "indexPrice": "45745.47701915", // "estimatedSettlePrice": "45133.91753671", // "lastFundingRate": "0.00063521", // "interestRate": "0.00010000", // "nextFundingTime": "1621267200000", // "time": "1621252344001" // } // ch <- this.ParseFundingRate(response, market) return nil }() return ch } /** * @method * @name binance#fetchFundingRateHistory * @description fetches historical funding rate prices * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Get-Funding-Rate-History * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Get-Funding-Rate-History-of-Perpetual-Futures * @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 * @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) * @param {string} [params.subType] "linear" or "inverse" * @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/#/?id=funding-rate-history-structure} */ func (this *binance) 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 retRes98078 := (<-this.LoadMarkets()) PanicOnError(retRes98078) var request interface{} = map[string]interface{} {} var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchFundingRateHistory", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes981219 := (<-this.FetchPaginatedCallDeterministic("fetchFundingRateHistory", symbol, since, limit, "8h", params)) PanicOnError(retRes981219) ch <- retRes981219 return nil } var defaultType interface{} = this.SafeString2(this.Options, "fetchFundingRateHistory", "defaultType", "future") var typeVar interface{} = this.SafeString(params, "type", defaultType) var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) symbol = GetValue(market, "symbol") AddElementToObject(request, "symbol", GetValue(market, "id")) } var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchFundingRateHistory", market, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) params = this.Omit(params, "type") if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } var until interface{} = this.SafeInteger(params, "until") // unified in milliseconds var endTime interface{} = this.SafeInteger(params, "endTime", until) // exchange-specific in milliseconds params = this.Omit(params, []interface{}{"endTime", "until"}) if IsTrue(!IsEqual(endTime, nil)) { AddElementToObject(request, "endTime", endTime) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { response = (<-this.FapiPublicGetFundingRate(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(this.IsInverse(typeVar, subType)) { response = (<-this.DapiPublicGetFundingRate(this.Extend(request, params))) PanicOnError(response) } else { panic(NotSupported(Add(Add(Add(this.Id, " fetchFundingRateHistory() is not supported for "), typeVar), " markets"))) } // // { // "symbol": "BTCUSDT", // "fundingRate": "0.00063521", // "fundingTime": "1621267200000", // } // ch <- this.ParseFundingRateHistories(response, market, since, limit) return nil }() return ch } func (this *binance) ParseFundingRateHistory(contract interface{}, optionalArgs ...interface{}) interface{} { // // { // "symbol": "BTCUSDT", // "fundingRate": "0.00063521", // "fundingTime": "1621267200000", // } // 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"), nil, nil, "swap"), "fundingRate": this.SafeNumber(contract, "fundingRate"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), } } /** * @method * @name binance#fetchFundingRates * @description fetch the funding rate for multiple markets * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Index-Price-and-Mark-Price * @param {string[]|undefined} symbols list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.subType] "linear" or "inverse" * @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/#/?id=funding-rates-structure}, indexed by market symbols */ func (this *binance) 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 retRes98858 := (<-this.LoadMarkets()) PanicOnError(retRes98858) symbols = this.MarketSymbols(symbols) var defaultType interface{} = this.SafeString2(this.Options, "fetchFundingRates", "defaultType", "future") var typeVar interface{} = this.SafeString(params, "type", defaultType) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchFundingRates", nil, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var query interface{} = this.Omit(params, "type") var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { response = (<-this.FapiPublicGetPremiumIndex(query)) PanicOnError(response) } else if IsTrue(this.IsInverse(typeVar, subType)) { response = (<-this.DapiPublicGetPremiumIndex(query)) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchFundingRates() supports linear and inverse contracts only"))) } ch <- this.ParseFundingRates(response, symbols) return nil }() return ch } func (this *binance) ParseFundingRate(contract interface{}, optionalArgs ...interface{}) interface{} { // ensure it matches with https://www.binance.com/en/futures/funding-history/0 // // fetchFundingRate, fetchFundingRates // // { // "symbol": "BTCUSDT", // "markPrice": "45802.81129892", // "indexPrice": "45745.47701915", // "estimatedSettlePrice": "45133.91753671", // "lastFundingRate": "0.00063521", // "interestRate": "0.00010000", // "nextFundingTime": "1621267200000", // "time": "1621252344001" // } // // fetchFundingInterval, fetchFundingIntervals // // { // "symbol": "BLZUSDT", // "adjustedFundingRateCap": "0.03000000", // "adjustedFundingRateFloor": "-0.03000000", // "fundingIntervalHours": 4, // "disclaimer": false // } // market := GetArg(optionalArgs, 0, nil) _ = market var timestamp interface{} = this.SafeInteger(contract, "time") var marketId interface{} = this.SafeString(contract, "symbol") var symbol interface{} = this.SafeSymbol(marketId, market, nil, "contract") var markPrice interface{} = this.SafeNumber(contract, "markPrice") var indexPrice interface{} = this.SafeNumber(contract, "indexPrice") var interestRate interface{} = this.SafeNumber(contract, "interestRate") var estimatedSettlePrice interface{} = this.SafeNumber(contract, "estimatedSettlePrice") var fundingRate interface{} = this.SafeNumber(contract, "lastFundingRate") var fundingTime interface{} = this.SafeInteger(contract, "nextFundingTime") var interval interface{} = this.SafeString(contract, "fundingIntervalHours") var intervalString interface{} = nil if IsTrue(!IsEqual(interval, nil)) { intervalString = Add(interval, "h") } return map[string]interface{} { "info": contract, "symbol": symbol, "markPrice": markPrice, "indexPrice": indexPrice, "interestRate": interestRate, "estimatedSettlePrice": estimatedSettlePrice, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "fundingRate": fundingRate, "fundingTimestamp": fundingTime, "fundingDatetime": this.Iso8601(fundingTime), "nextFundingRate": nil, "nextFundingTimestamp": nil, "nextFundingDatetime": nil, "previousFundingRate": nil, "previousFundingTimestamp": nil, "previousFundingDatetime": nil, "interval": intervalString, } } func (this *binance) ParseAccountPositions(account interface{}, optionalArgs ...interface{}) interface{} { filterClosed := GetArg(optionalArgs, 0, false) _ = filterClosed var positions interface{} = this.SafeList(account, "positions") var assets interface{} = this.SafeList(account, "assets", []interface{}{}) var balances interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(assets)); i++ { var entry interface{} = GetValue(assets, i) var currencyId interface{} = this.SafeString(entry, "asset") var code interface{} = this.SafeCurrencyCode(currencyId) var crossWalletBalance interface{} = this.SafeString(entry, "crossWalletBalance") var crossUnPnl interface{} = this.SafeString(entry, "crossUnPnl") AddElementToObject(balances, code, map[string]interface{} { "crossMargin": Precise.StringAdd(crossWalletBalance, crossUnPnl), "crossWalletBalance": crossWalletBalance, }) } var result interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(positions)); i++ { var position interface{} = GetValue(positions, i) var marketId interface{} = this.SafeString(position, "symbol") var market interface{} = this.SafeMarket(marketId, nil, nil, "contract") var code interface{} = Ternary(IsTrue(GetValue(market, "linear")), GetValue(market, "quote"), GetValue(market, "base")) var maintenanceMargin interface{} = this.SafeString(position, "maintMargin") // check for maintenance margin so empty positions are not returned var isPositionOpen interface{} = IsTrue((!IsEqual(maintenanceMargin, "0"))) && IsTrue((!IsEqual(maintenanceMargin, "0.00000000"))) if IsTrue(!IsTrue(filterClosed) || IsTrue(isPositionOpen)) { // sometimes not all the codes are correctly returned... if IsTrue(InOp(balances, code)) { var parsed interface{} = this.ParseAccountPosition(this.Extend(position, map[string]interface{} { "crossMargin": GetValue(GetValue(balances, code), "crossMargin"), "crossWalletBalance": GetValue(GetValue(balances, code), "crossWalletBalance"), }), market) AppendToArray(&result,parsed) } } } return result } func (this *binance) ParseAccountPosition(position interface{}, optionalArgs ...interface{}) interface{} { // // usdm // // v3 (similar for cross & isolated) // // { // "symbol": "WLDUSDT", // "positionSide": "BOTH", // "positionAmt": "-849", // "unrealizedProfit": "11.17920750", // "notional": "-1992.46079250", // "isolatedMargin": "0", // "isolatedWallet": "0", // "initialMargin": "99.62303962", // "maintMargin": "11.95476475", // "updateTime": "1721995760449" // "leverage": "50", // in v2 // "entryPrice": "2.34", // in v2 // "positionInitialMargin": "118.82116614", // in v2 // "openOrderInitialMargin": "0", // in v2 // "isolated": false, // in v2 // "breakEvenPrice": "2.3395788", // in v2 // "maxNotional": "25000", // in v2 // "bidNotional": "0", // in v2 // "askNotional": "0" // in v2 // } // // coinm // // { // "symbol": "BTCUSD_210625", // "initialMargin": "0.00024393", // "maintMargin": "0.00002439", // "unrealizedProfit": "-0.00000163", // "positionInitialMargin": "0.00024393", // "openOrderInitialMargin": "0", // "leverage": "10", // "isolated": false, // "positionSide": "BOTH", // "entryPrice": "41021.20000069", // "maxQty": "100", // "notionalValue": "0.00243939", // "isolatedWallet": "0", // "crossMargin": "0.314" // "crossWalletBalance": "34", // } // // linear portfolio margin // // { // "symbol": "CTSIUSDT", // "initialMargin": "0", // "maintMargin": "0", // "unrealizedProfit": "0.00000000", // "positionInitialMargin": "0", // "openOrderInitialMargin": "0", // "leverage": "20", // "entryPrice": "0.0", // "maxNotional": "25000", // "bidNotional": "0", // "askNotional": "0", // "positionSide": "SHORT", // "positionAmt": "0", // "updateTime": 0, // "notional": "0", // "breakEvenPrice": "0.0" // } // // inverse portoflio margin // // { // "symbol": "TRXUSD_PERP", // "initialMargin": "0", // "maintMargin": "0", // "unrealizedProfit": "0.00000000", // "positionInitialMargin": "0", // "openOrderInitialMargin": "0", // "leverage": "20", // "entryPrice": "0.00000000", // "positionSide": "SHORT", // "positionAmt": "0", // "maxQty": "5000000", // "updateTime": 0, // "notionalValue": "0", // "breakEvenPrice": "0.00000000" // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(position, "symbol") market = this.SafeMarket(marketId, market, nil, "contract") var symbol interface{} = this.SafeString(market, "symbol") var leverageString interface{} = this.SafeString(position, "leverage") var leverage interface{} = Ternary(IsTrue((!IsEqual(leverageString, nil))), ParseInt(leverageString), nil) var initialMarginString interface{} = this.SafeString(position, "initialMargin") var initialMargin interface{} = this.ParseNumber(initialMarginString) var initialMarginPercentageString interface{} = nil if IsTrue(!IsEqual(leverageString, nil)) { initialMarginPercentageString = Precise.StringDiv("1", leverageString, 8) var rational interface{} = this.IsRoundNumber(Mod(1000, leverage)) if !IsTrue(rational) { initialMarginPercentageString = Precise.StringDiv(Precise.StringAdd(initialMarginPercentageString, "1e-8"), "1", 8) } } // as oppose to notionalValue var usdm interface{} = (InOp(position, "notional")) var maintenanceMarginString interface{} = this.SafeString(position, "maintMargin") var maintenanceMargin interface{} = this.ParseNumber(maintenanceMarginString) var entryPriceString interface{} = this.SafeString(position, "entryPrice") var entryPrice interface{} = this.ParseNumber(entryPriceString) var notionalString interface{} = this.SafeString2(position, "notional", "notionalValue") var notionalStringAbs interface{} = Precise.StringAbs(notionalString) var notional interface{} = this.ParseNumber(notionalStringAbs) var contractsString interface{} = this.SafeString(position, "positionAmt") var contractsStringAbs interface{} = Precise.StringAbs(contractsString) if IsTrue(IsEqual(contractsString, nil)) { var entryNotional interface{} = Precise.StringMul(Precise.StringMul(leverageString, initialMarginString), entryPriceString) var contractSizeNew interface{} = this.SafeString(market, "contractSize") contractsString = Precise.StringDiv(entryNotional, contractSizeNew) contractsStringAbs = Precise.StringDiv(Precise.StringAdd(contractsString, "0.5"), "1", 0) } var contracts interface{} = this.ParseNumber(contractsStringAbs) var leverageBrackets interface{} = this.SafeDict(this.Options, "leverageBrackets", map[string]interface{} {}) var leverageBracket interface{} = this.SafeList(leverageBrackets, symbol, []interface{}{}) var maintenanceMarginPercentageString interface{} = nil for i := 0; IsLessThan(i, GetArrayLength(leverageBracket)); i++ { var bracket interface{} = GetValue(leverageBracket, i) if IsTrue(Precise.StringLt(notionalStringAbs, GetValue(bracket, 0))) { break } maintenanceMarginPercentageString = GetValue(bracket, 1) } var maintenanceMarginPercentage interface{} = this.ParseNumber(maintenanceMarginPercentageString) var unrealizedPnlString interface{} = this.SafeString(position, "unrealizedProfit") var unrealizedPnl interface{} = this.ParseNumber(unrealizedPnlString) var timestamp interface{} = this.SafeInteger(position, "updateTime") if IsTrue(IsEqual(timestamp, 0)) { timestamp = nil } var isolated interface{} = this.SafeBool(position, "isolated") if IsTrue(IsEqual(isolated, nil)) { var isolatedMarginRaw interface{} = this.SafeString(position, "isolatedMargin") isolated = !IsTrue(Precise.StringEq(isolatedMarginRaw, "0")) } var marginMode interface{} = nil var collateralString interface{} = nil var walletBalance interface{} = nil if IsTrue(isolated) { marginMode = "isolated" walletBalance = this.SafeString(position, "isolatedWallet") collateralString = Precise.StringAdd(walletBalance, unrealizedPnlString) } else { marginMode = "cross" walletBalance = this.SafeString(position, "crossWalletBalance") collateralString = this.SafeString(position, "crossMargin") } var collateral interface{} = this.ParseNumber(collateralString) var marginRatio interface{} = nil var side interface{} = nil var percentage interface{} = nil var liquidationPriceStringRaw interface{} = nil var liquidationPrice interface{} = nil var contractSize interface{} = this.SafeValue(market, "contractSize") var contractSizeString interface{} = this.NumberToString(contractSize) if IsTrue(Precise.StringEquals(notionalString, "0")) { entryPrice = nil } else { side = Ternary(IsTrue(Precise.StringLt(notionalString, "0")), "short", "long") marginRatio = this.ParseNumber(Precise.StringDiv(Precise.StringAdd(Precise.StringDiv(maintenanceMarginString, collateralString), "5e-5"), "1", 4)) percentage = this.ParseNumber(Precise.StringMul(Precise.StringDiv(unrealizedPnlString, initialMarginString, 4), "100")) if IsTrue(usdm) { // calculate liquidation price // // liquidationPrice = (walletBalance / (contracts * (±1 + mmp))) + (±entryPrice / (±1 + mmp)) // // mmp = maintenanceMarginPercentage // where ± is negative for long and positive for short // TODO: calculate liquidation price for coinm contracts var onePlusMaintenanceMarginPercentageString interface{} = nil var entryPriceSignString interface{} = entryPriceString if IsTrue(IsEqual(side, "short")) { onePlusMaintenanceMarginPercentageString = Precise.StringAdd("1", maintenanceMarginPercentageString) } else { onePlusMaintenanceMarginPercentageString = Precise.StringAdd("-1", maintenanceMarginPercentageString) entryPriceSignString = Precise.StringMul("-1", entryPriceSignString) } var leftSide interface{} = Precise.StringDiv(walletBalance, Precise.StringMul(contractsStringAbs, onePlusMaintenanceMarginPercentageString)) var rightSide interface{} = Precise.StringDiv(entryPriceSignString, onePlusMaintenanceMarginPercentageString) liquidationPriceStringRaw = Precise.StringAdd(leftSide, rightSide) } else { // calculate liquidation price // // liquidationPrice = (contracts * contractSize(±1 - mmp)) / (±1/entryPrice * contracts * contractSize - walletBalance) // var onePlusMaintenanceMarginPercentageString interface{} = nil var entryPriceSignString interface{} = entryPriceString if IsTrue(IsEqual(side, "short")) { onePlusMaintenanceMarginPercentageString = Precise.StringSub("1", maintenanceMarginPercentageString) } else { onePlusMaintenanceMarginPercentageString = Precise.StringSub("-1", maintenanceMarginPercentageString) entryPriceSignString = Precise.StringMul("-1", entryPriceSignString) } var size interface{} = Precise.StringMul(contractsStringAbs, contractSizeString) var leftSide interface{} = Precise.StringMul(size, onePlusMaintenanceMarginPercentageString) var rightSide interface{} = Precise.StringSub(Precise.StringMul(Precise.StringDiv("1", entryPriceSignString), size), walletBalance) liquidationPriceStringRaw = Precise.StringDiv(leftSide, rightSide) } var pricePrecision interface{} = this.PrecisionFromString(this.SafeString(GetValue(market, "precision"), "price")) var pricePrecisionPlusOne interface{} = Add(pricePrecision, 1) var pricePrecisionPlusOneString interface{} = ToString(pricePrecisionPlusOne) // round half up rounder := NewPrecise(Add("5e-", pricePrecisionPlusOneString)) var rounderString interface{} = ToString(rounder) var liquidationPriceRoundedString interface{} = Precise.StringAdd(rounderString, liquidationPriceStringRaw) var truncatedLiquidationPrice interface{} = Precise.StringDiv(liquidationPriceRoundedString, "1", pricePrecision) if IsTrue(IsEqual(GetValue(truncatedLiquidationPrice, 0), "-")) { // user cannot be liquidated // since he has more collateral than the size of the position truncatedLiquidationPrice = nil } liquidationPrice = this.ParseNumber(truncatedLiquidationPrice) } var positionSide interface{} = this.SafeString(position, "positionSide") var hedged interface{} = !IsEqual(positionSide, "BOTH") return map[string]interface{} { "info": position, "id": nil, "symbol": symbol, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "initialMargin": initialMargin, "initialMarginPercentage": this.ParseNumber(initialMarginPercentageString), "maintenanceMargin": maintenanceMargin, "maintenanceMarginPercentage": maintenanceMarginPercentage, "entryPrice": entryPrice, "notional": notional, "leverage": this.ParseNumber(leverageString), "unrealizedPnl": unrealizedPnl, "contracts": contracts, "contractSize": contractSize, "marginRatio": marginRatio, "liquidationPrice": liquidationPrice, "markPrice": nil, "collateral": collateral, "marginMode": marginMode, "side": side, "hedged": hedged, "percentage": percentage, } } func (this *binance) ParsePositionRisk(position interface{}, optionalArgs ...interface{}) interface{} { // // usdm // // { // symbol: "WLDUSDT", // positionSide: "BOTH", // positionAmt: "5", // entryPrice: "2.3483", // breakEvenPrice: "2.349356735", // markPrice: "2.39560000", // unRealizedProfit: "0.23650000", // liquidationPrice: "0", // isolatedMargin: "0", // notional: "11.97800000", // isolatedWallet: "0", // updateTime: "1722062678998", // initialMargin: "2.39560000", // not in v2 // maintMargin: "0.07186800", // not in v2 // positionInitialMargin: "2.39560000", // not in v2 // openOrderInitialMargin: "0", // not in v2 // adl: "2", // not in v2 // bidNotional: "0", // not in v2 // askNotional: "0", // not in v2 // marginAsset: "USDT", // not in v2 // // the below fields are only in v2 // leverage: "5", // maxNotionalValue: "6000000", // marginType: "cross", // isAutoAddMargin: "false", // isolated: false, // adlQuantile: "2", // // coinm // // { // "symbol": "BTCUSD_PERP", // "positionAmt": "2", // "entryPrice": "37643.10000021", // "markPrice": "38103.05510455", // "unRealizedProfit": "0.00006413", // "liquidationPrice": "25119.97445760", // "leverage": "2", // "maxQty": "1500", // "marginType": "isolated", // "isolatedMargin": "0.00274471", // "isAutoAddMargin": "false", // "positionSide": "BOTH", // "notionalValue": "0.00524892", // "isolatedWallet": "0.00268058" // } // // inverse portfolio margin // // { // "symbol": "ETHUSD_PERP", // "positionAmt": "1", // "entryPrice": "2422.400000007", // "markPrice": "2424.51267823", // "unRealizedProfit": "0.0000036", // "liquidationPrice": "293.57678898", // "leverage": "100", // "positionSide": "LONG", // "updateTime": 1707371941861, // "maxQty": "15", // "notionalValue": "0.00412454", // "breakEvenPrice": "2423.368960034" // } // // linear portfolio margin // // { // "symbol": "BTCUSDT", // "positionAmt": "0.01", // "entryPrice": "44525.0", // "markPrice": "45464.1735922", // "unRealizedProfit": "9.39173592", // "liquidationPrice": "38007.16308568", // "leverage": "100", // "positionSide": "LONG", // "updateTime": 1707371879042, // "maxNotionalValue": "500000.0", // "notional": "454.64173592", // "breakEvenPrice": "44542.81" // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(position, "symbol") market = this.SafeMarket(marketId, market, nil, "contract") var symbol interface{} = this.SafeString(market, "symbol") var isolatedMarginString interface{} = this.SafeString(position, "isolatedMargin") var leverageBrackets interface{} = this.SafeDict(this.Options, "leverageBrackets", map[string]interface{} {}) var leverageBracket interface{} = this.SafeList(leverageBrackets, symbol, []interface{}{}) var notionalString interface{} = this.SafeString2(position, "notional", "notionalValue") var notionalStringAbs interface{} = Precise.StringAbs(notionalString) var maintenanceMarginPercentageString interface{} = nil for i := 0; IsLessThan(i, GetArrayLength(leverageBracket)); i++ { var bracket interface{} = GetValue(leverageBracket, i) if IsTrue(Precise.StringLt(notionalStringAbs, GetValue(bracket, 0))) { break } maintenanceMarginPercentageString = GetValue(bracket, 1) } var notional interface{} = this.ParseNumber(notionalStringAbs) var contractsAbs interface{} = Precise.StringAbs(this.SafeString(position, "positionAmt")) var contracts interface{} = this.ParseNumber(contractsAbs) var unrealizedPnlString interface{} = this.SafeString(position, "unRealizedProfit") var unrealizedPnl interface{} = this.ParseNumber(unrealizedPnlString) var liquidationPriceString interface{} = this.OmitZero(this.SafeString(position, "liquidationPrice")) var liquidationPrice interface{} = this.ParseNumber(liquidationPriceString) var collateralString interface{} = nil var marginMode interface{} = this.SafeString(position, "marginType") if IsTrue(IsTrue(IsEqual(marginMode, nil)) && IsTrue(!IsEqual(isolatedMarginString, nil))) { marginMode = Ternary(IsTrue(Precise.StringEq(isolatedMarginString, "0")), "cross", "isolated") } var side interface{} = nil if IsTrue(Precise.StringGt(notionalString, "0")) { side = "long" } else if IsTrue(Precise.StringLt(notionalString, "0")) { side = "short" } var entryPriceString interface{} = this.SafeString(position, "entryPrice") var entryPrice interface{} = this.ParseNumber(entryPriceString) var contractSize interface{} = this.SafeValue(market, "contractSize") var contractSizeString interface{} = this.NumberToString(contractSize) // as oppose to notionalValue var linear interface{} = (InOp(position, "notional")) if IsTrue(IsEqual(marginMode, "cross")) { // calculate collateral var precision interface{} = this.SafeDict(market, "precision", map[string]interface{} {}) var basePrecisionValue interface{} = this.SafeString(precision, "base") var quotePrecisionValue interface{} = this.SafeString2(precision, "quote", "price") var precisionIsUndefined interface{} = IsTrue((IsEqual(basePrecisionValue, nil))) && IsTrue((IsEqual(quotePrecisionValue, nil))) if !IsTrue(precisionIsUndefined) { if IsTrue(linear) { // walletBalance = (liquidationPrice * (±1 + mmp) ± entryPrice) * contracts var onePlusMaintenanceMarginPercentageString interface{} = nil var entryPriceSignString interface{} = entryPriceString if IsTrue(IsEqual(side, "short")) { onePlusMaintenanceMarginPercentageString = Precise.StringAdd("1", maintenanceMarginPercentageString) entryPriceSignString = Precise.StringMul("-1", entryPriceSignString) } else { onePlusMaintenanceMarginPercentageString = Precise.StringAdd("-1", maintenanceMarginPercentageString) } var inner interface{} = Precise.StringMul(liquidationPriceString, onePlusMaintenanceMarginPercentageString) var leftSide interface{} = Precise.StringAdd(inner, entryPriceSignString) var quotePrecision interface{} = this.PrecisionFromString(this.SafeString2(precision, "quote", "price")) if IsTrue(!IsEqual(quotePrecision, nil)) { collateralString = Precise.StringDiv(Precise.StringMul(leftSide, contractsAbs), "1", quotePrecision) } } else { // walletBalance = (contracts * contractSize) * (±1/entryPrice - (±1 - mmp) / liquidationPrice) var onePlusMaintenanceMarginPercentageString interface{} = nil var entryPriceSignString interface{} = entryPriceString if IsTrue(IsEqual(side, "short")) { onePlusMaintenanceMarginPercentageString = Precise.StringSub("1", maintenanceMarginPercentageString) } else { onePlusMaintenanceMarginPercentageString = Precise.StringSub("-1", maintenanceMarginPercentageString) entryPriceSignString = Precise.StringMul("-1", entryPriceSignString) } var leftSide interface{} = Precise.StringMul(contractsAbs, contractSizeString) var rightSide interface{} = Precise.StringSub(Precise.StringDiv("1", entryPriceSignString), Precise.StringDiv(onePlusMaintenanceMarginPercentageString, liquidationPriceString)) var basePrecision interface{} = this.PrecisionFromString(this.SafeString(precision, "base")) if IsTrue(!IsEqual(basePrecision, nil)) { collateralString = Precise.StringDiv(Precise.StringMul(leftSide, rightSide), "1", basePrecision) } } } } else { collateralString = this.SafeString(position, "isolatedMargin") } collateralString = Ternary(IsTrue((IsEqual(collateralString, nil))), "0", collateralString) var collateral interface{} = this.ParseNumber(collateralString) var markPrice interface{} = this.ParseNumber(this.OmitZero(this.SafeString(position, "markPrice"))) var timestamp interface{} = this.SafeInteger(position, "updateTime") if IsTrue(IsEqual(timestamp, 0)) { timestamp = nil } var maintenanceMarginPercentage interface{} = this.ParseNumber(maintenanceMarginPercentageString) var maintenanceMarginString interface{} = Precise.StringMul(maintenanceMarginPercentageString, notionalStringAbs) if IsTrue(IsEqual(maintenanceMarginString, nil)) { // for a while, this new value was a backup to the existing calculations, but in future we might prioritize this maintenanceMarginString = this.SafeString(position, "maintMargin") } var maintenanceMargin interface{} = this.ParseNumber(maintenanceMarginString) var initialMarginString interface{} = nil var initialMarginPercentageString interface{} = nil var leverageString interface{} = this.SafeString(position, "leverage") if IsTrue(!IsEqual(leverageString, nil)) { var leverage interface{} = ParseInt(leverageString) var rational interface{} = this.IsRoundNumber(Mod(1000, leverage)) initialMarginPercentageString = Precise.StringDiv("1", leverageString, 8) if !IsTrue(rational) { initialMarginPercentageString = Precise.StringAdd(initialMarginPercentageString, "1e-8") } var unrounded interface{} = Precise.StringMul(notionalStringAbs, initialMarginPercentageString) initialMarginString = Precise.StringDiv(unrounded, "1", 8) } else { initialMarginString = this.SafeString(position, "initialMargin") var unrounded interface{} = Precise.StringMul(initialMarginString, "1") initialMarginPercentageString = Precise.StringDiv(unrounded, notionalStringAbs, 8) } var marginRatio interface{} = nil var percentage interface{} = nil if !IsTrue(Precise.StringEquals(collateralString, "0")) { marginRatio = this.ParseNumber(Precise.StringDiv(Precise.StringAdd(Precise.StringDiv(maintenanceMarginString, collateralString), "5e-5"), "1", 4)) percentage = this.ParseNumber(Precise.StringMul(Precise.StringDiv(unrealizedPnlString, initialMarginString, 4), "100")) } var positionSide interface{} = this.SafeString(position, "positionSide") var hedged interface{} = !IsEqual(positionSide, "BOTH") return map[string]interface{} { "info": position, "id": nil, "symbol": symbol, "contracts": contracts, "contractSize": contractSize, "unrealizedPnl": unrealizedPnl, "leverage": this.ParseNumber(leverageString), "liquidationPrice": liquidationPrice, "collateral": collateral, "notional": notional, "markPrice": markPrice, "entryPrice": entryPrice, "timestamp": timestamp, "initialMargin": this.ParseNumber(initialMarginString), "initialMarginPercentage": this.ParseNumber(initialMarginPercentageString), "maintenanceMargin": maintenanceMargin, "maintenanceMarginPercentage": maintenanceMarginPercentage, "marginRatio": marginRatio, "datetime": this.Iso8601(timestamp), "marginMode": marginMode, "marginType": marginMode, "side": side, "hedged": hedged, "percentage": percentage, "stopLossPrice": nil, "takeProfitPrice": nil, } } func (this *binance) LoadLeverageBrackets(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) reload := GetArg(optionalArgs, 0, false) _ = reload params := GetArg(optionalArgs, 1, map[string]interface{} {}) _ = params retRes104938 := (<-this.LoadMarkets()) PanicOnError(retRes104938) // by default cache the leverage bracket // it contains useful stuff like the maintenance margin and initial margin for positions var leverageBrackets interface{} = this.SafeDict(this.Options, "leverageBrackets") if IsTrue(IsTrue((IsEqual(leverageBrackets, nil))) || IsTrue((reload))) { var defaultType interface{} = this.SafeString(this.Options, "defaultType", "future") var typeVar interface{} = this.SafeString(params, "type", defaultType) var query interface{} = this.Omit(params, "type") var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("loadLeverageBrackets", nil, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "loadLeverageBrackets", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmLeverageBracket(query)) PanicOnError(response) } else { response = (<-this.FapiPrivateGetLeverageBracket(query)) PanicOnError(response) } } else if IsTrue(this.IsInverse(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmLeverageBracket(query)) PanicOnError(response) } else { response = (<-this.DapiPrivateV2GetLeverageBracket(query)) PanicOnError(response) } } else { panic(NotSupported(Add(this.Id, " loadLeverageBrackets() supports linear and inverse contracts only"))) } AddElementToObject(this.Options, "leverageBrackets", map[string]interface{} {}) for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) var marketId interface{} = this.SafeString(entry, "symbol") var symbol interface{} = this.SafeSymbol(marketId, nil, nil, "contract") var brackets interface{} = this.SafeList(entry, "brackets", []interface{}{}) var result interface{} = []interface{}{} for j := 0; IsLessThan(j, GetArrayLength(brackets)); j++ { var bracket interface{} = GetValue(brackets, j) var floorValue interface{} = this.SafeString2(bracket, "notionalFloor", "qtyFloor") var maintenanceMarginPercentage interface{} = this.SafeString(bracket, "maintMarginRatio") AppendToArray(&result,[]interface{}{floorValue, maintenanceMarginPercentage}) } AddElementToObject(GetValue(this.Options, "leverageBrackets"), symbol, result) } } ch <- GetValue(this.Options, "leverageBrackets") return nil }() return ch } /** * @method * @name binance#fetchLeverageTiers * @description retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Notional-and-Leverage-Brackets * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Notional-Bracket-for-Symbol * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/UM-Notional-and-Leverage-Brackets * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/CM-Notional-and-Leverage-Brackets * @param {string[]|undefined} symbols list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch the leverage tiers for a portfolio margin account * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a dictionary of [leverage tiers structures]{@link https://docs.ccxt.com/#/?id=leverage-tiers-structure}, indexed by market symbols */ func (this *binance) FetchLeverageTiers(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 retRes105558 := (<-this.LoadMarkets()) PanicOnError(retRes105558) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchLeverageTiers", nil, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchLeverageTiers", nil, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchLeverageTiers", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmLeverageBracket(params)) PanicOnError(response) } else { response = (<-this.FapiPrivateGetLeverageBracket(params)) PanicOnError(response) } } else if IsTrue(this.IsInverse(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmLeverageBracket(params)) PanicOnError(response) } else { response = (<-this.DapiPrivateV2GetLeverageBracket(params)) PanicOnError(response) } } else { panic(NotSupported(Add(this.Id, " fetchLeverageTiers() supports linear and inverse contracts only"))) } // // usdm // // [ // { // "symbol": "SUSHIUSDT", // "brackets": [ // { // "bracket": 1, // "initialLeverage": 50, // "notionalCap": 50000, // "notionalFloor": 0, // "maintMarginRatio": 0.01, // "cum": 0.0 // }, // ... // ] // } // ] // // coinm // // [ // { // "symbol":"XRPUSD_210326", // "brackets":[ // { // "bracket":1, // "initialLeverage":20, // "qtyCap":500000, // "qtyFloor":0, // "maintMarginRatio":0.0185, // "cum":0.0 // } // ] // } // ] // ch <- this.ParseLeverageTiers(response, symbols, "symbol") return nil }() return ch } func (this *binance) ParseMarketLeverageTiers(info interface{}, optionalArgs ...interface{}) interface{} { /** * @ignore * @method * @param {object} info Exchange response for 1 market * @param {object} market CCXT market */ // // { // "symbol": "SUSHIUSDT", // "brackets": [ // { // "bracket": 1, // "initialLeverage": 50, // "notionalCap": 50000, // "notionalFloor": 0, // "maintMarginRatio": 0.01, // "cum": 0.0 // }, // ... // ] // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(info, "symbol") market = this.SafeMarket(marketId, market, nil, "contract") var brackets interface{} = this.SafeList(info, "brackets", []interface{}{}) var tiers interface{} = []interface{}{} for j := 0; IsLessThan(j, GetArrayLength(brackets)); j++ { var bracket interface{} = GetValue(brackets, j) AppendToArray(&tiers,map[string]interface{} { "tier": this.SafeNumber(bracket, "bracket"), "symbol": this.SafeSymbol(marketId, market), "currency": GetValue(market, "quote"), "minNotional": this.SafeNumber2(bracket, "notionalFloor", "qtyFloor"), "maxNotional": this.SafeNumber2(bracket, "notionalCap", "qtyCap"), "maintenanceMarginRate": this.SafeNumber(bracket, "maintMarginRatio"), "maxLeverage": this.SafeNumber(bracket, "initialLeverage"), "info": bracket, }) } return tiers } /** * @method * @name binance#fetchPosition * @description fetch data on an open position * @see https://developers.binance.com/docs/derivatives/option/trade/Option-Position-Information * @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 *binance) 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 retRes106728 := (<-this.LoadMarkets()) PanicOnError(retRes106728) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "option")) { panic(NotSupported(Add(this.Id, " fetchPosition() supports option markets only"))) } var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } response:= (<-this.EapiPrivateGetPosition(this.Extend(request, params))) PanicOnError(response) // // [ // { // "entryPrice": "27.70000000", // "symbol": "ETH-230426-1850-C", // "side": "LONG", // "quantity": "0.50000000", // "reducibleQty": "0.50000000", // "markValue": "10.250000000", // "ror": "-0.2599", // "unrealizedPNL": "-3.600000000", // "markPrice": "20.5", // "strikePrice": "1850.00000000", // "positionCost": "13.85000000", // "expiryDate": 1682496000000, // "priceScale": 1, // "quantityScale": 2, // "optionSide": "CALL", // "quoteAsset": "USDT", // "time": 1682492427106 // } // ] // ch <- this.ParsePosition(GetValue(response, 0), market) return nil }() return ch } /** * @method * @name binance#fetchOptionPositions * @description fetch data on open options positions * @see https://developers.binance.com/docs/derivatives/option/trade/Option-Position-Information * @param {string[]|undefined} symbols list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/#/?id=position-structure} */ func (this *binance) FetchOptionPositions(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 retRes107178 := (<-this.LoadMarkets()) PanicOnError(retRes107178) symbols = this.MarketSymbols(symbols) var request interface{} = map[string]interface{} {} var market interface{} = nil if IsTrue(!IsEqual(symbols, nil)) { var symbol interface{} = nil if IsTrue(IsArray(symbols)) { var symbolsLength interface{} = GetArrayLength(symbols) if IsTrue(IsGreaterThan(symbolsLength, 1)) { panic(BadRequest(Add(this.Id, " fetchPositions() symbols argument cannot contain more than 1 symbol"))) } symbol = GetValue(symbols, 0) } else { symbol = symbols } market = this.Market(symbol) AddElementToObject(request, "symbol", GetValue(market, "id")) } response:= (<-this.EapiPrivateGetPosition(this.Extend(request, params))) PanicOnError(response) // // [ // { // "entryPrice": "27.70000000", // "symbol": "ETH-230426-1850-C", // "side": "LONG", // "quantity": "0.50000000", // "reducibleQty": "0.50000000", // "markValue": "10.250000000", // "ror": "-0.2599", // "unrealizedPNL": "-3.600000000", // "markPrice": "20.5", // "strikePrice": "1850.00000000", // "positionCost": "13.85000000", // "expiryDate": 1682496000000, // "priceScale": 1, // "quantityScale": 2, // "optionSide": "CALL", // "quoteAsset": "USDT", // "time": 1682492427106 // } // ] // var result interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { AppendToArray(&result,this.ParsePosition(GetValue(response, i), market)) } ch <- this.FilterByArrayPositions(result, "symbol", symbols, false) return nil }() return ch } func (this *binance) ParsePosition(position interface{}, optionalArgs ...interface{}) interface{} { // // { // "entryPrice": "27.70000000", // "symbol": "ETH-230426-1850-C", // "side": "LONG", // "quantity": "0.50000000", // "reducibleQty": "0.50000000", // "markValue": "10.250000000", // "ror": "-0.2599", // "unrealizedPNL": "-3.600000000", // "markPrice": "20.5", // "strikePrice": "1850.00000000", // "positionCost": "13.85000000", // "expiryDate": 1682496000000, // "priceScale": 1, // "quantityScale": 2, // "optionSide": "CALL", // "quoteAsset": "USDT", // "time": 1682492427106 // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(position, "symbol") market = this.SafeMarket(marketId, market, nil, "swap") var symbol interface{} = GetValue(market, "symbol") var side interface{} = this.SafeStringLower(position, "side") var quantity interface{} = this.SafeString(position, "quantity") if IsTrue(!IsEqual(side, "long")) { quantity = Precise.StringMul("-1", quantity) } var timestamp interface{} = this.SafeInteger(position, "time") return this.SafePosition(map[string]interface{} { "info": position, "id": nil, "symbol": symbol, "entryPrice": this.SafeNumber(position, "entryPrice"), "markPrice": this.SafeNumber(position, "markPrice"), "notional": this.SafeNumber(position, "markValue"), "collateral": this.SafeNumber(position, "positionCost"), "unrealizedPnl": this.SafeNumber(position, "unrealizedPNL"), "side": side, "contracts": this.ParseNumber(quantity), "contractSize": nil, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "hedged": nil, "maintenanceMargin": nil, "maintenanceMarginPercentage": nil, "initialMargin": nil, "initialMarginPercentage": nil, "leverage": nil, "liquidationPrice": nil, "marginRatio": nil, "marginMode": nil, "percentage": nil, }) } /** * @method * @name binance#fetchPositions * @description fetch all open positions * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Information-V2 * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Account-Information * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Position-Information-V2 * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Position-Information * @see https://developers.binance.com/docs/derivatives/option/trade/Option-Position-Information * @param {string[]} [symbols] list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {object} [params.params] extra parameters specific to the exchange API endpoint * @param {string} [params.method] method name to call, "positionRisk", "account" or "option", default is "positionRisk" * @param {bool} [params.useV2] set to true if you want to use the obsolete endpoint, where some more additional fields were provided * @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/#/?id=position-structure} */ func (this *binance) 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 var defaultMethod interface{} = nil defaultMethodparamsVariable := this.HandleOptionAndParams(params, "fetchPositions", "method"); defaultMethod = GetValue(defaultMethodparamsVariable,0); params = GetValue(defaultMethodparamsVariable,1) if IsTrue(IsEqual(defaultMethod, nil)) { var options interface{} = this.SafeDict(this.Options, "fetchPositions") if IsTrue(IsEqual(options, nil)) { defaultMethod = this.SafeString(this.Options, "fetchPositions", "positionRisk") } else { defaultMethod = "positionRisk" } } if IsTrue(IsEqual(defaultMethod, "positionRisk")) { retRes1085219 := (<-this.FetchPositionsRisk(symbols, params)) PanicOnError(retRes1085219) ch <- retRes1085219 return nil } else if IsTrue(IsEqual(defaultMethod, "account")) { retRes1085419 := (<-this.FetchAccountPositions(symbols, params)) PanicOnError(retRes1085419) ch <- retRes1085419 return nil } else if IsTrue(IsEqual(defaultMethod, "option")) { retRes1085619 := (<-this.FetchOptionPositions(symbols, params)) PanicOnError(retRes1085619) ch <- retRes1085619 return nil } else { panic(NotSupported(Add(Add(Add(this.Id, ".options[\"fetchPositions\"][\"method\"] or params[\"method\"] = \""), defaultMethod), "\" is invalid, please choose between \"account\", \"positionRisk\" and \"option\""))) } return nil }() return ch } /** * @method * @name binance#fetchAccountPositions * @ignore * @description fetch account positions * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Information-V2 * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Account-Information * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Position-Information-V2 * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Position-Information * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Information-V3 * @param {string[]} [symbols] list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch positions in a portfolio margin account * @param {string} [params.subType] "linear" or "inverse" * @param {boolean} [params.filterClosed] set to true if you would like to filter out closed positions, default is false * @param {boolean} [params.useV2] set to true if you want to use obsolete endpoint, where some more additional fields were provided * @returns {object} data on account positions */ func (this *binance) FetchAccountPositions(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 if IsTrue(!IsEqual(symbols, nil)) { if !IsTrue(IsArray(symbols)) { panic(ArgumentsRequired(Add(this.Id, " fetchPositions() requires an array argument for symbols"))) } } retRes108868 := (<-this.LoadMarkets()) PanicOnError(retRes108868) retRes108878 := (<-this.LoadLeverageBrackets(false, params)) PanicOnError(retRes108878) var defaultType interface{} = this.SafeString(this.Options, "defaultType", "future") var typeVar interface{} = this.SafeString(params, "type", defaultType) params = this.Omit(params, "type") var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchAccountPositions", nil, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchAccountPositions", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmAccount(params)) PanicOnError(response) } else { var useV2 interface{} = nil useV2paramsVariable := this.HandleOptionAndParams(params, "fetchAccountPositions", "useV2", false); useV2 = GetValue(useV2paramsVariable,0); params = GetValue(useV2paramsVariable,1) if !IsTrue(useV2) { response = (<-this.FapiPrivateV3GetAccount(params)) PanicOnError(response) } else { response = (<-this.FapiPrivateV2GetAccount(params)) PanicOnError(response) } } } else if IsTrue(this.IsInverse(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmAccount(params)) PanicOnError(response) } else { response = (<-this.DapiPrivateGetAccount(params)) PanicOnError(response) } } else { panic(NotSupported(Add(this.Id, " fetchPositions() supports linear and inverse contracts only"))) } var filterClosed interface{} = nil filterClosedparamsVariable := this.HandleOptionAndParams(params, "fetchAccountPositions", "filterClosed", false); filterClosed = GetValue(filterClosedparamsVariable,0); params = GetValue(filterClosedparamsVariable,1) var result interface{} = this.ParseAccountPositions(response, filterClosed) symbols = this.MarketSymbols(symbols) ch <- this.FilterByArrayPositions(result, "symbol", symbols, false) return nil }() return ch } /** * @method * @name binance#fetchPositionsRisk * @ignore * @description fetch positions risk * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Position-Information-V2 * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Position-Information * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-UM-Position-Information * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-CM-Position-Information * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Position-Information-V3 * @param {string[]|undefined} symbols list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch positions for a portfolio margin account * @param {string} [params.subType] "linear" or "inverse" * @param {bool} [params.useV2] set to true if you want to use the obsolete endpoint, where some more additional fields were provided * @returns {object} data on the positions risk */ func (this *binance) FetchPositionsRisk(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 if IsTrue(!IsEqual(symbols, nil)) { if !IsTrue(IsArray(symbols)) { panic(ArgumentsRequired(Add(this.Id, " fetchPositionsRisk() requires an array argument for symbols"))) } } retRes110138 := (<-this.LoadMarkets()) PanicOnError(retRes110138) retRes110148 := (<-this.LoadLeverageBrackets(false, params)) PanicOnError(retRes110148) var request interface{} = map[string]interface{} {} var defaultType interface{} = "future" defaultType = this.SafeString(this.Options, "defaultType", defaultType) var typeVar interface{} = this.SafeString(params, "type", defaultType) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchPositionsRisk", nil, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchPositionsRisk", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) params = this.Omit(params, "type") var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmPositionRisk(this.Extend(request, params))) PanicOnError(response) } else { var useV2 interface{} = nil useV2paramsVariable := this.HandleOptionAndParams(params, "fetchPositionsRisk", "useV2", false); useV2 = GetValue(useV2paramsVariable,0); params = GetValue(useV2paramsVariable,1) params = this.Extend(request, params) if !IsTrue(useV2) { response = (<-this.FapiPrivateV3GetPositionRisk(params)) PanicOnError(response) } else { response = (<-this.FapiPrivateV2GetPositionRisk(params)) PanicOnError(response) } } } else if IsTrue(this.IsInverse(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmPositionRisk(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivateGetPositionRisk(this.Extend(request, params))) PanicOnError(response) } } else { panic(NotSupported(Add(this.Id, " fetchPositionsRisk() supports linear and inverse contracts only"))) } // ### Response examples ### // // For One-way position mode: // // [ // { // "symbol": "BTCUSDT", // "positionSide": "BOTH", // "positionAmt": "0.000", // "entryPrice": "0.00000", // "markPrice": "6679.50671178", // "unRealizedProfit": "0.00000000", // "liquidationPrice": "0", // "isolatedMargin": "0.00000000", // "marginType": "isolated", // "isAutoAddMargin": "false", // "leverage": "10", // "maxNotionalValue": "20000000", // "updateTime": 0 // } // ] // // For Hedge position mode: // // [ // { // "entryPrice": "6563.66500", // "marginType": "isolated", // "isAutoAddMargin": "false", // "isolatedMargin": "15517.54150468", // "leverage": "10", // "liquidationPrice": "5930.78", // "markPrice": "6679.50671178", // "maxNotionalValue": "20000000", // "positionSide": "LONG", // "positionAmt": "20.000", // negative value for 'SHORT' // "symbol": "BTCUSDT", // "unRealizedProfit": "2316.83423560" // "updateTime": 1625474304765 // }, // .. second dict is similar, but with `positionSide: SHORT` // ] // // inverse portfolio margin: // // [ // { // "symbol": "ETHUSD_PERP", // "positionAmt": "1", // "entryPrice": "2422.400000007", // "markPrice": "2424.51267823", // "unRealizedProfit": "0.0000036", // "liquidationPrice": "293.57678898", // "leverage": "100", // "positionSide": "LONG", // "updateTime": 1707371941861, // "maxQty": "15", // "notionalValue": "0.00412454", // "breakEvenPrice": "2423.368960034" // } // ] // // linear portfolio margin: // // [ // { // "symbol": "BTCUSDT", // "positionAmt": "0.01", // "entryPrice": "44525.0", // "markPrice": "45464.1735922", // "unRealizedProfit": "9.39173592", // "liquidationPrice": "38007.16308568", // "leverage": "100", // "positionSide": "LONG", // "updateTime": 1707371879042, // "maxNotionalValue": "500000.0", // "notional": "454.64173592", // "breakEvenPrice": "44542.81" // } // ] // var result interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var rawPosition interface{} = GetValue(response, i) var entryPriceString interface{} = this.SafeString(rawPosition, "entryPrice") if IsTrue(Precise.StringGt(entryPriceString, "0")) { AppendToArray(&result,this.ParsePositionRisk(GetValue(response, i))) } } symbols = this.MarketSymbols(symbols) ch <- this.FilterByArrayPositions(result, "symbol", symbols, false) return nil }() return ch } /** * @method * @name binance#fetchFundingHistory * @description fetch the history of funding payments paid and received on this account * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Income-History * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Get-Income-History * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Income-History * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-CM-Income-History * @param {string} symbol unified market symbol * @param {int} [since] the earliest time in ms to fetch funding history for * @param {int} [limit] the maximum number of funding history structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.until] timestamp in ms of the latest funding history entry * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch the funding history for a portfolio margin account * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a [funding history structure]{@link https://docs.ccxt.com/#/?id=funding-history-structure} */ func (this *binance) FetchFundingHistory(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 retRes111848 := (<-this.LoadMarkets()) PanicOnError(retRes111848) var market interface{} = nil var request interface{} = map[string]interface{} { "incomeType": "FUNDING_FEE", } if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) AddElementToObject(request, "symbol", GetValue(market, "id")) if !IsTrue(GetValue(market, "swap")) { panic(NotSupported(Add(this.Id, " fetchFundingHistory() supports swap contracts only"))) } } var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchFundingHistory", market, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchFundingHistory", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) requestparamsVariable := this.HandleUntilOption("endTime", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } var defaultType interface{} = this.SafeString2(this.Options, "fetchFundingHistory", "defaultType", "future") var typeVar interface{} = this.SafeString(params, "type", defaultType) params = this.Omit(params, "type") var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmIncome(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPrivateGetIncome(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(this.IsInverse(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmIncome(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivateGetIncome(this.Extend(request, params))) PanicOnError(response) } } else { panic(NotSupported(Add(this.Id, " fetchFundingHistory() supports linear and inverse contracts only"))) } ch <- this.ParseIncomes(response, market, since, limit) return nil }() return ch } /** * @method * @name binance#setLeverage * @description set the level of leverage for a market * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Change-Initial-Leverage * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Change-Initial-Leverage * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Change-UM-Initial-Leverage * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Change-CM-Initial-Leverage * @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 {boolean} [params.portfolioMargin] set to true if you would like to set the leverage for a trading pair in a portfolio margin account * @returns {object} response from the exchange */ func (this *binance) 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"))) } // WARNING: THIS WILL INCREASE LIQUIDATION PRICE FOR OPEN ISOLATED LONG POSITIONS // AND DECREASE LIQUIDATION PRICE FOR OPEN ISOLATED SHORT POSITIONS if IsTrue(IsTrue((IsLessThan(leverage, 1))) || IsTrue((IsGreaterThan(leverage, 125)))) { panic(BadRequest(Add(this.Id, " leverage should be between 1 and 125"))) } retRes112528 := (<-this.LoadMarkets()) PanicOnError(retRes112528) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), "leverage": leverage, } var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "setLeverage", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var response interface{} = nil if IsTrue(GetValue(market, "linear")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiPostUmLeverage(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPrivatePostLeverage(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(GetValue(market, "inverse")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiPostCmLeverage(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivatePostLeverage(this.Extend(request, params))) PanicOnError(response) } } else { panic(NotSupported(Add(this.Id, " setLeverage() supports linear and inverse contracts only"))) } ch <- response return nil }() return ch } /** * @method * @name binance#setMarginMode * @description set margin mode to 'cross' or 'isolated' * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Change-Margin-Type * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Change-Margin-Type * @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 *binance) 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"))) } // // { "code": -4048 , "msg": "Margin type cannot be changed if there exists position." } // // or // // { "code": 200, "msg": "success" } // 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, " marginMode must be either isolated or cross"))) } retRes113088 := (<-this.LoadMarkets()) PanicOnError(retRes113088) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), "marginType": marginMode, } var response interface{} = nil { ret__ := func(this *binance) (ret_ interface{}) { defer func() { if e := recover(); e != nil { if e == "break" { return } ret_ = func(this *binance) interface{} { // catch block: // not an error // https://github.com/ccxt/ccxt/issues/11268 // https://github.com/ccxt/ccxt/pull/11624 // POST https://fapi.binance.com/fapi/v1/marginType 400 Bad Request // binanceusdm if IsTrue(IsInstance(e, MarginModeAlreadySet)) { var throwMarginModeAlreadySet interface{} = this.SafeBool(this.Options, "throwMarginModeAlreadySet", false) if IsTrue(throwMarginModeAlreadySet) { panic(e) } else { response = map[string]interface{} { "code": OpNeg(4046), "msg": "No need to change margin type.", } } } else { panic(e) } return nil }(this) } }() // try block: if IsTrue(GetValue(market, "linear")) { response = (<-this.FapiPrivatePostMarginType(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPrivatePostMarginType(this.Extend(request, params))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " setMarginMode() supports linear and inverse contracts only"))) } return nil }(this) if ret__ != nil { return ret__ } } ch <- response return nil }() return ch } /** * @method * @name binance#setPositionMode * @description set hedged to true or false for a market * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Change-Position-Mode * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Change-Position-Mode * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Current-Position-Mode * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-CM-Current-Position-Mode * @param {bool} hedged set to true to use dualSidePosition * @param {string} symbol not used by binance setPositionMode () * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to set the position mode for a portfolio margin account * @param {string} [params.subType] "linear" or "inverse" * @returns {object} response from the exchange */ func (this *binance) 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 defaultType interface{} = this.SafeString(this.Options, "defaultType", "future") var typeVar interface{} = this.SafeString(params, "type", defaultType) params = this.Omit(params, []interface{}{"type"}) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("setPositionMode", nil, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "setPositionMode", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var dualSidePosition interface{} = nil if IsTrue(hedged) { dualSidePosition = "true" } else { dualSidePosition = "false" } var request interface{} = map[string]interface{} { "dualSidePosition": dualSidePosition, } var response interface{} = nil if IsTrue(this.IsInverse(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiPostCmPositionSideDual(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivatePostPositionSideDual(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(this.IsLinear(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiPostUmPositionSideDual(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPrivatePostPositionSideDual(this.Extend(request, params))) PanicOnError(response) } } else { panic(BadRequest(Add(this.Id, " setPositionMode() supports linear and inverse contracts only"))) } // // { // "code": 200, // "msg": "success" // } // ch <- response return nil }() return ch } /** * @method * @name binance#fetchLeverages * @description fetch the set leverage for all markets * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Information-V2 * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Account-Information * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Account-Detail * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-CM-Account-Detail * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Symbol-Config * @param {string[]} [symbols] a list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a list of [leverage structures]{@link https://docs.ccxt.com/#/?id=leverage-structure} */ func (this *binance) FetchLeverages(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 retRes114158 := (<-this.LoadMarkets()) PanicOnError(retRes114158) retRes114168 := (<-this.LoadLeverageBrackets(false, params)) PanicOnError(retRes114168) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchLeverages", nil, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchLeverages", nil, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchLeverages", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmAccount(params)) PanicOnError(response) } else { response = (<-this.FapiPrivateGetSymbolConfig(params)) PanicOnError(response) } } else if IsTrue(this.IsInverse(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmAccount(params)) PanicOnError(response) } else { response = (<-this.DapiPrivateGetAccount(params)) PanicOnError(response) } } else { panic(NotSupported(Add(this.Id, " fetchLeverages() supports linear and inverse contracts only"))) } var leverages interface{} = this.SafeList(response, "positions", []interface{}{}) if IsTrue(IsArray(response)) { leverages = response } ch <- this.ParseLeverages(leverages, symbols, "symbol") return nil }() return ch } func (this *binance) ParseLeverage(leverage interface{}, optionalArgs ...interface{}) interface{} { market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(leverage, "symbol") var marginModeRaw interface{} = this.SafeBool(leverage, "isolated") var marginMode interface{} = nil if IsTrue(!IsEqual(marginModeRaw, nil)) { marginMode = Ternary(IsTrue(marginModeRaw), "isolated", "cross") } var marginTypeRaw interface{} = this.SafeStringLower(leverage, "marginType") if IsTrue(!IsEqual(marginTypeRaw, nil)) { marginMode = Ternary(IsTrue((IsEqual(marginTypeRaw, "crossed"))), "cross", "isolated") } var side interface{} = this.SafeStringLower(leverage, "positionSide") var longLeverage interface{} = nil var shortLeverage interface{} = nil var leverageValue interface{} = this.SafeInteger(leverage, "leverage") if IsTrue(IsTrue((IsEqual(side, nil))) || IsTrue((IsEqual(side, "both")))) { longLeverage = leverageValue shortLeverage = leverageValue } else if IsTrue(IsEqual(side, "long")) { longLeverage = leverageValue } else if IsTrue(IsEqual(side, "short")) { shortLeverage = leverageValue } return map[string]interface{} { "info": leverage, "symbol": this.SafeSymbol(marketId, market), "marginMode": marginMode, "longLeverage": longLeverage, "shortLeverage": shortLeverage, } } /** * @method * @name binance#fetchSettlementHistory * @description fetches historical settlement records * @see https://developers.binance.com/docs/derivatives/option/market-data/Historical-Exercise-Records * @param {string} symbol unified market symbol of the settlement history * @param {int} [since] timestamp in ms * @param {int} [limit] number of records, default 100, max 100 * @param {object} [params] exchange specific params * @returns {object[]} a list of [settlement history objects]{@link https://docs.ccxt.com/#/?id=settlement-history-structure} */ func (this *binance) FetchSettlementHistory(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 retRes114908 := (<-this.LoadMarkets()) PanicOnError(retRes114908) var market interface{} = Ternary(IsTrue((IsEqual(symbol, nil))), nil, this.Market(symbol)) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchSettlementHistory", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) if IsTrue(!IsEqual(typeVar, "option")) { panic(NotSupported(Add(this.Id, " fetchSettlementHistory() supports option markets only"))) } var request interface{} = map[string]interface{} {} if IsTrue(!IsEqual(symbol, nil)) { symbol = GetValue(market, "symbol") AddElementToObject(request, "underlying", Add(GetValue(market, "baseId"), GetValue(market, "quoteId"))) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } response:= (<-this.EapiPublicGetExerciseHistory(this.Extend(request, params))) PanicOnError(response) // // [ // { // "symbol": "ETH-230223-1900-P", // "strikePrice": "1900", // "realStrikePrice": "1665.5897334", // "expiryDate": 1677139200000, // "strikeResult": "REALISTIC_VALUE_STRICKEN" // } // ] // var settlements interface{} = this.ParseSettlements(response, market) var sorted interface{} = this.SortBy(settlements, "timestamp") ch <- this.FilterBySymbolSinceLimit(sorted, symbol, since, limit) return nil }() return ch } /** * @method * @name binance#fetchMySettlementHistory * @description fetches historical settlement records of the user * @see https://developers.binance.com/docs/derivatives/option/trade/User-Exercise-Record * @param {string} symbol unified market symbol of the settlement history * @param {int} [since] timestamp in ms * @param {int} [limit] number of records * @param {object} [params] exchange specific params * @returns {object[]} a list of [settlement history objects] */ func (this *binance) FetchMySettlementHistory(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 retRes115378 := (<-this.LoadMarkets()) PanicOnError(retRes115378) var market interface{} = Ternary(IsTrue((IsEqual(symbol, nil))), nil, this.Market(symbol)) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchMySettlementHistory", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) if IsTrue(!IsEqual(typeVar, "option")) { panic(NotSupported(Add(this.Id, " fetchMySettlementHistory() supports option markets only"))) } var request interface{} = map[string]interface{} {} if IsTrue(!IsEqual(symbol, nil)) { AddElementToObject(request, "symbol", GetValue(market, "id")) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } response:= (<-this.EapiPrivateGetExerciseRecord(this.Extend(request, params))) PanicOnError(response) // // [ // { // "id": "1125899906842897036", // "currency": "USDT", // "symbol": "BTC-230728-30000-C", // "exercisePrice": "30000.00000000", // "markPrice": "29160.71284993", // "quantity": "1.00000000", // "amount": "0.00000000", // "fee": "0.00000000", // "createDate": 1690531200000, // "priceScale": 0, // "quantityScale": 2, // "optionSide": "CALL", // "positionSide": "LONG", // "quoteAsset": "USDT" // } // ] // var settlements interface{} = this.ParseSettlements(response, market) var sorted interface{} = this.SortBy(settlements, "timestamp") ch <- this.FilterBySymbolSinceLimit(sorted, GetValue(market, "symbol"), since, limit) return nil }() return ch } func (this *binance) ParseSettlement(settlement interface{}, market interface{}) interface{} { // // fetchSettlementHistory // // { // "symbol": "ETH-230223-1900-P", // "strikePrice": "1900", // "realStrikePrice": "1665.5897334", // "expiryDate": 1677139200000, // "strikeResult": "REALISTIC_VALUE_STRICKEN" // } // // fetchMySettlementHistory // // { // "id": "1125899906842897036", // "currency": "USDT", // "symbol": "BTC-230728-30000-C", // "exercisePrice": "30000.00000000", // "markPrice": "29160.71284993", // "quantity": "1.00000000", // "amount": "0.00000000", // "fee": "0.00000000", // "createDate": 1690531200000, // "priceScale": 0, // "quantityScale": 2, // "optionSide": "CALL", // "positionSide": "LONG", // "quoteAsset": "USDT" // } // var timestamp interface{} = this.SafeInteger2(settlement, "expiryDate", "createDate") var marketId interface{} = this.SafeString(settlement, "symbol") return map[string]interface{} { "info": settlement, "symbol": this.SafeSymbol(marketId, market), "price": this.SafeNumber2(settlement, "realStrikePrice", "exercisePrice"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), } } func (this *binance) ParseSettlements(settlements interface{}, market interface{}) interface{} { // // fetchSettlementHistory // // [ // { // "symbol": "ETH-230223-1900-P", // "strikePrice": "1900", // "realStrikePrice": "1665.5897334", // "expiryDate": 1677139200000, // "strikeResult": "EXTRINSIC_VALUE_EXPIRED" // } // ] // // fetchMySettlementHistory // // [ // { // "id": "1125899906842897036", // "currency": "USDT", // "symbol": "BTC-230728-30000-C", // "exercisePrice": "30000.00000000", // "markPrice": "29160.71284993", // "quantity": "1.00000000", // "amount": "0.00000000", // "fee": "0.00000000", // "createDate": 1690531200000, // "priceScale": 0, // "quantityScale": 2, // "optionSide": "CALL", // "positionSide": "LONG", // "quoteAsset": "USDT" // } // ] // var result interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(settlements)); i++ { AppendToArray(&result,this.ParseSettlement(GetValue(settlements, i), market)) } return result } /** * @method * @name binance#fetchLedgerEntry * @description fetch the history of changes, actions done by the user or operations that altered the balance of the user * @see https://developers.binance.com/docs/derivatives/option/account/Account-Funding-Flow * @param {string} id the identification number of the ledger entry * @param {string} code unified currency code * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [ledger structure]{@link https://docs.ccxt.com/#/?id=ledger} */ func (this *binance) FetchLedgerEntry(id interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) code := GetArg(optionalArgs, 0, nil) _ = code params := GetArg(optionalArgs, 1, map[string]interface{} {}) _ = params retRes116758 := (<-this.LoadMarkets()) PanicOnError(retRes116758) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchLedgerEntry", nil, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) if IsTrue(!IsEqual(typeVar, "option")) { panic(BadRequest(Add(this.Id, " fetchLedgerEntry() can only be used for type option"))) } this.CheckRequiredArgument("fetchLedgerEntry", code, "code") var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "recordId": id, "currency": GetValue(currency, "id"), } response:= (<-this.EapiPrivateGetBill(this.Extend(request, params))) PanicOnError(response) // // [ // { // "id": "1125899906845701870", // "asset": "USDT", // "amount": "-0.16518203", // "type": "FEE", // "createDate": 1676621042489 // } // ] // var first interface{} = this.SafeDict(response, 0, response) ch <- this.ParseLedgerEntry(first, currency) return nil }() return ch } /** * @method * @name binance#fetchLedger * @description fetch the history of changes, actions done by the user or operations that altered the balance of the user * @see https://developers.binance.com/docs/derivatives/option/account/Account-Funding-Flow * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Income-History * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Get-Income-History * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Income-History * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-CM-Income-History * @param {string} [code] unified currency code * @param {int} [since] timestamp in ms of the earliest ledger entry * @param {int} [limit] max number of ledger entries to return * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.until] timestamp in ms of the latest ledger entry * @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) * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch the ledger for a portfolio margin account * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a [ledger structure]{@link https://docs.ccxt.com/#/?id=ledger} */ func (this *binance) FetchLedger(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 retRes117238 := (<-this.LoadMarkets()) PanicOnError(retRes117238) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchLedger", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes1172719 := (<-this.FetchPaginatedCallDynamic("fetchLedger", code, since, limit, params, nil, false)) PanicOnError(retRes1172719) ch <- retRes1172719 return nil } var typeVar interface{} = nil var subType interface{} = nil var currency interface{} = nil if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) } var request interface{} = map[string]interface{} {} typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchLedger", nil, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) subTypeparamsVariable := this.HandleSubTypeAndParams("fetchLedger", nil, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } var until interface{} = this.SafeInteger(params, "until") if IsTrue(!IsEqual(until, nil)) { params = this.Omit(params, "until") AddElementToObject(request, "endTime", until) } var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchLedger", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var response interface{} = nil if IsTrue(IsEqual(typeVar, "option")) { this.CheckRequiredArgument("fetchLedger", code, "code") AddElementToObject(request, "currency", GetValue(currency, "id")) response = (<-this.EapiPrivateGetBill(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(this.IsLinear(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmIncome(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPrivateGetIncome(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(this.IsInverse(typeVar, subType)) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmIncome(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivateGetIncome(this.Extend(request, params))) PanicOnError(response) } } else { panic(NotSupported(Add(this.Id, " fetchLedger() supports contract wallets only"))) } // // options (eapi) // // [ // { // "id": "1125899906845701870", // "asset": "USDT", // "amount": "-0.16518203", // "type": "FEE", // "createDate": 1676621042489 // } // ] // // futures (fapi, dapi, papi) // // [ // { // "symbol": "", // "incomeType": "TRANSFER", // "income": "10.00000000", // "asset": "USDT", // "time": 1677645250000, // "info": "TRANSFER", // "tranId": 131001573082, // "tradeId": "" // } // ] // ch <- this.ParseLedger(response, currency, since, limit) return nil }() return ch } func (this *binance) ParseLedgerEntry(item interface{}, optionalArgs ...interface{}) interface{} { // // options (eapi) // // { // "id": "1125899906845701870", // "asset": "USDT", // "amount": "-0.16518203", // "type": "FEE", // "createDate": 1676621042489 // } // // futures (fapi, dapi, papi) // // { // "symbol": "", // "incomeType": "TRANSFER", // "income": "10.00000000", // "asset": "USDT", // "time": 1677645250000, // "info": "TRANSFER", // "tranId": 131001573082, // "tradeId": "" // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var amount interface{} = this.SafeString2(item, "amount", "income") var direction interface{} = nil if IsTrue(Precise.StringLe(amount, "0")) { direction = "out" amount = Precise.StringMul("-1", amount) } else { direction = "in" } var currencyId interface{} = this.SafeString(item, "asset") var code interface{} = this.SafeCurrencyCode(currencyId, currency) currency = this.SafeCurrency(currencyId, currency) var timestamp interface{} = this.SafeInteger2(item, "createDate", "time") var typeVar interface{} = this.SafeString2(item, "type", "incomeType") return this.SafeLedgerEntry(map[string]interface{} { "info": item, "id": this.SafeString2(item, "id", "tranId"), "direction": direction, "account": nil, "referenceAccount": nil, "referenceId": this.SafeString(item, "tradeId"), "type": this.ParseLedgerEntryType(typeVar), "currency": code, "amount": this.ParseNumber(amount), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "before": nil, "after": nil, "status": nil, "fee": nil, }, currency) } func (this *binance) ParseLedgerEntryType(typeVar interface{}) interface{} { var ledgerType interface{} = map[string]interface{} { "FEE": "fee", "FUNDING_FEE": "fee", "OPTIONS_PREMIUM_FEE": "fee", "POSITION_LIMIT_INCREASE_FEE": "fee", "CONTRACT": "trade", "REALIZED_PNL": "trade", "TRANSFER": "transfer", "CROSS_COLLATERAL_TRANSFER": "transfer", "INTERNAL_TRANSFER": "transfer", "COIN_SWAP_DEPOSIT": "deposit", "COIN_SWAP_WITHDRAW": "withdrawal", "OPTIONS_SETTLE_PROFIT": "settlement", "DELIVERED_SETTELMENT": "settlement", "WELCOME_BONUS": "cashback", "CONTEST_REWARD": "cashback", "COMMISSION_REBATE": "rebate", "API_REBATE": "rebate", "REFERRAL_KICKBACK": "referral", "COMMISSION": "commission", } return this.SafeString(ledgerType, typeVar, typeVar) } func (this *binance) Sign(path interface{}, optionalArgs ...interface{}) interface{} { api := GetArg(optionalArgs, 0, "public") _ = api 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 urls interface{} = this.Urls if !IsTrue((InOp(GetValue(urls, "api"), api))) { panic(NotSupported(Add(Add(Add(this.Id, " does not have a testnet/sandbox URL for "), api), " endpoints"))) } var url interface{} = GetValue(GetValue(this.Urls, "api"), api) url = Add(url, Add("/", path)) if IsTrue(IsEqual(path, "historicalTrades")) { if IsTrue(this.ApiKey) { headers = map[string]interface{} { "X-MBX-APIKEY": this.ApiKey, } } else { panic(AuthenticationError(Add(this.Id, " historicalTrades endpoint requires `apiKey` credential"))) } } var userDataStream interface{} = IsTrue((IsEqual(path, "userDataStream"))) || IsTrue((IsEqual(path, "listenKey"))) if IsTrue(userDataStream) { if IsTrue(this.ApiKey) { // v1 special case for userDataStream headers = map[string]interface{} { "X-MBX-APIKEY": this.ApiKey, "Content-Type": "application/x-www-form-urlencoded", } if IsTrue(!IsEqual(method, "GET")) { body = this.Urlencode(params) } } else { panic(AuthenticationError(Add(this.Id, " userDataStream endpoint requires `apiKey` credential"))) } } else if IsTrue(IsTrue(IsTrue(IsTrue(IsTrue(IsTrue(IsTrue(IsTrue(IsTrue(IsTrue(IsTrue(IsTrue((IsEqual(api, "private"))) || IsTrue((IsEqual(api, "eapiPrivate")))) || IsTrue((IsTrue(IsEqual(api, "sapi")) && IsTrue(!IsEqual(path, "system/status"))))) || IsTrue((IsEqual(api, "sapiV2")))) || IsTrue((IsEqual(api, "sapiV3")))) || IsTrue((IsEqual(api, "sapiV4")))) || IsTrue((IsEqual(api, "dapiPrivate")))) || IsTrue((IsEqual(api, "dapiPrivateV2")))) || IsTrue((IsEqual(api, "fapiPrivate")))) || IsTrue((IsEqual(api, "fapiPrivateV2")))) || IsTrue((IsEqual(api, "fapiPrivateV3")))) || IsTrue((IsTrue(IsEqual(api, "papi")) && IsTrue(!IsEqual(path, "ping"))))) { this.CheckRequiredCredentials() if IsTrue(IsTrue(IsEqual(method, "POST")) && IsTrue((IsTrue((IsEqual(path, "order"))) || IsTrue((IsEqual(path, "sor/order")))))) { // inject in implicit API calls var newClientOrderId interface{} = this.SafeString(params, "newClientOrderId") if IsTrue(IsEqual(newClientOrderId, nil)) { var isSpotOrMargin interface{} = (IsTrue(IsGreaterThan(GetIndexOf(api, "sapi"), OpNeg(1))) || IsTrue(IsEqual(api, "private"))) var marketType interface{} = Ternary(IsTrue(isSpotOrMargin), "spot", "future") var defaultId interface{} = Ternary(IsTrue((!IsTrue(isSpotOrMargin))), "x-xcKtGhcu", "x-R4BD3S82") var broker interface{} = this.SafeDict(this.Options, "broker", map[string]interface{} {}) var brokerId interface{} = this.SafeString(broker, marketType, defaultId) AddElementToObject(params, "newClientOrderId", Add(brokerId, this.Uuid22())) } } var query interface{} = nil // handle batchOrders if IsTrue(IsTrue((IsEqual(path, "batchOrders"))) && IsTrue((IsTrue((IsEqual(method, "POST"))) || IsTrue((IsEqual(method, "PUT")))))) { var batchOrders interface{} = this.SafeValue(params, "batchOrders") var queryBatch interface{} = (this.Json(batchOrders)) AddElementToObject(params, "batchOrders", queryBatch) } var defaultRecvWindow interface{} = this.SafeInteger(this.Options, "recvWindow") var extendedParams interface{} = this.Extend(map[string]interface{} { "timestamp": this.Nonce(), }, params) if IsTrue(!IsEqual(defaultRecvWindow, nil)) { AddElementToObject(extendedParams, "recvWindow", defaultRecvWindow) } var recvWindow interface{} = this.SafeInteger(params, "recvWindow") if IsTrue(!IsEqual(recvWindow, nil)) { AddElementToObject(extendedParams, "recvWindow", recvWindow) } if IsTrue(IsTrue((IsEqual(api, "sapi"))) && IsTrue((IsEqual(path, "asset/dust")))) { query = this.UrlencodeWithArrayRepeat(extendedParams) } else if IsTrue(IsTrue(IsTrue(IsTrue(IsTrue((IsEqual(path, "batchOrders"))) || IsTrue((IsGreaterThanOrEqual(GetIndexOf(path, "sub-account"), 0)))) || IsTrue((IsEqual(path, "capital/withdraw/apply")))) || IsTrue((IsGreaterThanOrEqual(GetIndexOf(path, "staking"), 0)))) || IsTrue((IsGreaterThanOrEqual(GetIndexOf(path, "simple-earn"), 0)))) { if IsTrue(IsTrue((IsEqual(method, "DELETE"))) && IsTrue((IsEqual(path, "batchOrders")))) { var orderidlist interface{} = this.SafeList(extendedParams, "orderidlist", []interface{}{}) var origclientorderidlist interface{} = this.SafeList(extendedParams, "origclientorderidlist", []interface{}{}) extendedParams = this.Omit(extendedParams, []interface{}{"orderidlist", "origclientorderidlist"}) query = this.Rawencode(extendedParams) var orderidlistLength interface{} = GetArrayLength(orderidlist) var origclientorderidlistLength interface{} = GetArrayLength(origclientorderidlist) if IsTrue(IsGreaterThan(orderidlistLength, 0)) { query = Add(Add(Add(Add(query, "&"), "orderidlist=%5B"), Join(orderidlist, "%2C")), "%5D") } if IsTrue(IsGreaterThan(origclientorderidlistLength, 0)) { query = Add(Add(Add(Add(query, "&"), "origclientorderidlist=%5B"), Join(origclientorderidlist, "%2C")), "%5D") } } else { query = this.Rawencode(extendedParams) } } else { query = this.Urlencode(extendedParams) } var signature interface{} = nil if IsTrue(IsGreaterThan(GetIndexOf(this.Secret, "PRIVATE KEY"), OpNeg(1))) { if IsTrue(IsGreaterThan(GetLength(this.Secret), 120)) { signature = this.EncodeURIComponent(Rsa(query, this.Secret, sha256)) } else { signature = this.EncodeURIComponent(Eddsa(this.Encode(query), this.Secret, ed25519)) } } else { signature = this.Hmac(this.Encode(query), this.Encode(this.Secret), sha256) } query = Add(query, Add(Add("&", "signature="), signature)) headers = map[string]interface{} { "X-MBX-APIKEY": this.ApiKey, } if IsTrue(IsTrue((IsEqual(method, "GET"))) || IsTrue((IsEqual(method, "DELETE")))) { url = Add(url, Add("?", query)) } else { body = query AddElementToObject(headers, "Content-Type", "application/x-www-form-urlencoded") } } else { if IsTrue(GetArrayLength(ObjectKeys(params))) { url = Add(url, Add("?", this.Urlencode(params))) } } return map[string]interface{} { "url": url, "method": method, "body": body, "headers": headers, } } func (this *binance) GetExceptionsByUrl(url interface{}, exactOrBroad interface{}) interface{} { var marketType interface{} = nil var hostname interface{} = Ternary(IsTrue((!IsEqual(this.Hostname, nil))), this.Hostname, "binance.com") if IsTrue(IsTrue(StartsWith(url, Add(Add("https://api.", hostname), "/"))) || IsTrue(StartsWith(url, "https://testnet.binance.vision"))) { marketType = "spot" } else if IsTrue(IsTrue(StartsWith(url, Add(Add("https://dapi.", hostname), "/"))) || IsTrue(StartsWith(url, "https://testnet.binancefuture.com/dapi"))) { marketType = "inverse" } else if IsTrue(IsTrue(StartsWith(url, Add(Add("https://fapi.", hostname), "/"))) || IsTrue(StartsWith(url, "https://testnet.binancefuture.com/fapi"))) { marketType = "linear" } else if IsTrue(StartsWith(url, Add(Add("https://eapi.", hostname), "/"))) { marketType = "option" } else if IsTrue(StartsWith(url, Add(Add("https://papi.", hostname), "/"))) { marketType = "portfolioMargin" } if IsTrue(!IsEqual(marketType, nil)) { var exceptionsForMarketType interface{} = this.SafeDict(this.Exceptions, marketType, map[string]interface{} {}) return this.SafeDict(exceptionsForMarketType, exactOrBroad, map[string]interface{} {}) } return map[string]interface{} {} } func (this *binance) HandleErrors(code interface{}, reason interface{}, url interface{}, method interface{}, headers interface{}, body interface{}, response interface{}, requestHeaders interface{}, requestBody interface{}) interface{} { if IsTrue(IsTrue((IsEqual(code, 418))) || IsTrue((IsEqual(code, 429)))) { panic(DDoSProtection(Add(Add(Add(Add(Add(Add(this.Id, " "), ToString(code)), " "), reason), " "), body))) } // error response in a form: { "code": -1013, "msg": "Invalid quantity." } // following block cointains legacy checks against message patterns in "msg" property // will switch "code" checks eventually, when we know all of them if IsTrue(IsGreaterThanOrEqual(code, 400)) { if IsTrue(IsGreaterThanOrEqual(GetIndexOf(body, "Price * QTY is zero or less"), 0)) { panic(InvalidOrder(Add(Add(this.Id, " order cost = amount * price is zero or less "), body))) } if IsTrue(IsGreaterThanOrEqual(GetIndexOf(body, "LOT_SIZE"), 0)) { panic(InvalidOrder(Add(Add(this.Id, " order amount should be evenly divisible by lot size "), body))) } if IsTrue(IsGreaterThanOrEqual(GetIndexOf(body, "PRICE_FILTER"), 0)) { panic(InvalidOrder(Add(Add(this.Id, " order price is invalid, i.e. exceeds allowed price precision, exceeds min price or max price limits or is invalid value in general, use this.priceToPrecision (symbol, amount) "), body))) } } if IsTrue(IsEqual(response, nil)) { return nil // fallback to default error handler } // response in format {'msg': 'The coin does not exist.', 'success': true/false} var success interface{} = this.SafeBool(response, "success", true) if !IsTrue(success) { var messageNew interface{} = this.SafeString(response, "msg") var parsedMessage interface{} = nil if IsTrue(!IsEqual(messageNew, nil)) { { ret__ := func(this *binance) (ret_ interface{}) { defer func() { if e := recover(); e != nil { if e == "break" { return } ret_ = func(this *binance) interface{} { // catch block: // do nothing parsedMessage = nil return nil }(this) } }() // try block: parsedMessage = JsonParse(messageNew) return nil }(this) if ret__ != nil { return ret__ } } if IsTrue(!IsEqual(parsedMessage, nil)) { response = parsedMessage } } } var message interface{} = this.SafeString(response, "msg") if IsTrue(!IsEqual(message, nil)) { this.ThrowExactlyMatchedException(this.GetExceptionsByUrl(url, "exact"), message, Add(Add(this.Id, " "), message)) this.ThrowExactlyMatchedException(GetValue(this.Exceptions, "exact"), message, Add(Add(this.Id, " "), message)) this.ThrowBroadlyMatchedException(this.GetExceptionsByUrl(url, "broad"), message, Add(Add(this.Id, " "), message)) this.ThrowBroadlyMatchedException(GetValue(this.Exceptions, "broad"), message, Add(Add(this.Id, " "), message)) } // checks against error codes var error interface{} = this.SafeString(response, "code") if IsTrue(!IsEqual(error, nil)) { // https://github.com/ccxt/ccxt/issues/6501 // https://github.com/ccxt/ccxt/issues/7742 if IsTrue(IsTrue((IsEqual(error, "200"))) || IsTrue(Precise.StringEquals(error, "0"))) { return nil } // a workaround for {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."} // despite that their message is very confusing, it is raised by Binance // on a temporary ban, the API key is valid, but disabled for a while if IsTrue(IsTrue((IsEqual(error, "-2015"))) && IsTrue(GetValue(this.Options, "hasAlreadyAuthenticatedSuccessfully"))) { panic(DDoSProtection(Add(Add(this.Id, " "), body))) } var feedback interface{} = Add(Add(this.Id, " "), body) if IsTrue(IsEqual(message, "No need to change margin type.")) { panic(MarginModeAlreadySet(feedback)) } this.ThrowExactlyMatchedException(this.GetExceptionsByUrl(url, "exact"), error, feedback) this.ThrowExactlyMatchedException(GetValue(this.Exceptions, "exact"), error, feedback) panic(ExchangeError(feedback)) } if !IsTrue(success) { panic(ExchangeError(Add(Add(this.Id, " "), body))) } if IsTrue(IsArray(response)) { // cancelOrders returns an array like this: [{"code":-2011,"msg":"Unknown order sent."}] var arrayLength interface{} = GetArrayLength(response) if IsTrue(IsEqual(arrayLength, 1)) { var element interface{} = GetValue(response, 0) var errorCode interface{} = this.SafeString(element, "code") if IsTrue(!IsEqual(errorCode, nil)) { this.ThrowExactlyMatchedException(this.GetExceptionsByUrl(url, "exact"), errorCode, Add(Add(this.Id, " "), body)) this.ThrowExactlyMatchedException(GetValue(this.Exceptions, "exact"), errorCode, Add(Add(this.Id, " "), body)) } } } return nil } func (this *binance) CalculateRateLimiterCost(api interface{}, method interface{}, path interface{}, params interface{}, optionalArgs ...interface{}) interface{} { config := GetArg(optionalArgs, 0, map[string]interface{} {}) _ = config if IsTrue(IsTrue((InOp(config, "noCoin"))) && !IsTrue((InOp(params, "coin")))) { return GetValue(config, "noCoin") } else if IsTrue(IsTrue((InOp(config, "noSymbol"))) && !IsTrue((InOp(params, "symbol")))) { return GetValue(config, "noSymbol") } else if IsTrue(IsTrue((InOp(config, "noPoolId"))) && !IsTrue((InOp(params, "poolId")))) { return GetValue(config, "noPoolId") } else if IsTrue(IsTrue((InOp(config, "byLimit"))) && IsTrue((InOp(params, "limit")))) { var limit interface{} = GetValue(params, "limit") var byLimit interface{} = GetValue(config, "byLimit") for i := 0; IsLessThan(i, GetArrayLength(byLimit)); i++ { var entry interface{} = GetValue(byLimit, i) if IsTrue(IsLessThanOrEqual(limit, GetValue(entry, 0))) { return GetValue(entry, 1) } } } return this.SafeValue(config, "cost", 1) } func (this *binance) Request(path interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) api := GetArg(optionalArgs, 0, "public") _ = api 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 config := GetArg(optionalArgs, 5, map[string]interface{} {}) _ = config response:= (<-this.Fetch2(path, api, method, params, headers, body, config)) PanicOnError(response) // a workaround for {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."} if IsTrue(IsEqual(api, "private")) { AddElementToObject(this.Options, "hasAlreadyAuthenticatedSuccessfully", true) } ch <- response return nil }() return ch } func (this *binance) ModifyMarginHelper(symbol interface{}, amount interface{}, addOrReduce interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) // used to modify isolated positions params := GetArg(optionalArgs, 0, map[string]interface{} {}) _ = params var defaultType interface{} = this.SafeString(this.Options, "defaultType", "future") if IsTrue(IsEqual(defaultType, "spot")) { defaultType = "future" } var typeVar interface{} = this.SafeString(params, "type", defaultType) if IsTrue(IsTrue((IsEqual(typeVar, "margin"))) || IsTrue((IsEqual(typeVar, "spot")))) { panic(NotSupported(Add(this.Id, " add / reduce margin only supported with type future or delivery"))) } retRes121468 := (<-this.LoadMarkets()) PanicOnError(retRes121468) var market interface{} = this.Market(symbol) amount = this.AmountToPrecision(symbol, amount) var request interface{} = map[string]interface{} { "type": addOrReduce, "symbol": GetValue(market, "id"), "amount": amount, } var response interface{} = nil var code interface{} = nil if IsTrue(GetValue(market, "linear")) { code = GetValue(market, "quote") response = (<-this.FapiPrivatePostPositionMargin(this.Extend(request, params))) PanicOnError(response) } else { code = GetValue(market, "base") response = (<-this.DapiPrivatePostPositionMargin(this.Extend(request, params))) PanicOnError(response) } // // { // "code": 200, // "msg": "Successfully modify position margin.", // "amount": 0.001, // "type": 1 // } // ch <- this.Extend(this.ParseMarginModification(response, market), map[string]interface{} { "code": code, }) return nil }() return ch } func (this *binance) ParseMarginModification(data interface{}, optionalArgs ...interface{}) interface{} { // // add/reduce margin // // { // "code": 200, // "msg": "Successfully modify position margin.", // "amount": 0.001, // "type": 1 // } // // fetchMarginAdjustmentHistory // // { // symbol: "XRPUSDT", // type: "1", // deltaType: "TRADE", // amount: "2.57148240", // asset: "USDT", // time: "1711046271555", // positionSide: "BOTH", // clientTranId: "" // } // market := GetArg(optionalArgs, 0, nil) _ = market var rawType interface{} = this.SafeInteger(data, "type") var errorCode interface{} = this.SafeString(data, "code") var marketId interface{} = this.SafeString(data, "symbol") var timestamp interface{} = this.SafeInteger(data, "time") market = this.SafeMarket(marketId, market, nil, "swap") var noErrorCode interface{} = IsEqual(errorCode, nil) var success interface{} = IsEqual(errorCode, "200") return map[string]interface{} { "info": data, "symbol": GetValue(market, "symbol"), "type": Ternary(IsTrue((IsEqual(rawType, 1))), "add", "reduce"), "marginMode": "isolated", "amount": this.SafeNumber(data, "amount"), "code": this.SafeString(data, "asset"), "total": nil, "status": Ternary(IsTrue((IsTrue(success) || IsTrue(noErrorCode))), "ok", "failed"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), } } /** * @method * @name binance#reduceMargin * @description remove margin from a position * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Isolated-Position-Margin * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Modify-Isolated-Position-Margin * @param {string} symbol unified market symbol * @param {float} amount the amount of margin to remove * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [margin structure]{@link https://docs.ccxt.com/#/?id=reduce-margin-structure} */ func (this *binance) 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 retRes1223315 := (<-this.ModifyMarginHelper(symbol, amount, 2, params)) PanicOnError(retRes1223315) ch <- retRes1223315 return nil }() return ch } /** * @method * @name binance#addMargin * @description add margin * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Isolated-Position-Margin * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Modify-Isolated-Position-Margin * @param {string} symbol unified market symbol * @param {float} amount amount of margin to add * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [margin structure]{@link https://docs.ccxt.com/#/?id=add-margin-structure} */ func (this *binance) 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 retRes1224815 := (<-this.ModifyMarginHelper(symbol, amount, 1, params)) PanicOnError(retRes1224815) ch <- retRes1224815 return nil }() return ch } /** * @method * @name binance#fetchCrossBorrowRate * @description fetch the rate of interest to borrow a currency for margin trading * @see https://developers.binance.com/docs/margin_trading/borrow-and-repay/Query-Margin-Interest-Rate-History * @param {string} code unified currency code * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [borrow rate structure]{@link https://docs.ccxt.com/#/?id=borrow-rate-structure} */ func (this *binance) FetchCrossBorrowRate(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 retRes122618 := (<-this.LoadMarkets()) PanicOnError(retRes122618) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "asset": GetValue(currency, "id"), } response:= (<-this.SapiGetMarginInterestRateHistory(this.Extend(request, params))) PanicOnError(response) // // [ // { // "asset": "USDT", // "timestamp": 1638230400000, // "dailyInterestRate": "0.0006", // "vipLevel": 0 // }, // ] // var rate interface{} = this.SafeDict(response, 0) ch <- this.ParseBorrowRate(rate) return nil }() return ch } /** * @method * @name binance#fetchIsolatedBorrowRate * @description fetch the rate of interest to borrow a currency for margin trading * @see https://developers.binance.com/docs/margin_trading/account/Query-Isolated-Margin-Fee-Data * @param {string} symbol unified market symbol * @param {object} [params] extra parameters specific to the exchange API endpoint * * EXCHANGE SPECIFIC PARAMETERS * @param {object} [params.vipLevel] user's current specific margin data will be returned if viplevel is omitted * @returns {object} an [isolated borrow rate structure]{@link https://docs.ccxt.com/#/?id=isolated-borrow-rate-structure} */ func (this *binance) FetchIsolatedBorrowRate(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 var request interface{} = map[string]interface{} { "symbol": symbol, } borrowRates:= (<-this.FetchIsolatedBorrowRates(this.Extend(request, params))) PanicOnError(borrowRates) ch <- this.SafeDict(borrowRates, symbol) return nil }() return ch } /** * @method * @name binance#fetchIsolatedBorrowRates * @description fetch the borrow interest rates of all currencies * @see https://developers.binance.com/docs/margin_trading/account/Query-Isolated-Margin-Fee-Data * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {object} [params.symbol] unified market symbol * * EXCHANGE SPECIFIC PARAMETERS * @param {object} [params.vipLevel] user's current specific margin data will be returned if viplevel is omitted * @returns {object} a [borrow rate structure]{@link https://docs.ccxt.com/#/?id=borrow-rate-structure} */ func (this *binance) FetchIsolatedBorrowRates(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 retRes123158 := (<-this.LoadMarkets()) PanicOnError(retRes123158) var request interface{} = map[string]interface{} {} var symbol interface{} = this.SafeString(params, "symbol") params = this.Omit(params, "symbol") if IsTrue(!IsEqual(symbol, nil)) { var market interface{} = this.Market(symbol) AddElementToObject(request, "symbol", GetValue(market, "id")) } response:= (<-this.SapiGetMarginIsolatedMarginData(this.Extend(request, params))) PanicOnError(response) // // [ // { // "vipLevel": 0, // "symbol": "BTCUSDT", // "leverage": "10", // "data": [ // { // "coin": "BTC", // "dailyInterest": "0.00026125", // "borrowLimit": "270" // }, // { // "coin": "USDT", // "dailyInterest": "0.000475", // "borrowLimit": "2100000" // } // ] // } // ] // ch <- this.ParseIsolatedBorrowRates(response) return nil }() return ch } /** * @method * @name binance#fetchBorrowRateHistory * @description retrieves a history of a currencies borrow interest rate at specific time slots * @see https://developers.binance.com/docs/margin_trading/borrow-and-repay/Query-Margin-Interest-Rate-History * @param {string} code unified currency code * @param {int} [since] timestamp for the earliest borrow rate * @param {int} [limit] the maximum number of [borrow rate structures]{@link https://docs.ccxt.com/#/?id=borrow-rate-structure} to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} an array of [borrow rate structures]{@link https://docs.ccxt.com/#/?id=borrow-rate-structure} */ func (this *binance) FetchBorrowRateHistory(code 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 retRes123608 := (<-this.LoadMarkets()) PanicOnError(retRes123608) if IsTrue(IsEqual(limit, nil)) { limit = 93 } else if IsTrue(IsGreaterThan(limit, 93)) { panic(BadRequest(Add(this.Id, " fetchBorrowRateHistory() limit parameter cannot exceed 92"))) } var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "asset": GetValue(currency, "id"), "limit": limit, } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) var endTime interface{} = Subtract(this.Sum(since, Multiply(limit, 86400000)), 1) // required when startTime is further than 93 days in the past var now interface{} = this.Milliseconds() AddElementToObject(request, "endTime", mathMin(endTime, now)) // cannot have an endTime later than current time } response:= (<-this.SapiGetMarginInterestRateHistory(this.Extend(request, params))) PanicOnError(response) // // [ // { // "asset": "USDT", // "timestamp": 1638230400000, // "dailyInterestRate": "0.0006", // "vipLevel": 0 // }, // ] // ch <- this.ParseBorrowRateHistory(response, code, since, limit) return nil }() return ch } func (this *binance) ParseBorrowRate(info interface{}, optionalArgs ...interface{}) interface{} { // // { // "asset": "USDT", // "timestamp": 1638230400000, // "dailyInterestRate": "0.0006", // "vipLevel": 0 // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var timestamp interface{} = this.SafeInteger(info, "timestamp") var currencyId interface{} = this.SafeString(info, "asset") return map[string]interface{} { "currency": this.SafeCurrencyCode(currencyId, currency), "rate": this.SafeNumber(info, "dailyInterestRate"), "period": 86400000, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "info": info, } } func (this *binance) ParseIsolatedBorrowRate(info interface{}, optionalArgs ...interface{}) interface{} { // // { // "vipLevel": 0, // "symbol": "BTCUSDT", // "leverage": "10", // "data": [ // { // "coin": "BTC", // "dailyInterest": "0.00026125", // "borrowLimit": "270" // }, // { // "coin": "USDT", // "dailyInterest": "0.000475", // "borrowLimit": "2100000" // } // ] // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(info, "symbol") market = this.SafeMarket(marketId, market, nil, "spot") var data interface{} = this.SafeList(info, "data") var baseInfo interface{} = this.SafeDict(data, 0) var quoteInfo interface{} = this.SafeDict(data, 1) return map[string]interface{} { "info": info, "symbol": this.SafeString(market, "symbol"), "base": this.SafeString(baseInfo, "coin"), "baseRate": this.SafeNumber(baseInfo, "dailyInterest"), "quote": this.SafeString(quoteInfo, "coin"), "quoteRate": this.SafeNumber(quoteInfo, "dailyInterest"), "period": 86400000, "timestamp": nil, "datetime": nil, } } /** * @method * @name binance#createGiftCode * @description create gift code * @see https://developers.binance.com/docs/gift_card/market-data/Create-a-single-token-gift-card * @param {string} code gift code * @param {float} amount amount of currency for the gift * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} The gift code id, code, currency and amount */ func (this *binance) CreateGiftCode(code 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 retRes124628 := (<-this.LoadMarkets()) PanicOnError(retRes124628) var currency interface{} = this.Currency(code) // ensure you have enough token in your funding account before calling this code var request interface{} = map[string]interface{} { "token": GetValue(currency, "id"), "amount": amount, } response:= (<-this.SapiPostGiftcardCreateCode(this.Extend(request, params))) PanicOnError(response) // // { // "code": "000000", // "message": "success", // "data": { referenceNo: "0033002404219823", code: "AP6EXTLKNHM6CEX7" }, // "success": true // } // var data interface{} = this.SafeDict(response, "data") var giftcardCode interface{} = this.SafeString(data, "code") var id interface{} = this.SafeString(data, "referenceNo") ch <- map[string]interface{} { "info": response, "id": id, "code": giftcardCode, "currency": code, "amount": amount, } return nil }() return ch } /** * @method * @name binance#redeemGiftCode * @description redeem gift code * @see https://developers.binance.com/docs/gift_card/market-data/Redeem-a-Binance-Gift-Card * @param {string} giftcardCode * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} response from the exchange */ func (this *binance) RedeemGiftCode(giftcardCode 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{} { "code": giftcardCode, } response:= (<-this.SapiPostGiftcardRedeemCode(this.Extend(request, params))) PanicOnError(response) // // { // "code": "000000", // "message": "success", // "data": { // "referenceNo": "0033002404219823", // "identityNo": "10316431732801474560" // }, // "success": true // } // ch <- response return nil }() return ch } /** * @method * @name binance#verifyGiftCode * @description verify gift code * @see https://developers.binance.com/docs/gift_card/market-data/Verify-Binance-Gift-Card-by-Gift-Card-Number * @param {string} id reference number id * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} response from the exchange */ func (this *binance) VerifyGiftCode(id 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{} { "referenceNo": id, } response:= (<-this.SapiGetGiftcardVerify(this.Extend(request, params))) PanicOnError(response) // // { // "code": "000000", // "message": "success", // "data": { valid: true }, // "success": true // } // ch <- response return nil }() return ch } /** * @method * @name binance#fetchBorrowInterest * @description fetch the interest owed by the user for borrowing currency for margin trading * @see https://developers.binance.com/docs/margin_trading/borrow-and-repay/Get-Interest-History * @see https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-Margin-BorrowLoan-Interest-History * @param {string} [code] unified currency code * @param {string} [symbol] unified market symbol when fetch interest in isolated markets * @param {int} [since] the earliest time in ms to fetch borrrow interest for * @param {int} [limit] the maximum number of structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch the borrow interest in a portfolio margin account * @returns {object[]} a list of [borrow interest structures]{@link https://docs.ccxt.com/#/?id=borrow-interest-structure} */ func (this *binance) FetchBorrowInterest(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) code := GetArg(optionalArgs, 0, nil) _ = code symbol := GetArg(optionalArgs, 1, nil) _ = symbol since := GetArg(optionalArgs, 2, nil) _ = since limit := GetArg(optionalArgs, 3, nil) _ = limit params := GetArg(optionalArgs, 4, map[string]interface{} {}) _ = params retRes125588 := (<-this.LoadMarkets()) PanicOnError(retRes125588) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchBorrowInterest", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var request interface{} = map[string]interface{} {} var market interface{} = nil if IsTrue(!IsEqual(code, nil)) { var currency interface{} = this.Currency(code) AddElementToObject(request, "asset", GetValue(currency, "id")) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "size", limit) } requestparamsVariable := this.HandleUntilOption("endTime", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) var response interface{} = nil if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetMarginMarginInterestHistory(this.Extend(request, params))) PanicOnError(response) } else { if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) AddElementToObject(request, "isolatedSymbol", GetValue(market, "id")) } response = (<-this.SapiGetMarginInterestHistory(this.Extend(request, params))) PanicOnError(response) } // // spot margin // // { // "rows":[ // { // "isolatedSymbol": "BNBUSDT", // isolated symbol, will not be returned for crossed margin // "asset": "BNB", // "interest": "0.02414667", // "interestAccuredTime": 1566813600000, // "interestRate": "0.01600000", // "principal": "36.22000000", // "type": "ON_BORROW" // } // ], // "total": 1 // } // // spot margin portfolio margin // // { // "total": 49, // "rows": [ // { // "txId": 1656187724899910076, // "interestAccuredTime": 1707541200000, // "asset": "USDT", // "rawAsset": "USDT", // "principal": "0.00011146", // "interest": "0.00000001", // "interestRate": "0.00089489", // "type": "PERIODIC" // }, // ] // } // var rows interface{} = this.SafeList(response, "rows") var interest interface{} = this.ParseBorrowInterests(rows, market) ch <- this.FilterByCurrencySinceLimit(interest, code, since, limit) return nil }() return ch } func (this *binance) ParseBorrowInterest(info interface{}, optionalArgs ...interface{}) interface{} { market := GetArg(optionalArgs, 0, nil) _ = market var symbol interface{} = this.SafeString(info, "isolatedSymbol") var timestamp interface{} = this.SafeInteger(info, "interestAccuredTime") var marginMode interface{} = Ternary(IsTrue((IsEqual(symbol, nil))), "cross", "isolated") return map[string]interface{} { "info": info, "symbol": symbol, "currency": this.SafeCurrencyCode(this.SafeString(info, "asset")), "interest": this.SafeNumber(info, "interest"), "interestRate": this.SafeNumber(info, "interestRate"), "amountBorrowed": this.SafeNumber(info, "principal"), "marginMode": marginMode, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), } } /** * @method * @name binance#repayCrossMargin * @description repay borrowed margin and interest * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Repay * @see https://developers.binance.com/docs/margin_trading/borrow-and-repay/Margin-Account-Borrow-Repay * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Repay-Debt * @param {string} code unified currency code of the currency to repay * @param {float} amount the amount to repay * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to repay margin in a portfolio margin account * @param {string} [params.repayCrossMarginMethod] *portfolio margin only* 'papiPostRepayLoan' (default), 'papiPostMarginRepayDebt' (alternative) * @param {string} [params.specifyRepayAssets] *portfolio margin papiPostMarginRepayDebt only* specific asset list to repay debt * @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/#/?id=margin-loan-structure} */ func (this *binance) RepayCrossMargin(code 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 retRes126588 := (<-this.LoadMarkets()) PanicOnError(retRes126588) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "asset": GetValue(currency, "id"), "amount": this.CurrencyToPrecision(code, amount), } var response interface{} = nil var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "repayCrossMargin", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) if IsTrue(isPortfolioMargin) { var method interface{} = nil methodparamsVariable := this.HandleOptionAndParams2(params, "repayCrossMargin", "repayCrossMarginMethod", "method"); method = GetValue(methodparamsVariable,0); params = GetValue(methodparamsVariable,1) if IsTrue(IsEqual(method, "papiPostMarginRepayDebt")) { response = (<-this.PapiPostMarginRepayDebt(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PapiPostRepayLoan(this.Extend(request, params))) PanicOnError(response) } } else { AddElementToObject(request, "isIsolated", "FALSE") AddElementToObject(request, "type", "REPAY") response = (<-this.SapiPostMarginBorrowRepay(this.Extend(request, params))) PanicOnError(response) } ch <- this.ParseMarginLoan(response, currency) return nil }() return ch } /** * @method * @name binance#repayIsolatedMargin * @description repay borrowed margin and interest * @see https://developers.binance.com/docs/margin_trading/borrow-and-repay/Margin-Account-Borrow-Repay * @param {string} symbol unified market symbol, required for isolated margin * @param {string} code unified currency code of the currency to repay * @param {float} amount the amount to repay * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/#/?id=margin-loan-structure} */ func (this *binance) RepayIsolatedMargin(symbol interface{}, code 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 retRes127168 := (<-this.LoadMarkets()) PanicOnError(retRes127168) var currency interface{} = this.Currency(code) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "asset": GetValue(currency, "id"), "amount": this.CurrencyToPrecision(code, amount), "symbol": GetValue(market, "id"), "isIsolated": "TRUE", "type": "REPAY", } response:= (<-this.SapiPostMarginBorrowRepay(this.Extend(request, params))) PanicOnError(response) // // { // "tranId": 108988250265, // "clientTag":"" // } // ch <- this.ParseMarginLoan(response, currency) return nil }() return ch } /** * @method * @name binance#borrowCrossMargin * @description create a loan to borrow margin * @see https://developers.binance.com/docs/margin_trading/borrow-and-repay/Margin-Account-Borrow-Repay * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Borrow * @param {string} code unified currency code of the currency to borrow * @param {float} amount the amount to borrow * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.portfolioMargin] set to true if you would like to borrow margin in a portfolio margin account * @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/#/?id=margin-loan-structure} */ func (this *binance) BorrowCrossMargin(code 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 retRes127498 := (<-this.LoadMarkets()) PanicOnError(retRes127498) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "asset": GetValue(currency, "id"), "amount": this.CurrencyToPrecision(code, amount), } var response interface{} = nil var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "borrowCrossMargin", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) if IsTrue(isPortfolioMargin) { response = (<-this.PapiPostMarginLoan(this.Extend(request, params))) PanicOnError(response) } else { AddElementToObject(request, "isIsolated", "FALSE") AddElementToObject(request, "type", "BORROW") response = (<-this.SapiPostMarginBorrowRepay(this.Extend(request, params))) PanicOnError(response) } // // { // "tranId": 108988250265, // "clientTag":"" // } // ch <- this.ParseMarginLoan(response, currency) return nil }() return ch } /** * @method * @name binance#borrowIsolatedMargin * @description create a loan to borrow margin * @see https://developers.binance.com/docs/margin_trading/borrow-and-repay/Margin-Account-Borrow-Repay * @param {string} symbol unified market symbol, required for isolated margin * @param {string} code unified currency code of the currency to borrow * @param {float} amount the amount to borrow * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/#/?id=margin-loan-structure} */ func (this *binance) BorrowIsolatedMargin(symbol interface{}, code 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 retRes127868 := (<-this.LoadMarkets()) PanicOnError(retRes127868) var currency interface{} = this.Currency(code) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "asset": GetValue(currency, "id"), "amount": this.CurrencyToPrecision(code, amount), "symbol": GetValue(market, "id"), "isIsolated": "TRUE", "type": "BORROW", } response:= (<-this.SapiPostMarginBorrowRepay(this.Extend(request, params))) PanicOnError(response) // // { // "tranId": 108988250265, // "clientTag":"" // } // ch <- this.ParseMarginLoan(response, currency) return nil }() return ch } func (this *binance) ParseMarginLoan(info interface{}, optionalArgs ...interface{}) interface{} { // // { // "tranId": 108988250265, // "clientTag":"" // } // // repayCrossMargin alternative endpoint // // { // "asset": "USDC", // "amount": 10, // "specifyRepayAssets": null, // "updateTime": 1727170761267, // "success": true // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var currencyId interface{} = this.SafeString(info, "asset") var timestamp interface{} = this.SafeInteger(info, "updateTime") return map[string]interface{} { "id": this.SafeInteger(info, "tranId"), "currency": this.SafeCurrencyCode(currencyId, currency), "amount": this.SafeNumber(info, "amount"), "symbol": nil, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "info": info, } } /** * @method * @name binance#fetchOpenInterestHistory * @description Retrieves the open interest history of a currency * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest-Statistics * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Open-Interest-Statistics * @param {string} symbol Unified CCXT market symbol * @param {string} timeframe "5m","15m","30m","1h","2h","4h","6h","12h", or "1d" * @param {int} [since] the time(ms) of the earliest record to retrieve as a unix timestamp * @param {int} [limit] default 30, max 500 * @param {object} [params] exchange specific parameters * @param {int} [params.until] the time(ms) of the latest record to retrieve as a unix timestamp * @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} an array of [open interest structure]{@link https://docs.ccxt.com/#/?id=open-interest-structure} */ func (this *binance) FetchOpenInterestHistory(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) timeframe := GetArg(optionalArgs, 0, "5m") _ = timeframe since := GetArg(optionalArgs, 1, nil) _ = since limit := GetArg(optionalArgs, 2, nil) _ = limit params := GetArg(optionalArgs, 3, map[string]interface{} {}) _ = params if IsTrue(IsEqual(timeframe, "1m")) { panic(BadRequest(Add(this.Id, " fetchOpenInterestHistory cannot use the 1m timeframe"))) } retRes128558 := (<-this.LoadMarkets()) PanicOnError(retRes128558) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOpenInterestHistory", "paginate", false); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes1285919 := (<-this.FetchPaginatedCallDeterministic("fetchOpenInterestHistory", symbol, since, limit, timeframe, params, 500)) PanicOnError(retRes1285919) ch <- retRes1285919 return nil } var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "period": this.SafeString(this.Timeframes, timeframe, timeframe), } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } var symbolKey interface{} = Ternary(IsTrue(GetValue(market, "linear")), "symbol", "pair") AddElementToObject(request, symbolKey, GetValue(market, "id")) if IsTrue(GetValue(market, "inverse")) { AddElementToObject(request, "contractType", this.SafeString(params, "contractType", "CURRENT_QUARTER")) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } var until interface{} = this.SafeInteger(params, "until") // unified in milliseconds var endTime interface{} = this.SafeInteger(params, "endTime", until) // exchange-specific in milliseconds params = this.Omit(params, []interface{}{"endTime", "until"}) if IsTrue(endTime) { AddElementToObject(request, "endTime", endTime) } else if IsTrue(since) { if IsTrue(IsEqual(limit, nil)) { limit = 30 // Exchange default } var duration interface{} = this.ParseTimeframe(timeframe) AddElementToObject(request, "endTime", this.Sum(since, Multiply(Multiply(duration, limit), 1000))) } var response interface{} = nil if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiDataGetOpenInterestHist(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiDataGetOpenInterestHist(this.Extend(request, params))) PanicOnError(response) } // // [ // { // "symbol":"BTCUSDT", // "sumOpenInterest":"75375.61700000", // "sumOpenInterestValue":"3248828883.71251440", // "timestamp":1642179900000 // }, // ... // ] // ch <- this.ParseOpenInterestsHistory(response, market, since, limit) return nil }() return ch } /** * @method * @name binance#fetchOpenInterest * @description retrieves the open interest of a contract trading pair * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Open-Interest * @see https://developers.binance.com/docs/derivatives/option/market-data/Open-Interest * @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 *binance) 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 retRes129208 := (<-this.LoadMarkets()) PanicOnError(retRes129208) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} {} if IsTrue(GetValue(market, "option")) { AddElementToObject(request, "underlyingAsset", GetValue(market, "baseId")) if IsTrue(IsEqual(GetValue(market, "expiry"), nil)) { panic(NotSupported(Add(Add(this.Id, " fetchOpenInterest does not support "), symbol))) } AddElementToObject(request, "expiration", this.Yymmdd(GetValue(market, "expiry"))) } else { AddElementToObject(request, "symbol", GetValue(market, "id")) } var response interface{} = nil if IsTrue(GetValue(market, "option")) { response = (<-this.EapiPublicGetOpenInterest(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPublicGetOpenInterest(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPublicGetOpenInterest(this.Extend(request, params))) PanicOnError(response) } // // futures (fapi) // // { // "symbol": "ETHUSDT_230331", // "openInterest": "23581.677", // "time": 1677356872265 // } // // futures (dapi) // // { // "symbol": "ETHUSD_PERP", // "pair": "ETHUSD", // "openInterest": "26542436", // "contractType": "PERPETUAL", // "time": 1677360272224 // } // // options (eapi) // // [ // { // "symbol": "ETH-230225-1625-C", // "sumOpenInterest": "460.50", // "sumOpenInterestUsd": "734957.4358092150", // "timestamp": "1677304860000" // } // ] // if IsTrue(GetValue(market, "option")) { symbol = GetValue(market, "symbol") var result interface{} = this.ParseOpenInterestsHistory(response, market) for i := 0; IsLessThan(i, GetArrayLength(result)); i++ { var item interface{} = GetValue(result, i) if IsTrue(IsEqual(GetValue(item, "symbol"), symbol)) { ch <- item return nil } } } else { ch <- this.ParseOpenInterest(response, market) return nil } return nil }() return ch } func (this *binance) ParseOpenInterest(interest interface{}, optionalArgs ...interface{}) interface{} { market := GetArg(optionalArgs, 0, nil) _ = market var timestamp interface{} = this.SafeInteger2(interest, "timestamp", "time") var id interface{} = this.SafeString(interest, "symbol") var amount interface{} = this.SafeNumber2(interest, "sumOpenInterest", "openInterest") var value interface{} = this.SafeNumber2(interest, "sumOpenInterestValue", "sumOpenInterestUsd") // Inverse returns the number of contracts different from the base or quote volume in this case // compared with https://www.binance.com/en/futures/funding-history/quarterly/4 return this.SafeOpenInterest(map[string]interface{} { "symbol": this.SafeSymbol(id, market, nil, "contract"), "baseVolume": Ternary(IsTrue(GetValue(market, "inverse")), nil, amount), "quoteVolume": value, "openInterestAmount": amount, "openInterestValue": value, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "info": interest, }, market) } /** * @method * @name binance#fetchMyLiquidations * @description retrieves the users liquidated positions * @see https://developers.binance.com/docs/margin_trading/trade/Get-Force-Liquidation-Record * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Users-Force-Orders * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Users-Force-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Users-UM-Force-Orders * @see https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Users-CM-Force-Orders * @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 binance api endpoint * @param {int} [params.until] timestamp in ms of the latest liquidation * @param {boolean} [params.paginate] *spot only* 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) * @param {boolean} [params.portfolioMargin] set to true if you would like to fetch liquidations in a portfolio margin account * @param {string} [params.type] "spot" * @param {string} [params.subType] "linear" or "inverse" * @returns {object} an array of [liquidation structures]{@link https://docs.ccxt.com/#/?id=liquidation-structure} */ func (this *binance) 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 retRes130258 := (<-this.LoadMarkets()) PanicOnError(retRes130258) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchMyLiquidations", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes1302919 := (<-this.FetchPaginatedCallIncremental("fetchMyLiquidations", symbol, since, limit, params, "current", 100)) PanicOnError(retRes1302919) ch <- retRes1302919 return nil } var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) } var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchMyLiquidations", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchMyLiquidations", market, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var isPortfolioMargin interface{} = nil isPortfolioMarginparamsVariable := this.HandleOptionAndParams2(params, "fetchMyLiquidations", "papi", "portfolioMargin", false); isPortfolioMargin = GetValue(isPortfolioMarginparamsVariable,0); params = GetValue(isPortfolioMarginparamsVariable,1) var request interface{} = map[string]interface{} {} if IsTrue(!IsEqual(typeVar, "spot")) { AddElementToObject(request, "autoCloseType", "LIQUIDATION") } if IsTrue(!IsEqual(market, nil)) { var symbolKey interface{} = Ternary(IsTrue(GetValue(market, "spot")), "isolatedSymbol", "symbol") if !IsTrue(isPortfolioMargin) { AddElementToObject(request, symbolKey, GetValue(market, "id")) } } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } if IsTrue(!IsEqual(limit, nil)) { if IsTrue(IsEqual(typeVar, "spot")) { AddElementToObject(request, "size", limit) } else { AddElementToObject(request, "limit", limit) } } requestparamsVariable := this.HandleUntilOption("endTime", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) var response interface{} = nil if IsTrue(IsEqual(typeVar, "spot")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetMarginForceOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.SapiGetMarginForceLiquidationRec(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(IsEqual(subType, "linear")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetUmForceOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.FapiPrivateGetForceOrders(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(IsEqual(subType, "inverse")) { if IsTrue(isPortfolioMargin) { response = (<-this.PapiGetCmForceOrders(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.DapiPrivateGetForceOrders(this.Extend(request, params))) PanicOnError(response) } } else { panic(NotSupported(Add(Add(Add(this.Id, " fetchMyLiquidations() does not support "), GetValue(market, "type")), " markets"))) } // // margin // // { // "rows": [ // { // "avgPrice": "0.00388359", // "executedQty": "31.39000000", // "orderId": 180015097, // "price": "0.00388110", // "qty": "31.39000000", // "side": "SELL", // "symbol": "BNBBTC", // "timeInForce": "GTC", // "isIsolated": true, // "updatedTime": 1558941374745 // } // ], // "total": 1 // } // // linear // // [ // { // "orderId": 6071832819, // "symbol": "BTCUSDT", // "status": "FILLED", // "clientOrderId": "autoclose-1596107620040000020", // "price": "10871.09", // "avgPrice": "10913.21000", // "origQty": "0.001", // "executedQty": "0.001", // "cumQuote": "10.91321", // "timeInForce": "IOC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "SELL", // "positionSide": "BOTH", // "stopPrice": "0", // "workingType": "CONTRACT_PRICE", // "origType": "LIMIT", // "time": 1596107620044, // "updateTime": 1596107620087 // }, // ] // // inverse // // [ // { // "orderId": 165123080, // "symbol": "BTCUSD_200925", // "pair": "BTCUSD", // "status": "FILLED", // "clientOrderId": "autoclose-1596542005017000006", // "price": "11326.9", // "avgPrice": "11326.9", // "origQty": "1", // "executedQty": "1", // "cumBase": "0.00882854", // "timeInForce": "IOC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "SELL", // "positionSide": "BOTH", // "stopPrice": "0", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "time": 1596542005019, // "updateTime": 1596542005050 // }, // ] // var liquidations interface{} = this.SafeList(response, "rows", response) ch <- this.ParseLiquidations(liquidations, market, since, limit) return nil }() return ch } func (this *binance) ParseLiquidation(liquidation interface{}, optionalArgs ...interface{}) interface{} { // // margin // // { // "avgPrice": "0.00388359", // "executedQty": "31.39000000", // "orderId": 180015097, // "price": "0.00388110", // "qty": "31.39000000", // "side": "SELL", // "symbol": "BNBBTC", // "timeInForce": "GTC", // "isIsolated": true, // "updatedTime": 1558941374745 // } // // linear // // { // "orderId": 6071832819, // "symbol": "BTCUSDT", // "status": "FILLED", // "clientOrderId": "autoclose-1596107620040000020", // "price": "10871.09", // "avgPrice": "10913.21000", // "origQty": "0.001", // "executedQty": "0.002", // "cumQuote": "10.91321", // "timeInForce": "IOC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "SELL", // "positionSide": "BOTH", // "stopPrice": "0", // "workingType": "CONTRACT_PRICE", // "origType": "LIMIT", // "time": 1596107620044, // "updateTime": 1596107620087 // } // // inverse // // { // "orderId": 165123080, // "symbol": "BTCUSD_200925", // "pair": "BTCUSD", // "status": "FILLED", // "clientOrderId": "autoclose-1596542005017000006", // "price": "11326.9", // "avgPrice": "11326.9", // "origQty": "1", // "executedQty": "1", // "cumBase": "0.00882854", // "timeInForce": "IOC", // "type": "LIMIT", // "reduceOnly": false, // "closePosition": false, // "side": "SELL", // "positionSide": "BOTH", // "stopPrice": "0", // "workingType": "CONTRACT_PRICE", // "priceProtect": false, // "origType": "LIMIT", // "time": 1596542005019, // "updateTime": 1596542005050 // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(liquidation, "symbol") var timestamp interface{} = this.SafeInteger2(liquidation, "updatedTime", "updateTime") return this.SafeLiquidation(map[string]interface{} { "info": liquidation, "symbol": this.SafeSymbol(marketId, market), "contracts": this.SafeNumber(liquidation, "executedQty"), "contractSize": this.SafeNumber(market, "contractSize"), "price": this.SafeNumber(liquidation, "avgPrice"), "baseValue": this.SafeNumber(liquidation, "cumBase"), "quoteValue": this.SafeNumber(liquidation, "cumQuote"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), }) } /** * @method * @name binance#fetchGreeks * @description fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract * @see https://developers.binance.com/docs/derivatives/option/market-data/Option-Mark-Price * @param {string} symbol unified symbol of the market to fetch greeks for * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [greeks structure]{@link https://docs.ccxt.com/#/?id=greeks-structure} */ func (this *binance) FetchGreeks(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 retRes132598 := (<-this.LoadMarkets()) PanicOnError(retRes132598) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } response:= (<-this.EapiPublicGetMark(this.Extend(request, params))) PanicOnError(response) // // [ // { // "symbol": "BTC-231229-40000-C", // "markPrice": "2012", // "bidIV": "0.60236275", // "askIV": "0.62267244", // "markIV": "0.6125176", // "delta": "0.39111646", // "theta": "-32.13948531", // "gamma": "0.00004656", // "vega": "51.70062218", // "highPriceLimit": "6474", // "lowPriceLimit": "5" // } // ] // ch <- this.ParseGreeks(GetValue(response, 0), market) return nil }() return ch } func (this *binance) ParseGreeks(greeks interface{}, optionalArgs ...interface{}) interface{} { // // { // "symbol": "BTC-231229-40000-C", // "markPrice": "2012", // "bidIV": "0.60236275", // "askIV": "0.62267244", // "markIV": "0.6125176", // "delta": "0.39111646", // "theta": "-32.13948531", // "gamma": "0.00004656", // "vega": "51.70062218", // "highPriceLimit": "6474", // "lowPriceLimit": "5" // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(greeks, "symbol") var symbol interface{} = this.SafeSymbol(marketId, market) return map[string]interface{} { "symbol": symbol, "timestamp": nil, "datetime": nil, "delta": this.SafeNumber(greeks, "delta"), "gamma": this.SafeNumber(greeks, "gamma"), "theta": this.SafeNumber(greeks, "theta"), "vega": this.SafeNumber(greeks, "vega"), "rho": nil, "bidSize": nil, "askSize": nil, "bidImpliedVolatility": this.SafeNumber(greeks, "bidIV"), "askImpliedVolatility": this.SafeNumber(greeks, "askIV"), "markImpliedVolatility": this.SafeNumber(greeks, "markIV"), "bidPrice": nil, "askPrice": nil, "markPrice": this.SafeNumber(greeks, "markPrice"), "lastPrice": nil, "underlyingPrice": nil, "info": greeks, } } func (this *binance) FetchTradingLimits(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) // this method should not be called directly, use loadTradingLimits () instead symbols := GetArg(optionalArgs, 0, nil) _ = symbols params := GetArg(optionalArgs, 1, map[string]interface{} {}) _ = params markets:= (<-this.FetchMarkets()) PanicOnError(markets) var tradingLimits interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(markets)); i++ { var market interface{} = GetValue(markets, i) var symbol interface{} = GetValue(market, "symbol") if IsTrue(IsTrue((IsEqual(symbols, nil))) || IsTrue((this.InArray(symbol, symbols)))) { AddElementToObject(tradingLimits, symbol, GetValue(GetValue(market, "limits"), "amount")) } } ch <- tradingLimits return nil }() return ch } /** * @method * @name binance#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://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Current-Position-Mode * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Get-Current-Position-Mode * @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 * @param {string} [params.subType] "linear" or "inverse" * @returns {object} an object detailing whether the market is in hedged or one-way mode */ func (this *binance) 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 var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) } var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchPositionMode", market, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var response interface{} = nil if IsTrue(IsEqual(subType, "linear")) { response = (<-this.FapiPrivateGetPositionSideDual(params)) PanicOnError(response) } else if IsTrue(IsEqual(subType, "inverse")) { response = (<-this.DapiPrivateGetPositionSideDual(params)) PanicOnError(response) } else { panic(BadRequest(Add(this.Id, " fetchPositionMode requires either a symbol argument or params[\"subType\"]"))) } // // { // dualSidePosition: false // } // var dualSidePosition interface{} = this.SafeBool(response, "dualSidePosition") ch <- map[string]interface{} { "info": response, "hedged": dualSidePosition, } return nil }() return ch } /** * @method * @name binance#fetchMarginModes * @description fetches margin modes ("isolated" or "cross") that the market for the symbol in in, with symbol=undefined all markets for a subType (linear/inverse) are returned * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Account-Information * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Information-V2 * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Symbol-Config * @param {string[]} symbols unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.subType] "linear" or "inverse" * @returns {object} a list of [margin mode structures]{@link https://docs.ccxt.com/#/?id=margin-mode-structure} */ func (this *binance) FetchMarginModes(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 retRes133918 := (<-this.LoadMarkets()) PanicOnError(retRes133918) var market interface{} = nil if IsTrue(!IsEqual(symbols, nil)) { symbols = this.MarketSymbols(symbols) market = this.Market(GetValue(symbols, 0)) } var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchMarginMode", market, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var response interface{} = nil if IsTrue(IsEqual(subType, "linear")) { response = (<-this.FapiPrivateGetSymbolConfig(params)) PanicOnError(response) } else if IsTrue(IsEqual(subType, "inverse")) { response = (<-this.DapiPrivateGetAccount(params)) PanicOnError(response) } else { panic(BadRequest(Add(this.Id, " fetchMarginModes () supports linear and inverse subTypes only"))) } var assets interface{} = this.SafeList(response, "positions", []interface{}{}) if IsTrue(IsArray(response)) { assets = response } ch <- this.ParseMarginModes(assets, symbols, "symbol", "swap") return nil }() return ch } /** * @method * @name binance#fetchMarginMode * @description fetches the margin mode of a specific symbol * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Symbol-Config * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/account/Account-Information * @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.subType] "linear" or "inverse" * @returns {object} a [margin mode structure]{@link https://docs.ccxt.com/#/?id=margin-mode-structure} */ func (this *binance) 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 retRes134858 := (<-this.LoadMarkets()) PanicOnError(retRes134858) var market interface{} = this.Market(symbol) var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchMarginMode", market, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var response interface{} = nil if IsTrue(IsEqual(subType, "linear")) { var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } response = (<-this.FapiPrivateGetSymbolConfig(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(subType, "inverse")) { fetchMarginModesResponse:= (<-this.FetchMarginModes([]interface{}{symbol}, params)) PanicOnError(fetchMarginModesResponse) ch <- GetValue(fetchMarginModesResponse, symbol) return nil } else { panic(BadRequest(Add(this.Id, " fetchMarginMode () supports linear and inverse subTypes only"))) } ch <- this.ParseMarginMode(GetValue(response, 0), market) return nil }() return ch } func (this *binance) ParseMarginMode(marginMode interface{}, optionalArgs ...interface{}) interface{} { market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(marginMode, "symbol") market = this.SafeMarket(marketId, market) var marginModeRaw interface{} = this.SafeBool(marginMode, "isolated") var reMarginMode interface{} = nil if IsTrue(!IsEqual(marginModeRaw, nil)) { reMarginMode = Ternary(IsTrue(marginModeRaw), "isolated", "cross") } var marginTypeRaw interface{} = this.SafeStringLower(marginMode, "marginType") if IsTrue(!IsEqual(marginTypeRaw, nil)) { reMarginMode = Ternary(IsTrue((IsEqual(marginTypeRaw, "crossed"))), "cross", "isolated") } return map[string]interface{} { "info": marginMode, "symbol": GetValue(market, "symbol"), "marginMode": reMarginMode, } } /** * @method * @name binance#fetchOption * @description fetches option data that is commonly found in an option chain * @see https://developers.binance.com/docs/derivatives/option/market-data/24hr-Ticker-Price-Change-Statistics * @param {string} symbol unified market symbol * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} an [option chain structure]{@link https://docs.ccxt.com/#/?id=option-chain-structure} */ func (this *binance) FetchOption(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 retRes135448 := (<-this.LoadMarkets()) PanicOnError(retRes135448) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } response:= (<-this.EapiPublicGetTicker(this.Extend(request, params))) PanicOnError(response) // // [ // { // "symbol": "BTC-241227-80000-C", // "priceChange": "0", // "priceChangePercent": "0", // "lastPrice": "2750", // "lastQty": "0", // "open": "2750", // "high": "2750", // "low": "2750", // "volume": "0", // "amount": "0", // "bidPrice": "4880", // "askPrice": "0", // "openTime": 0, // "closeTime": 0, // "firstTradeId": 0, // "tradeCount": 0, // "strikePrice": "80000", // "exercisePrice": "63944.09893617" // } // ] // var chain interface{} = this.SafeDict(response, 0, map[string]interface{} {}) ch <- this.ParseOption(chain, nil, market) return nil }() return ch } func (this *binance) ParseOption(chain interface{}, optionalArgs ...interface{}) interface{} { // // { // "symbol": "BTC-241227-80000-C", // "priceChange": "0", // "priceChangePercent": "0", // "lastPrice": "2750", // "lastQty": "0", // "open": "2750", // "high": "2750", // "low": "2750", // "volume": "0", // "amount": "0", // "bidPrice": "4880", // "askPrice": "0", // "openTime": 0, // "closeTime": 0, // "firstTradeId": 0, // "tradeCount": 0, // "strikePrice": "80000", // "exercisePrice": "63944.09893617" // } // currency := GetArg(optionalArgs, 0, nil) _ = currency market := GetArg(optionalArgs, 1, nil) _ = market var marketId interface{} = this.SafeString(chain, "symbol") market = this.SafeMarket(marketId, market) return map[string]interface{} { "info": chain, "currency": nil, "symbol": GetValue(market, "symbol"), "timestamp": nil, "datetime": nil, "impliedVolatility": nil, "openInterest": nil, "bidPrice": this.SafeNumber(chain, "bidPrice"), "askPrice": this.SafeNumber(chain, "askPrice"), "midPrice": nil, "markPrice": nil, "lastPrice": this.SafeNumber(chain, "lastPrice"), "underlyingPrice": this.SafeNumber(chain, "exercisePrice"), "change": this.SafeNumber(chain, "priceChange"), "percentage": this.SafeNumber(chain, "priceChangePercent"), "baseVolume": this.SafeNumber(chain, "volume"), "quoteVolume": nil, } } /** * @method * @name binance#fetchMarginAdjustmentHistory * @description fetches the history of margin added or reduced from contract isolated positions * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Get-Position-Margin-Change-History * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/Get-Position-Margin-Change-History * @param {string} symbol unified market symbol * @param {string} [type] "add" or "reduce" * @param {int} [since] timestamp in ms of the earliest change to fetch * @param {int} [limit] the maximum amount of changes to fetch * @param {object} params extra parameters specific to the exchange api endpoint * @param {int} [params.until] timestamp in ms of the latest change to fetch * @returns {object[]} a list of [margin structures]{@link https://docs.ccxt.com/#/?id=margin-loan-structure} */ func (this *binance) FetchMarginAdjustmentHistory(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) symbol := GetArg(optionalArgs, 0, nil) _ = symbol typeVar := GetArg(optionalArgs, 1, nil) _ = typeVar since := GetArg(optionalArgs, 2, nil) _ = since limit := GetArg(optionalArgs, 3, nil) _ = limit params := GetArg(optionalArgs, 4, map[string]interface{} {}) _ = params retRes136398 := (<-this.LoadMarkets()) PanicOnError(retRes136398) if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchMarginAdjustmentHistory () requires a symbol argument"))) } var market interface{} = this.Market(symbol) var until interface{} = this.SafeInteger(params, "until") params = this.Omit(params, "until") var request interface{} = map[string]interface{} { "symbol": GetValue(market, "id"), } if IsTrue(!IsEqual(typeVar, nil)) { AddElementToObject(request, "type", Ternary(IsTrue((IsEqual(typeVar, "add"))), 1, 2)) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } if IsTrue(!IsEqual(until, nil)) { AddElementToObject(request, "endTime", until) } var response interface{} = nil if IsTrue(GetValue(market, "linear")) { response = (<-this.FapiPrivateGetPositionMarginHistory(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "inverse")) { response = (<-this.DapiPrivateGetPositionMarginHistory(this.Extend(request, params))) PanicOnError(response) } else { panic(BadRequest(Add(Add(this.Id, " fetchMarginAdjustmentHistory () is not supported for markets of type "), GetValue(market, "type")))) } // // [ // { // symbol: "XRPUSDT", // type: "1", // deltaType: "TRADE", // amount: "2.57148240", // asset: "USDT", // time: "1711046271555", // positionSide: "BOTH", // clientTranId: "" // } // ... // ] // var modifications interface{} = this.ParseMarginModifications(response) ch <- this.FilterBySymbolSinceLimit(modifications, symbol, since, limit) return nil }() return ch } /** * @method * @name binance#fetchConvertCurrencies * @description fetches all available currencies that can be converted * @see https://developers.binance.com/docs/convert/market-data/Query-order-quantity-precision-per-asset * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} an associative dictionary of currencies */ func (this *binance) FetchConvertCurrencies(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 retRes136978 := (<-this.LoadMarkets()) PanicOnError(retRes136978) response:= (<-this.SapiGetConvertAssetInfo(params)) PanicOnError(response) // // [ // { // "asset": "BTC", // "fraction": 8 // }, // ] // var result interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) var id interface{} = this.SafeString(entry, "asset") var code interface{} = this.SafeCurrencyCode(id) AddElementToObject(result, code, map[string]interface{} { "info": entry, "id": id, "code": code, "networks": nil, "type": nil, "name": nil, "active": nil, "deposit": nil, "withdraw": nil, "fee": nil, "precision": this.ParseNumber(this.ParsePrecision(this.SafeString(entry, "fraction"))), "limits": map[string]interface{} { "amount": map[string]interface{} { "min": nil, "max": nil, }, "withdraw": map[string]interface{} { "min": nil, "max": nil, }, "deposit": map[string]interface{} { "min": nil, "max": nil, }, }, "created": nil, }) } ch <- result return nil }() return ch } /** * @method * @name binance#fetchConvertQuote * @description fetch a quote for converting from one currency to another * @see https://developers.binance.com/docs/convert/trade/Send-quote-request * @param {string} fromCode the currency that you want to sell and convert from * @param {string} toCode the currency that you want to buy and convert into * @param {float} amount how much you want to trade in units of the from currency * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.walletType] either 'SPOT' or 'FUNDING', the default is 'SPOT' * @returns {object} a [conversion structure]{@link https://docs.ccxt.com/#/?id=conversion-structure} */ func (this *binance) FetchConvertQuote(fromCode interface{}, toCode interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) amount := GetArg(optionalArgs, 0, nil) _ = amount params := GetArg(optionalArgs, 1, map[string]interface{} {}) _ = params if IsTrue(IsEqual(amount, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchConvertQuote() requires an amount argument"))) } retRes137608 := (<-this.LoadMarkets()) PanicOnError(retRes137608) var request interface{} = map[string]interface{} { "fromAsset": fromCode, "toAsset": toCode, "fromAmount": amount, } response:= (<-this.SapiPostConvertGetQuote(this.Extend(request, params))) PanicOnError(response) // // { // "quoteId":"12415572564", // "ratio":"38163.7", // "inverseRatio":"0.0000262", // "validTimestamp":1623319461670, // "toAmount":"3816.37", // "fromAmount":"0.1" // } // var fromCurrency interface{} = this.Currency(fromCode) var toCurrency interface{} = this.Currency(toCode) ch <- this.ParseConversion(response, fromCurrency, toCurrency) return nil }() return ch } /** * @method * @name binance#createConvertTrade * @description convert from one currency to another * @see https://developers.binance.com/docs/convert/trade/Accept-Quote * @param {string} id the id of the trade that you want to make * @param {string} fromCode the currency that you want to sell and convert from * @param {string} toCode the currency that you want to buy and convert into * @param {float} [amount] how much you want to trade in units of the from currency * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [conversion structure]{@link https://docs.ccxt.com/#/?id=conversion-structure} */ func (this *binance) CreateConvertTrade(id interface{}, fromCode interface{}, toCode interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) amount := GetArg(optionalArgs, 0, nil) _ = amount params := GetArg(optionalArgs, 1, map[string]interface{} {}) _ = params retRes137958 := (<-this.LoadMarkets()) PanicOnError(retRes137958) var request interface{} = map[string]interface{} {} var response interface{} = nil if IsTrue(IsTrue((IsEqual(fromCode, "BUSD"))) || IsTrue((IsEqual(toCode, "BUSD")))) { if IsTrue(IsEqual(amount, nil)) { panic(ArgumentsRequired(Add(this.Id, " createConvertTrade() requires an amount argument"))) } AddElementToObject(request, "clientTranId", id) AddElementToObject(request, "asset", fromCode) AddElementToObject(request, "targetAsset", toCode) AddElementToObject(request, "amount", amount) response = (<-this.SapiPostAssetConvertTransfer(this.Extend(request, params))) PanicOnError(response) } else { AddElementToObject(request, "quoteId", id) response = (<-this.SapiPostConvertAcceptQuote(this.Extend(request, params))) PanicOnError(response) } var fromCurrency interface{} = this.Currency(fromCode) var toCurrency interface{} = this.Currency(toCode) ch <- this.ParseConversion(response, fromCurrency, toCurrency) return nil }() return ch } /** * @method * @name binance#fetchConvertTrade * @description fetch the data for a conversion trade * @see https://developers.binance.com/docs/convert/trade/Order-Status * @param {string} id the id of the trade that you want to fetch * @param {string} [code] the unified currency code of the conversion trade * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [conversion structure]{@link https://docs.ccxt.com/#/?id=conversion-structure} */ func (this *binance) FetchConvertTrade(id interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) code := GetArg(optionalArgs, 0, nil) _ = code params := GetArg(optionalArgs, 1, map[string]interface{} {}) _ = params retRes138408 := (<-this.LoadMarkets()) PanicOnError(retRes138408) var request interface{} = map[string]interface{} {} var response interface{} = nil if IsTrue(IsEqual(code, "BUSD")) { var msInDay interface{} = 86400000 var now interface{} = this.Milliseconds() if IsTrue(!IsEqual(code, nil)) { var currency interface{} = this.Currency(code) AddElementToObject(request, "asset", GetValue(currency, "id")) } AddElementToObject(request, "tranId", id) AddElementToObject(request, "startTime", Subtract(now, msInDay)) AddElementToObject(request, "endTime", now) response = (<-this.SapiGetAssetConvertTransferQueryByPage(this.Extend(request, params))) PanicOnError(response) } else { AddElementToObject(request, "orderId", id) response = (<-this.SapiGetConvertOrderStatus(this.Extend(request, params))) PanicOnError(response) } var data interface{} = response if IsTrue(IsEqual(code, "BUSD")) { var rows interface{} = this.SafeList(response, "rows", []interface{}{}) data = this.SafeDict(rows, 0, map[string]interface{} {}) } var fromCurrencyId interface{} = this.SafeString2(data, "deductedAsset", "fromAsset") var toCurrencyId interface{} = this.SafeString2(data, "targetAsset", "toAsset") var fromCurrency interface{} = nil var toCurrency interface{} = nil if IsTrue(!IsEqual(fromCurrencyId, nil)) { fromCurrency = this.Currency(fromCurrencyId) } if IsTrue(!IsEqual(toCurrencyId, nil)) { toCurrency = this.Currency(toCurrencyId) } ch <- this.ParseConversion(data, fromCurrency, toCurrency) return nil }() return ch } /** * @method * @name binance#fetchConvertTradeHistory * @description fetch the users history of conversion trades * @see https://developers.binance.com/docs/convert/trade/Get-Convert-Trade-History * @param {string} [code] the unified currency code * @param {int} [since] the earliest time in ms to fetch conversions for * @param {int} [limit] the maximum number of conversion structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.until] timestamp in ms of the latest conversion to fetch * @returns {object[]} a list of [conversion structures]{@link https://docs.ccxt.com/#/?id=conversion-structure} */ func (this *binance) FetchConvertTradeHistory(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 retRes139208 := (<-this.LoadMarkets()) PanicOnError(retRes139208) var request interface{} = map[string]interface{} {} var msInThirtyDays interface{} = 2592000000 var now interface{} = this.Milliseconds() if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "startTime", since) } else { AddElementToObject(request, "startTime", Subtract(now, msInThirtyDays)) } var endTime interface{} = this.SafeInteger2(params, "endTime", "until") if IsTrue(!IsEqual(endTime, nil)) { AddElementToObject(request, "endTime", endTime) } else { AddElementToObject(request, "endTime", now) } params = this.Omit(params, "until") var response interface{} = nil var responseQuery interface{} = nil var fromCurrencyKey interface{} = nil var toCurrencyKey interface{} = nil if IsTrue(IsEqual(code, "BUSD")) { var currency interface{} = this.Currency(code) AddElementToObject(request, "asset", GetValue(currency, "id")) if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "size", limit) } fromCurrencyKey = "deductedAsset" toCurrencyKey = "targetAsset" responseQuery = "rows" response = (<-this.SapiGetAssetConvertTransferQueryByPage(this.Extend(request, params))) PanicOnError(response) } else { if IsTrue(IsGreaterThan((Subtract(GetValue(request, "endTime"), GetValue(request, "startTime"))), msInThirtyDays)) { panic(BadRequest(Add(this.Id, " fetchConvertTradeHistory () the max interval between startTime and endTime is 30 days."))) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } fromCurrencyKey = "fromAsset" toCurrencyKey = "toAsset" responseQuery = "list" response = (<-this.SapiGetConvertTradeFlow(this.Extend(request, params))) PanicOnError(response) } var rows interface{} = this.SafeList(response, responseQuery, []interface{}{}) ch <- this.ParseConversions(rows, code, fromCurrencyKey, toCurrencyKey, since, limit) return nil }() return ch } func (this *binance) ParseConversion(conversion interface{}, optionalArgs ...interface{}) interface{} { // // fetchConvertQuote // // { // "quoteId":"12415572564", // "ratio":"38163.7", // "inverseRatio":"0.0000262", // "validTimestamp":1623319461670, // "toAmount":"3816.37", // "fromAmount":"0.1" // } // // createConvertTrade // // { // "orderId":"933256278426274426", // "createTime":1623381330472, // "orderStatus":"PROCESS" // } // // createConvertTrade BUSD // // { // "tranId": 118263407119, // "status": "S" // } // // fetchConvertTrade, fetchConvertTradeHistory BUSD // // { // "tranId": 118263615991, // "type": 244, // "time": 1664442078000, // "deductedAsset": "BUSD", // "deductedAmount": "1", // "targetAsset": "USDC", // "targetAmount": "1", // "status": "S", // "accountType": "MAIN" // } // // fetchConvertTrade // // { // "orderId":933256278426274426, // "orderStatus":"SUCCESS", // "fromAsset":"BTC", // "fromAmount":"0.00054414", // "toAsset":"USDT", // "toAmount":"20", // "ratio":"36755", // "inverseRatio":"0.00002721", // "createTime":1623381330472 // } // // fetchConvertTradeHistory // // { // "quoteId": "f3b91c525b2644c7bc1e1cd31b6e1aa6", // "orderId": 940708407462087195, // "orderStatus": "SUCCESS", // "fromAsset": "USDT", // "fromAmount": "20", // "toAsset": "BNB", // "toAmount": "0.06154036", // "ratio": "0.00307702", // "inverseRatio": "324.99", // "createTime": 1624248872184 // } // fromCurrency := GetArg(optionalArgs, 0, nil) _ = fromCurrency toCurrency := GetArg(optionalArgs, 1, nil) _ = toCurrency var timestamp interface{} = this.SafeIntegerN(conversion, []interface{}{"time", "validTimestamp", "createTime"}) var fromCur interface{} = this.SafeString2(conversion, "deductedAsset", "fromAsset") var fromCode interface{} = this.SafeCurrencyCode(fromCur, fromCurrency) var to interface{} = this.SafeString2(conversion, "targetAsset", "toAsset") var toCode interface{} = this.SafeCurrencyCode(to, toCurrency) return map[string]interface{} { "info": conversion, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "id": this.SafeStringN(conversion, []interface{}{"tranId", "orderId", "quoteId"}), "fromCurrency": fromCode, "fromAmount": this.SafeNumber2(conversion, "deductedAmount", "fromAmount"), "toCurrency": toCode, "toAmount": this.SafeNumber2(conversion, "targetAmount", "toAmount"), "price": nil, "fee": nil, } } /** * @method * @name binance#fetchFundingIntervals * @description fetch the funding rate interval for multiple markets * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Get-Funding-Info * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Get-Funding-Info * @param {string[]} [symbols] list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.subType] "linear" or "inverse" * @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/#/?id=funding-rate-structure} */ func (this *binance) FetchFundingIntervals(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 retRes141088 := (<-this.LoadMarkets()) PanicOnError(retRes141088) var market interface{} = nil if IsTrue(!IsEqual(symbols, nil)) { symbols = this.MarketSymbols(symbols) market = this.Market(GetValue(symbols, 0)) } var typeVar interface{} = "swap" var subType interface{} = nil subTypeparamsVariable := this.HandleSubTypeAndParams("fetchFundingIntervals", market, params, "linear"); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var response interface{} = nil if IsTrue(this.IsLinear(typeVar, subType)) { response = (<-this.FapiPublicGetFundingInfo(params)) PanicOnError(response) } else if IsTrue(this.IsInverse(typeVar, subType)) { response = (<-this.DapiPublicGetFundingInfo(params)) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchFundingIntervals() supports linear and inverse swap contracts only"))) } // // [ // { // "symbol": "BLZUSDT", // "adjustedFundingRateCap": "0.03000000", // "adjustedFundingRateFloor": "-0.03000000", // "fundingIntervalHours": 4, // "disclaimer": false // }, // ] // ch <- this.ParseFundingRates(response, symbols) return nil }() return ch } /** * @method * @name binance#fetchLongShortRatioHistory * @description fetches the long short ratio history for a unified market symbol * @see https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Long-Short-Ratio * @see https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/Long-Short-Ratio * @param {string} symbol unified symbol of the market to fetch the long short ratio for * @param {string} [timeframe] the period for the ratio, default is 24 hours * @param {int} [since] the earliest time in ms to fetch ratios for * @param {int} [limit] the maximum number of long short ratio structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.until] timestamp in ms of the latest ratio to fetch * @returns {object[]} an array of [long short ratio structures]{@link https://docs.ccxt.com/#/?id=long-short-ratio-structure} */ func (this *binance) FetchLongShortRatioHistory(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) symbol := GetArg(optionalArgs, 0, nil) _ = symbol timeframe := GetArg(optionalArgs, 1, nil) _ = timeframe since := GetArg(optionalArgs, 2, nil) _ = since limit := GetArg(optionalArgs, 3, nil) _ = limit params := GetArg(optionalArgs, 4, map[string]interface{} {}) _ = params retRes141548 := (<-this.LoadMarkets()) PanicOnError(retRes141548) var market interface{} = this.Market(symbol) if IsTrue(IsEqual(timeframe, nil)) { timeframe = "1d" } var request interface{} = map[string]interface{} { "period": timeframe, } requestparamsVariable := this.HandleUntilOption("endTime", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) 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("fetchLongShortRatioHistory", market, params); subType = GetValue(subTypeparamsVariable,0); params = GetValue(subTypeparamsVariable,1) var response interface{} = nil if IsTrue(IsEqual(subType, "linear")) { AddElementToObject(request, "symbol", GetValue(market, "id")) response = (<-this.FapiDataGetGlobalLongShortAccountRatio(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(subType, "inverse")) { AddElementToObject(request, "pair", GetValue(GetValue(market, "info"), "pair")) response = (<-this.DapiDataGetGlobalLongShortAccountRatio(this.Extend(request, params))) PanicOnError(response) } else { panic(BadRequest(Add(this.Id, " fetchLongShortRatioHistory() supports linear and inverse subTypes only"))) } ch <- this.ParseLongShortRatioHistory(response, market) return nil }() return ch } func (this *binance) ParseLongShortRatio(info interface{}, optionalArgs ...interface{}) interface{} { // // linear // // { // "symbol": "BTCUSDT", // "longAccount": "0.4558", // "longShortRatio": "0.8376", // "shortAccount": "0.5442", // "timestamp": 1726790400000 // } // // inverse // // { // "longAccount": "0.7262", // "longShortRatio": "2.6523", // "shortAccount": "0.2738", // "pair": "BTCUSD", // "timestamp": 1726790400000 // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(info, "symbol") var timestamp interface{} = this.SafeIntegerOmitZero(info, "timestamp") return map[string]interface{} { "info": info, "symbol": this.SafeSymbol(marketId, market, nil, "contract"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "timeframe": nil, "longShortRatio": this.SafeNumber(info, "longShortRatio"), } } func (this *binance) Init(userConfig map[string]interface{}) { this.Exchange = Exchange{} this.Exchange.InitParent(userConfig, this.Describe().(map[string]interface{}), this) this.Exchange.DerivedExchange = this }