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 gate struct { Exchange } func NewGateCore() gate { p := gate{} setDefaults(&p) return p } func (this *gate) Describe() interface{} { return this.DeepExtend(this.Exchange.Describe(), map[string]interface{} { "id": "gate", "name": "Gate.io", "countries": []interface{}{"KR"}, "rateLimit": 50, "version": "v4", "certified": true, "pro": true, "urls": map[string]interface{} { "logo": "https://github.com/user-attachments/assets/64f988c5-07b6-4652-b5c1-679a6bf67c85", "doc": "https://www.gate.io/docs/developers/apiv4/en/", "www": "https://gate.io/", "api": map[string]interface{} { "public": map[string]interface{} { "wallet": "https://api.gateio.ws/api/v4", "futures": "https://api.gateio.ws/api/v4", "margin": "https://api.gateio.ws/api/v4", "delivery": "https://api.gateio.ws/api/v4", "spot": "https://api.gateio.ws/api/v4", "options": "https://api.gateio.ws/api/v4", "sub_accounts": "https://api.gateio.ws/api/v4", "earn": "https://api.gateio.ws/api/v4", }, "private": map[string]interface{} { "withdrawals": "https://api.gateio.ws/api/v4", "wallet": "https://api.gateio.ws/api/v4", "futures": "https://api.gateio.ws/api/v4", "margin": "https://api.gateio.ws/api/v4", "delivery": "https://api.gateio.ws/api/v4", "spot": "https://api.gateio.ws/api/v4", "options": "https://api.gateio.ws/api/v4", "subAccounts": "https://api.gateio.ws/api/v4", "unified": "https://api.gateio.ws/api/v4", "rebate": "https://api.gateio.ws/api/v4", "earn": "https://api.gateio.ws/api/v4", "account": "https://api.gateio.ws/api/v4", "loan": "https://api.gateio.ws/api/v4", }, }, "test": map[string]interface{} { "public": map[string]interface{} { "futures": "https://fx-api-testnet.gateio.ws/api/v4", "delivery": "https://fx-api-testnet.gateio.ws/api/v4", "options": "https://fx-api-testnet.gateio.ws/api/v4", }, "private": map[string]interface{} { "futures": "https://fx-api-testnet.gateio.ws/api/v4", "delivery": "https://fx-api-testnet.gateio.ws/api/v4", "options": "https://fx-api-testnet.gateio.ws/api/v4", }, }, "referral": map[string]interface{} { "url": "https://www.gate.io/signup/2436035", "discount": 0.2, }, }, "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, "cancelOrdersForSymbols": true, "createMarketBuyOrderWithCost": true, "createMarketOrder": true, "createMarketOrderWithCost": false, "createMarketSellOrderWithCost": false, "createOrder": true, "createOrders": true, "createPostOnlyOrder": true, "createReduceOnlyOrder": true, "createStopLimitOrder": true, "createStopLossOrder": true, "createStopMarketOrder": false, "createStopOrder": true, "createTakeProfitOrder": true, "createTriggerOrder": true, "editOrder": true, "fetchBalance": true, "fetchBorrowInterest": true, "fetchBorrowRateHistories": false, "fetchBorrowRateHistory": false, "fetchClosedOrders": true, "fetchCrossBorrowRate": false, "fetchCrossBorrowRates": false, "fetchCurrencies": true, "fetchDepositAddress": true, "fetchDepositAddresses": false, "fetchDepositAddressesByNetwork": false, "fetchDeposits": true, "fetchDepositWithdrawFee": "emulated", "fetchDepositWithdrawFees": true, "fetchFundingHistory": true, "fetchFundingRate": true, "fetchFundingRateHistory": true, "fetchFundingRates": true, "fetchGreeks": true, "fetchIndexOHLCV": true, "fetchIsolatedBorrowRate": false, "fetchIsolatedBorrowRates": false, "fetchLedger": true, "fetchLeverage": true, "fetchLeverages": true, "fetchLeverageTiers": true, "fetchLiquidations": true, "fetchMarginAdjustmentHistory": false, "fetchMarginMode": false, "fetchMarketLeverageTiers": true, "fetchMarkets": true, "fetchMarkOHLCV": true, "fetchMyLiquidations": true, "fetchMySettlementHistory": true, "fetchMyTrades": true, "fetchNetworkDepositAddress": true, "fetchOHLCV": true, "fetchOpenInterest": false, "fetchOpenInterestHistory": true, "fetchOpenOrders": true, "fetchOption": true, "fetchOptionChain": true, "fetchOrder": true, "fetchOrderBook": true, "fetchPosition": true, "fetchPositionHistory": "emulated", "fetchPositionMode": false, "fetchPositions": true, "fetchPositionsHistory": true, "fetchPremiumIndexOHLCV": false, "fetchSettlementHistory": true, "fetchTicker": true, "fetchTickers": true, "fetchTime": true, "fetchTrades": true, "fetchTradingFee": true, "fetchTradingFees": true, "fetchTransactionFees": true, "fetchUnderlyingAssets": true, "fetchVolatilityHistory": false, "fetchWithdrawals": true, "reduceMargin": true, "repayCrossMargin": true, "repayIsolatedMargin": true, "sandbox": true, "setLeverage": true, "setMarginMode": false, "setPositionMode": true, "signIn": false, "transfer": true, "withdraw": true, }, "api": map[string]interface{} { "public": map[string]interface{} { "wallet": map[string]interface{} { "get": map[string]interface{} { "currency_chains": 1, }, }, "spot": map[string]interface{} { "get": map[string]interface{} { "currencies": 1, "currencies/{currency}": 1, "currency_pairs": 1, "currency_pairs/{currency_pair}": 1, "tickers": 1, "order_book": 1, "trades": 1, "candlesticks": 1, "time": 1, }, }, "margin": map[string]interface{} { "get": map[string]interface{} { "currency_pairs": 1, "currency_pairs/{currency_pair}": 1, "funding_book": 1, "cross/currencies": 1, "cross/currencies/{currency}": 1, "uni/currency_pairs": 1, "uni/currency_pairs/{currency_pair}": 1, }, }, "flash_swap": map[string]interface{} { "get": map[string]interface{} { "currencies": 1, }, }, "futures": map[string]interface{} { "get": map[string]interface{} { "{settle}/contracts": 1, "{settle}/contracts/{contract}": 1, "{settle}/order_book": 1, "{settle}/trades": 1, "{settle}/candlesticks": 1, "{settle}/premium_index": 1, "{settle}/tickers": 1, "{settle}/funding_rate": 1, "{settle}/insurance": 1, "{settle}/contract_stats": 1, "{settle}/index_constituents/{index}": 1, "{settle}/liq_orders": 1, "{settle}/risk_limit_tiers": 1, }, }, "delivery": map[string]interface{} { "get": map[string]interface{} { "{settle}/contracts": 1, "{settle}/contracts/{contract}": 1, "{settle}/order_book": 1, "{settle}/trades": 1, "{settle}/candlesticks": 1, "{settle}/tickers": 1, "{settle}/insurance": 1, }, }, "options": map[string]interface{} { "get": map[string]interface{} { "underlyings": 1, "expirations": 1, "contracts": 1, "contracts/{contract}": 1, "settlements": 1, "settlements/{contract}": 1, "order_book": 1, "tickers": 1, "underlying/tickers/{underlying}": 1, "candlesticks": 1, "underlying/candlesticks": 1, "trades": 1, }, }, "earn": map[string]interface{} { "get": map[string]interface{} { "uni/currencies": 1, "uni/currencies/{currency}": 1, }, }, }, "private": map[string]interface{} { "withdrawals": map[string]interface{} { "post": map[string]interface{} { "withdrawals": 20, "push": 1, }, "delete": map[string]interface{} { "withdrawals/{withdrawal_id}": 1, }, }, "wallet": map[string]interface{} { "get": map[string]interface{} { "deposit_address": 1, "withdrawals": 1, "deposits": 1, "sub_account_transfers": 1, "order_status": 1, "withdraw_status": 1, "sub_account_balances": 2.5, "sub_account_margin_balances": 2.5, "sub_account_futures_balances": 2.5, "sub_account_cross_margin_balances": 2.5, "saved_address": 1, "fee": 1, "total_balance": 2.5, "small_balance": 1, "small_balance_history": 1, "push": 1, }, "post": map[string]interface{} { "transfers": 2.5, "sub_account_transfers": 2.5, "sub_account_to_sub_account": 2.5, "small_balance": 1, }, }, "subAccounts": map[string]interface{} { "get": map[string]interface{} { "sub_accounts": 2.5, "sub_accounts/{user_id}": 2.5, "sub_accounts/{user_id}/keys": 2.5, "sub_accounts/{user_id}/keys/{key}": 2.5, }, "post": map[string]interface{} { "sub_accounts": 2.5, "sub_accounts/{user_id}/keys": 2.5, "sub_accounts/{user_id}/lock": 2.5, "sub_accounts/{user_id}/unlock": 2.5, }, "put": map[string]interface{} { "sub_accounts/{user_id}/keys/{key}": 2.5, }, "delete": map[string]interface{} { "sub_accounts/{user_id}/keys/{key}": 2.5, }, }, "unified": map[string]interface{} { "get": map[string]interface{} { "accounts": Divide(20, 15), "account_mode": Divide(20, 15), "borrowable": Divide(20, 15), "transferable": Divide(20, 15), "loans": Divide(20, 15), "loan_records": Divide(20, 15), "interest_records": Divide(20, 15), "estimate_rate": Divide(20, 15), "currency_discount_tiers": Divide(20, 15), "risk_units": Divide(20, 15), "unified_mode": Divide(20, 15), "loan_margin_tiers": Divide(20, 15), "leverage/user_currency_config": Divide(20, 15), "leverage/user_currency_setting": Divide(20, 15), }, "post": map[string]interface{} { "account_mode": Divide(20, 15), "loans": Divide(200, 15), "portfolio_calculator": Divide(20, 15), "leverage/user_currency_setting": Divide(20, 15), }, "put": map[string]interface{} { "unified_mode": Divide(20, 15), }, }, "spot": map[string]interface{} { "get": map[string]interface{} { "fee": 1, "batch_fee": 1, "accounts": 1, "account_book": 1, "open_orders": 1, "orders": 1, "orders/{order_id}": 1, "my_trades": 1, "price_orders": 1, "price_orders/{order_id}": 1, }, "post": map[string]interface{} { "batch_orders": 0.4, "cross_liquidate_orders": 1, "orders": 0.4, "cancel_batch_orders": Divide(20, 75), "countdown_cancel_all": Divide(20, 75), "amend_batch_orders": 0.4, "price_orders": 0.4, }, "delete": map[string]interface{} { "orders": Divide(20, 75), "orders/{order_id}": Divide(20, 75), "price_orders": Divide(20, 75), "price_orders/{order_id}": Divide(20, 75), }, "patch": map[string]interface{} { "orders/{order_id}": 0.4, }, }, "margin": map[string]interface{} { "get": map[string]interface{} { "accounts": Divide(20, 15), "account_book": Divide(20, 15), "funding_accounts": Divide(20, 15), "auto_repay": Divide(20, 15), "transferable": Divide(20, 15), "loans": Divide(20, 15), "loans/{loan_id}": Divide(20, 15), "loans/{loan_id}/repayment": Divide(20, 15), "loan_records": Divide(20, 15), "loan_records/{loan_record_id}": Divide(20, 15), "borrowable": Divide(20, 15), "cross/accounts": Divide(20, 15), "cross/account_book": Divide(20, 15), "cross/loans": Divide(20, 15), "cross/loans/{loan_id}": Divide(20, 15), "cross/repayments": Divide(20, 15), "cross/interest_records": Divide(20, 15), "cross/transferable": Divide(20, 15), "cross/estimate_rate": Divide(20, 15), "cross/borrowable": Divide(20, 15), "uni/estimate_rate": Divide(20, 15), "uni/loans": Divide(20, 15), "uni/loan_records": Divide(20, 15), "uni/interest_records": Divide(20, 15), "uni/borrowable": Divide(20, 15), }, "post": map[string]interface{} { "auto_repay": Divide(20, 15), "loans": Divide(20, 15), "merged_loans": Divide(20, 15), "loans/{loan_id}/repayment": Divide(20, 15), "cross/loans": Divide(20, 15), "cross/repayments": Divide(20, 15), "uni/loans": Divide(20, 15), }, "patch": map[string]interface{} { "loans/{loan_id}": Divide(20, 15), "loan_records/{loan_record_id}": Divide(20, 15), }, "delete": map[string]interface{} { "loans/{loan_id}": Divide(20, 15), }, }, "flash_swap": map[string]interface{} { "get": map[string]interface{} { "currencies": 1, "currency_pairs": 1, "orders": 1, "orders/{order_id}": 1, }, "post": map[string]interface{} { "orders": 1, "orders/preview": 1, }, }, "futures": map[string]interface{} { "get": map[string]interface{} { "{settle}/accounts": 1, "{settle}/account_book": 1, "{settle}/positions": 1, "{settle}/positions/{contract}": 1, "{settle}/dual_comp/positions/{contract}": 1, "{settle}/orders": 1, "{settle}/orders_timerange": 1, "{settle}/orders/{order_id}": 1, "{settle}/my_trades": 1, "{settle}/my_trades_timerange": 1, "{settle}/position_close": 1, "{settle}/liquidates": 1, "{settle}/auto_deleverages": 1, "{settle}/fee": 1, "{settle}/risk_limit_tiers": 1, "{settle}/price_orders": 1, "{settle}/price_orders/{order_id}": 1, }, "post": map[string]interface{} { "{settle}/positions/{contract}/margin": 1, "{settle}/positions/{contract}/leverage": 1, "{settle}/positions/{contract}/risk_limit": 1, "{settle}/dual_mode": 1, "{settle}/dual_comp/positions/{contract}/margin": 1, "{settle}/dual_comp/positions/{contract}/leverage": 1, "{settle}/dual_comp/positions/{contract}/risk_limit": 1, "{settle}/orders": 0.4, "{settle}/batch_orders": 0.4, "{settle}/countdown_cancel_all": 0.4, "{settle}/batch_cancel_orders": 0.4, "{settle}/price_orders": 0.4, }, "put": map[string]interface{} { "{settle}/orders/{order_id}": 1, }, "delete": map[string]interface{} { "{settle}/orders": Divide(20, 75), "{settle}/orders/{order_id}": Divide(20, 75), "{settle}/price_orders": Divide(20, 75), "{settle}/price_orders/{order_id}": Divide(20, 75), }, }, "delivery": map[string]interface{} { "get": map[string]interface{} { "{settle}/accounts": Divide(20, 15), "{settle}/account_book": Divide(20, 15), "{settle}/positions": Divide(20, 15), "{settle}/positions/{contract}": Divide(20, 15), "{settle}/orders": Divide(20, 15), "{settle}/orders/{order_id}": Divide(20, 15), "{settle}/my_trades": Divide(20, 15), "{settle}/position_close": Divide(20, 15), "{settle}/liquidates": Divide(20, 15), "{settle}/settlements": Divide(20, 15), "{settle}/price_orders": Divide(20, 15), "{settle}/price_orders/{order_id}": Divide(20, 15), }, "post": map[string]interface{} { "{settle}/positions/{contract}/margin": Divide(20, 15), "{settle}/positions/{contract}/leverage": Divide(20, 15), "{settle}/positions/{contract}/risk_limit": Divide(20, 15), "{settle}/orders": Divide(20, 15), "{settle}/price_orders": Divide(20, 15), }, "delete": map[string]interface{} { "{settle}/orders": Divide(20, 15), "{settle}/orders/{order_id}": Divide(20, 15), "{settle}/price_orders": Divide(20, 15), "{settle}/price_orders/{order_id}": Divide(20, 15), }, }, "options": map[string]interface{} { "get": map[string]interface{} { "my_settlements": Divide(20, 15), "accounts": Divide(20, 15), "account_book": Divide(20, 15), "positions": Divide(20, 15), "positions/{contract}": Divide(20, 15), "position_close": Divide(20, 15), "orders": Divide(20, 15), "orders/{order_id}": Divide(20, 15), "my_trades": Divide(20, 15), "mmp": Divide(20, 15), }, "post": map[string]interface{} { "orders": Divide(20, 15), "countdown_cancel_all": Divide(20, 15), "mmp": Divide(20, 15), "mmp/reset": Divide(20, 15), }, "delete": map[string]interface{} { "orders": Divide(20, 15), "orders/{order_id}": Divide(20, 15), }, }, "earn": map[string]interface{} { "get": map[string]interface{} { "uni/currencies": Divide(20, 15), "uni/currencies/{currency}": Divide(20, 15), "uni/lends": Divide(20, 15), "uni/lend_records": Divide(20, 15), "uni/interests/{currency}": Divide(20, 15), "uni/interest_records": Divide(20, 15), "uni/interest_status/{currency}": Divide(20, 15), }, "post": map[string]interface{} { "uni/lends": Divide(20, 15), }, "put": map[string]interface{} { "uni/interest_reinvest": Divide(20, 15), }, "patch": map[string]interface{} { "uni/lends": Divide(20, 15), }, }, "loan": map[string]interface{} { "get": map[string]interface{} { "collateral/orders": Divide(20, 15), "collateral/orders/{order_id}": Divide(20, 15), "collateral/repay_records": Divide(20, 15), "collateral/collaterals": Divide(20, 15), "collateral/total_amount": Divide(20, 15), "collateral/ltv": Divide(20, 15), "collateral/currencies": Divide(20, 15), "multi_collateral/orders": Divide(20, 15), "multi_collateral/orders/{order_id}": Divide(20, 15), "multi_collateral/repay": Divide(20, 15), "multi_collateral/mortgage": Divide(20, 15), "multi_collateral/currency_quota": Divide(20, 15), "multi_collateral/currencies": Divide(20, 15), "multi_collateral/ltv": Divide(20, 15), "multi_collateral/fixed_rate": Divide(20, 15), "multi_collateral/current_rate": Divide(20, 15), }, "post": map[string]interface{} { "collateral/orders": Divide(20, 15), "collateral/repay": Divide(20, 15), "collateral/collaterals": Divide(20, 15), "multi_collateral/orders": Divide(20, 15), "multi_collateral/repay": Divide(20, 15), "multi_collateral/mortgage": Divide(20, 15), }, }, "account": map[string]interface{} { "get": map[string]interface{} { "detail": Divide(20, 15), "rate_limit": Divide(20, 15), "stp_groups": Divide(20, 15), "stp_groups/{stp_id}/users": Divide(20, 15), "stp_groups/debit_fee": Divide(20, 15), }, "post": map[string]interface{} { "stp_groups": Divide(20, 15), "stp_groups/{stp_id}/users": Divide(20, 15), }, "delete": map[string]interface{} { "stp_groups/{stp_id}/users": Divide(20, 15), }, }, "rebate": map[string]interface{} { "get": map[string]interface{} { "agency/transaction_history": Divide(20, 15), "agency/commission_history": Divide(20, 15), }, }, }, }, "timeframes": map[string]interface{} { "10s": "10s", "1m": "1m", "5m": "5m", "15m": "15m", "30m": "30m", "1h": "1h", "2h": "2h", "4h": "4h", "8h": "8h", "1d": "1d", "7d": "7d", "1w": "7d", }, "commonCurrencies": map[string]interface{} { "ORT": "XREATORS", "ASS": "ASSF", "88MPH": "MPH", "AXIS": "AXISDEFI", "BIFI": "BITCOINFILE", "BOX": "DEFIBOX", "BYN": "BEYONDFI", "EGG": "GOOSEFINANCE", "GTC": "GAMECOM", "GTC_HT": "GAMECOM_HT", "GTC_BSC": "GAMECOM_BSC", "HIT": "HITCHAIN", "MM": "MILLION", "MPH": "MORPHER", "POINT": "GATEPOINT", "RAI": "RAIREFLEXINDEX", "RED": "RedLang", "SBTC": "SUPERBITCOIN", "TNC": "TRINITYNETWORKCREDIT", "VAI": "VAIOT", "TRAC": "TRACO", }, "requiredCredentials": map[string]interface{} { "apiKey": true, "secret": true, }, "headers": map[string]interface{} { "X-Gate-Channel-Id": "ccxt", }, "options": map[string]interface{} { "timeDifference": 0, "adjustForTimeDifference": false, "sandboxMode": false, "unifiedAccount": nil, "createOrder": map[string]interface{} { "expiration": 86400, }, "createMarketBuyOrderRequiresPrice": true, "networks": map[string]interface{} { "BTC": "BTC", "BRC20": "BTCBRC", "ETH": "ETH", "ERC20": "ETH", "TRX": "TRX", "TRC20": "TRX", "HECO": "HT", "HRC20": "HT", "BSC": "BSC", "BEP20": "BSC", "SOL": "SOL", "POLYGON": "POL", "MATIC": "POL", "OP": "OPETH", "OPTIMISM": "OPETH", "ADA": "ADA", "AVAXC": "AVAX_C", "NEAR": "NEAR", "ARBONE": "ARBEVM", "BASE": "BASEEVM", "SUI": "SUI", "CRONOS": "CRO", "CRO": "CRO", "APT": "APT", "SCROLL": "SCROLLETH", "TAIKO": "TAIKOETH", "HYPE": "HYPE", "ALGO": "ALGO", "LINEA": "LINEAETH", "BLAST": "BLASTETH", "XLM": "XLM", "RSK": "RBTC", "TON": "TON", "MNT": "MNT", "CELO": "CELO", "HBAR": "HBAR", "ZKSERA": "ZKSERA", "KLAY": "KLAY", "EOS": "EOS", "ACA": "ACA", "XTZ": "XTZ", "EGLD": "EGLD", "GLMR": "GLMR", "AURORA": "AURORAEVM", "KON": "KONET", "GATECHAIN": "GTEVM", "KUSAMA": "KSMSM", "OKC": "OKT", "POLKADOT": "DOTSM", "LUNA": "LUNC", }, "networksById": map[string]interface{} { "OPETH": "OP", }, "timeInForce": map[string]interface{} { "GTC": "gtc", "IOC": "ioc", "PO": "poc", "POC": "poc", "FOK": "fok", }, "accountsByType": map[string]interface{} { "funding": "spot", "spot": "spot", "margin": "margin", "cross_margin": "cross_margin", "cross": "cross_margin", "isolated": "margin", "swap": "futures", "future": "delivery", "futures": "futures", "delivery": "delivery", "option": "options", "options": "options", }, "swap": map[string]interface{} { "fetchMarkets": map[string]interface{} { "settlementCurrencies": []interface{}{"usdt", "btc"}, }, }, "future": map[string]interface{} { "fetchMarkets": map[string]interface{} { "settlementCurrencies": []interface{}{"usdt"}, }, }, }, "features": map[string]interface{} { "default": map[string]interface{} { "sandbox": true, "createOrder": map[string]interface{} { "marginMode": true, "triggerPrice": true, "triggerDirection": true, "triggerPriceType": nil, "stopLossPrice": true, "takeProfitPrice": true, "attachedStopLossTakeProfit": nil, "timeInForce": map[string]interface{} { "IOC": true, "FOK": true, "PO": true, "GTD": false, }, "hedged": false, "trailing": false, "iceberg": true, "selfTradePrevention": true, "leverage": false, "marketBuyByCost": true, "marketBuyRequiresPrice": true, }, "createOrders": map[string]interface{} { "max": 40, }, "fetchMyTrades": map[string]interface{} { "marginMode": true, "limit": 1000, "daysBack": nil, "untilDays": 30, "symbolRequired": false, }, "fetchOrder": map[string]interface{} { "marginMode": false, "trigger": true, "trailing": false, "symbolRequired": true, }, "fetchOpenOrders": map[string]interface{} { "marginMode": true, "trigger": true, "trailing": false, "limit": 100, "symbolRequired": false, }, "fetchOrders": nil, "fetchClosedOrders": map[string]interface{} { "marginMode": true, "trigger": true, "trailing": false, "limit": 100, "untilDays": 30, "daysBack": nil, "daysBackCanceled": nil, "symbolRequired": false, }, "fetchOHLCV": map[string]interface{} { "limit": 1000, }, }, "spot": map[string]interface{} { "extends": "default", }, "forDerivatives": map[string]interface{} { "extends": "spot", "createOrder": map[string]interface{} { "marginMode": false, "triggerPriceType": map[string]interface{} { "last": true, "mark": true, "index": true, }, }, "createOrders": map[string]interface{} { "max": 10, }, "fetchMyTrades": map[string]interface{} { "marginMode": false, "untilDays": nil, }, "fetchOpenOrders": map[string]interface{} { "marginMode": false, }, "fetchClosedOrders": map[string]interface{} { "marginMode": false, "untilDays": nil, "limit": 1000, }, "fetchOHLCV": map[string]interface{} { "limit": 1999, }, }, "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", }, }, }, "precisionMode": TICK_SIZE, "fees": map[string]interface{} { "trading": map[string]interface{} { "tierBased": true, "feeSide": "get", "percentage": true, "maker": this.ParseNumber("0.002"), "taker": this.ParseNumber("0.002"), "tiers": map[string]interface{} { "maker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.002")}, []interface{}{this.ParseNumber("1.5"), this.ParseNumber("0.00185")}, []interface{}{this.ParseNumber("3"), this.ParseNumber("0.00175")}, []interface{}{this.ParseNumber("6"), this.ParseNumber("0.00165")}, []interface{}{this.ParseNumber("12.5"), this.ParseNumber("0.00155")}, []interface{}{this.ParseNumber("25"), this.ParseNumber("0.00145")}, []interface{}{this.ParseNumber("75"), this.ParseNumber("0.00135")}, []interface{}{this.ParseNumber("200"), this.ParseNumber("0.00125")}, []interface{}{this.ParseNumber("500"), this.ParseNumber("0.00115")}, []interface{}{this.ParseNumber("1250"), this.ParseNumber("0.00105")}, []interface{}{this.ParseNumber("2500"), this.ParseNumber("0.00095")}, []interface{}{this.ParseNumber("3000"), this.ParseNumber("0.00085")}, []interface{}{this.ParseNumber("6000"), this.ParseNumber("0.00075")}, []interface{}{this.ParseNumber("11000"), this.ParseNumber("0.00065")}, []interface{}{this.ParseNumber("20000"), this.ParseNumber("0.00055")}, []interface{}{this.ParseNumber("40000"), this.ParseNumber("0.00055")}, []interface{}{this.ParseNumber("75000"), this.ParseNumber("0.00055")}}, "taker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.002")}, []interface{}{this.ParseNumber("1.5"), this.ParseNumber("0.00195")}, []interface{}{this.ParseNumber("3"), this.ParseNumber("0.00185")}, []interface{}{this.ParseNumber("6"), this.ParseNumber("0.00175")}, []interface{}{this.ParseNumber("12.5"), this.ParseNumber("0.00165")}, []interface{}{this.ParseNumber("25"), this.ParseNumber("0.00155")}, []interface{}{this.ParseNumber("75"), this.ParseNumber("0.00145")}, []interface{}{this.ParseNumber("200"), this.ParseNumber("0.00135")}, []interface{}{this.ParseNumber("500"), this.ParseNumber("0.00125")}, []interface{}{this.ParseNumber("1250"), this.ParseNumber("0.00115")}, []interface{}{this.ParseNumber("2500"), this.ParseNumber("0.00105")}, []interface{}{this.ParseNumber("3000"), this.ParseNumber("0.00095")}, []interface{}{this.ParseNumber("6000"), this.ParseNumber("0.00085")}, []interface{}{this.ParseNumber("11000"), this.ParseNumber("0.00075")}, []interface{}{this.ParseNumber("20000"), this.ParseNumber("0.00065")}, []interface{}{this.ParseNumber("40000"), this.ParseNumber("0.00065")}, []interface{}{this.ParseNumber("75000"), this.ParseNumber("0.00065")}}, }, }, "swap": map[string]interface{} { "tierBased": true, "feeSide": "base", "percentage": true, "maker": this.ParseNumber("0.0"), "taker": this.ParseNumber("0.0005"), "tiers": map[string]interface{} { "maker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.0000")}, []interface{}{this.ParseNumber("1.5"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("3"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("6"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("12.5"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("25"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("75"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("200"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("500"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("1250"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("2500"), this.ParseNumber("-0.00005")}, []interface{}{this.ParseNumber("3000"), this.ParseNumber("-0.00008")}, []interface{}{this.ParseNumber("6000"), this.ParseNumber("-0.01000")}, []interface{}{this.ParseNumber("11000"), this.ParseNumber("-0.01002")}, []interface{}{this.ParseNumber("20000"), this.ParseNumber("-0.01005")}, []interface{}{this.ParseNumber("40000"), this.ParseNumber("-0.02000")}, []interface{}{this.ParseNumber("75000"), this.ParseNumber("-0.02005")}}, "taker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.00050")}, []interface{}{this.ParseNumber("1.5"), this.ParseNumber("0.00048")}, []interface{}{this.ParseNumber("3"), this.ParseNumber("0.00046")}, []interface{}{this.ParseNumber("6"), this.ParseNumber("0.00044")}, []interface{}{this.ParseNumber("12.5"), this.ParseNumber("0.00042")}, []interface{}{this.ParseNumber("25"), this.ParseNumber("0.00040")}, []interface{}{this.ParseNumber("75"), this.ParseNumber("0.00038")}, []interface{}{this.ParseNumber("200"), this.ParseNumber("0.00036")}, []interface{}{this.ParseNumber("500"), this.ParseNumber("0.00034")}, []interface{}{this.ParseNumber("1250"), this.ParseNumber("0.00032")}, []interface{}{this.ParseNumber("2500"), this.ParseNumber("0.00030")}, []interface{}{this.ParseNumber("3000"), this.ParseNumber("0.00030")}, []interface{}{this.ParseNumber("6000"), this.ParseNumber("0.00030")}, []interface{}{this.ParseNumber("11000"), this.ParseNumber("0.00030")}, []interface{}{this.ParseNumber("20000"), this.ParseNumber("0.00030")}, []interface{}{this.ParseNumber("40000"), this.ParseNumber("0.00030")}, []interface{}{this.ParseNumber("75000"), this.ParseNumber("0.00030")}}, }, }, }, "exceptions": map[string]interface{} { "exact": map[string]interface{} { "INVALID_PARAM_VALUE": BadRequest, "INVALID_PROTOCOL": BadRequest, "INVALID_ARGUMENT": BadRequest, "INVALID_REQUEST_BODY": BadRequest, "MISSING_REQUIRED_PARAM": ArgumentsRequired, "BAD_REQUEST": BadRequest, "INVALID_CONTENT_TYPE": BadRequest, "NOT_ACCEPTABLE": BadRequest, "METHOD_NOT_ALLOWED": BadRequest, "NOT_FOUND": ExchangeError, "AUTHENTICATION_FAILED": AuthenticationError, "INVALID_CREDENTIALS": AuthenticationError, "INVALID_KEY": AuthenticationError, "IP_FORBIDDEN": AuthenticationError, "READ_ONLY": PermissionDenied, "INVALID_SIGNATURE": AuthenticationError, "MISSING_REQUIRED_HEADER": AuthenticationError, "REQUEST_EXPIRED": AuthenticationError, "ACCOUNT_LOCKED": AccountSuspended, "FORBIDDEN": PermissionDenied, "SUB_ACCOUNT_NOT_FOUND": ExchangeError, "SUB_ACCOUNT_LOCKED": AccountSuspended, "MARGIN_BALANCE_EXCEPTION": ExchangeError, "MARGIN_TRANSFER_FAILED": ExchangeError, "TOO_MUCH_FUTURES_AVAILABLE": ExchangeError, "FUTURES_BALANCE_NOT_ENOUGH": InsufficientFunds, "ACCOUNT_EXCEPTION": ExchangeError, "SUB_ACCOUNT_TRANSFER_FAILED": ExchangeError, "ADDRESS_NOT_USED": ExchangeError, "TOO_FAST": RateLimitExceeded, "WITHDRAWAL_OVER_LIMIT": ExchangeError, "API_WITHDRAW_DISABLED": ExchangeNotAvailable, "INVALID_WITHDRAW_ID": ExchangeError, "INVALID_WITHDRAW_CANCEL_STATUS": ExchangeError, "INVALID_PRECISION": InvalidOrder, "INVALID_CURRENCY": BadSymbol, "INVALID_CURRENCY_PAIR": BadSymbol, "POC_FILL_IMMEDIATELY": OrderImmediatelyFillable, "ORDER_NOT_FOUND": OrderNotFound, "CLIENT_ID_NOT_FOUND": OrderNotFound, "ORDER_CLOSED": InvalidOrder, "ORDER_CANCELLED": InvalidOrder, "QUANTITY_NOT_ENOUGH": InvalidOrder, "BALANCE_NOT_ENOUGH": InsufficientFunds, "MARGIN_NOT_SUPPORTED": InvalidOrder, "MARGIN_BALANCE_NOT_ENOUGH": InsufficientFunds, "AMOUNT_TOO_LITTLE": InvalidOrder, "AMOUNT_TOO_MUCH": InvalidOrder, "REPEATED_CREATION": InvalidOrder, "LOAN_NOT_FOUND": OrderNotFound, "LOAN_RECORD_NOT_FOUND": OrderNotFound, "NO_MATCHED_LOAN": ExchangeError, "NOT_MERGEABLE": ExchangeError, "NO_CHANGE": ExchangeError, "REPAY_TOO_MUCH": ExchangeError, "TOO_MANY_CURRENCY_PAIRS": InvalidOrder, "TOO_MANY_ORDERS": InvalidOrder, "TOO_MANY_REQUESTS": RateLimitExceeded, "MIXED_ACCOUNT_TYPE": InvalidOrder, "AUTO_BORROW_TOO_MUCH": ExchangeError, "TRADE_RESTRICTED": InsufficientFunds, "USER_NOT_FOUND": AccountNotEnabled, "CONTRACT_NO_COUNTER": ExchangeError, "CONTRACT_NOT_FOUND": BadSymbol, "RISK_LIMIT_EXCEEDED": ExchangeError, "INSUFFICIENT_AVAILABLE": InsufficientFunds, "LIQUIDATE_IMMEDIATELY": InvalidOrder, "LEVERAGE_TOO_HIGH": InvalidOrder, "LEVERAGE_TOO_LOW": InvalidOrder, "ORDER_NOT_OWNED": ExchangeError, "ORDER_FINISHED": ExchangeError, "POSITION_CROSS_MARGIN": ExchangeError, "POSITION_IN_LIQUIDATION": ExchangeError, "POSITION_IN_CLOSE": ExchangeError, "POSITION_EMPTY": InvalidOrder, "REMOVE_TOO_MUCH": ExchangeError, "RISK_LIMIT_NOT_MULTIPLE": ExchangeError, "RISK_LIMIT_TOO_HIGH": ExchangeError, "RISK_LIMIT_TOO_lOW": ExchangeError, "PRICE_TOO_DEVIATED": InvalidOrder, "SIZE_TOO_LARGE": InvalidOrder, "SIZE_TOO_SMALL": InvalidOrder, "PRICE_OVER_LIQUIDATION": InvalidOrder, "PRICE_OVER_BANKRUPT": InvalidOrder, "ORDER_POC_IMMEDIATE": OrderImmediatelyFillable, "INCREASE_POSITION": InvalidOrder, "CONTRACT_IN_DELISTING": ExchangeError, "INTERNAL": ExchangeNotAvailable, "SERVER_ERROR": ExchangeNotAvailable, "TOO_BUSY": ExchangeNotAvailable, "CROSS_ACCOUNT_NOT_FOUND": ExchangeError, "RISK_LIMIT_TOO_LOW": BadRequest, "AUTO_TRIGGER_PRICE_LESS_LAST": InvalidOrder, "AUTO_TRIGGER_PRICE_GREATE_LAST": InvalidOrder, "POSITION_HOLDING": BadRequest, "USER_LOAN_EXCEEDED": BadRequest, }, "broad": map[string]interface{} {}, }, }) } func (this *gate) SetSandboxMode(enable interface{}) { this.Exchange.SetSandboxMode(enable) AddElementToObject(this.Options, "sandboxMode", enable) } /** * @method * @name gate#loadUnifiedStatus * @param {object} [params] extra parameters specific to the exchange API endpoint * @description returns unifiedAccount so the user can check if the unified account is enabled * @see https://www.gate.io/docs/developers/apiv4/#get-account-detail * @returns {boolean} true or false if the enabled unified account is enabled or not and sets the unifiedAccount option if it is undefined */ func (this *gate) LoadUnifiedStatus(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 unifiedAccount interface{} = this.SafeBool(this.Options, "unifiedAccount") if IsTrue(IsEqual(unifiedAccount, nil)) { { ret__ := func(this *gate) (ret_ interface{}) { defer func() { if e := recover(); e != nil { if e == "break" { return } ret_ = func(this *gate) interface{} { // catch block: // if the request fails, the unifiedAccount is disabled AddElementToObject(this.Options, "unifiedAccount", false) return nil }(this) } }() // try block: // // { // "user_id": 10406147, // "ip_whitelist": [], // "currency_pairs": [], // "key": { // "mode": 1 // }, // "tier": 0, // "tier_expire_time": "0001-01-01T00:00:00Z", // "copy_trading_role": 0 // } // response:= (<-this.PrivateAccountGetDetail(params)) PanicOnError(response) var result interface{} = this.SafeDict(response, "key", map[string]interface{} {}) AddElementToObject(this.Options, "unifiedAccount", IsEqual(this.SafeInteger(result, "mode"), 2)) return nil }(this) if ret__ != nil { return ret__ } } } ch <- GetValue(this.Options, "unifiedAccount") return nil }() return ch } func (this *gate) UpgradeUnifiedTradeAccount(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 retRes110915 := (<-this.PrivateUnifiedPutUnifiedMode(params)) PanicOnError(retRes110915) ch <- retRes110915 return nil }() return ch } /** * @method * @name gate#fetchTime * @description fetches the current integer timestamp in milliseconds from the exchange server * @see https://www.gate.io/docs/developers/apiv4/en/#get-server-current-time * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {int} the current integer timestamp in milliseconds from the exchange server */ func (this *gate) FetchTime(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) params := GetArg(optionalArgs, 0, map[string]interface{} {}) _ = params response:= (<-this.PublicSpotGetTime(params)) PanicOnError(response) // // { // "server_time": 1731447921098 // } // ch <- this.SafeInteger(response, "server_time") return nil }() return ch } func (this *gate) CreateExpiredOptionMarket(symbol interface{}) interface{} { // support expired option contracts var quote interface{} = "USDT" var settle interface{} = quote var optionParts interface{} = Split(symbol, "-") var symbolBase interface{} = Split(symbol, "/") var marketIdBase interface{} = Split(symbol, "_") var base interface{} = nil var expiry interface{} = this.SafeString(optionParts, 1) if IsTrue(IsGreaterThan(GetIndexOf(symbol, "/"), OpNeg(1))) { base = this.SafeString(symbolBase, 0) } else { base = this.SafeString(marketIdBase, 0) expiry = Slice(expiry, 2, 8) // convert 20230728 to 230728 } var strike 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(Add(Add(Add(base, "_"), quote), "-"), "20"), expiry), "-"), strike), "-"), optionType), "symbol": Add(Add(Add(Add(Add(Add(Add(Add(Add(Add(base, "/"), quote), ":"), settle), "-"), expiry), "-"), strike), "-"), optionType), "base": base, "quote": quote, "settle": settle, "baseId": base, "quoteId": quote, "settleId": settle, "active": false, "type": "option", "linear": nil, "inverse": nil, "spot": false, "swap": false, "future": false, "option": true, "margin": false, "contract": true, "contractSize": this.ParseNumber("1"), "expiry": timestamp, "expiryDatetime": datetime, "optionType": Ternary(IsTrue((IsEqual(optionType, "C"))), "call", "put"), "strike": this.ParseNumber(strike), "precision": map[string]interface{} { "amount": this.ParseNumber("1"), "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 *gate) 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) } /** * @method * @name gate#fetchMarkets * @description retrieves data on all markets for gate * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-currency-pairs-supported // spot * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-supported-currency-pairs-supported-in-margin-trading // margin * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts // swap * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts-2 // future * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-the-contracts-with-specified-underlying-and-expiration-time // option * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object[]} an array of objects representing market data */ func (this *gate) 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 if IsTrue(GetValue(this.Options, "adjustForTimeDifference")) { retRes121812 := (<-this.LoadTimeDifference()) PanicOnError(retRes121812) } var sandboxMode interface{} = this.SafeBool(this.Options, "sandboxMode", false) var rawPromises interface{} = []interface{}{this.FetchContractMarkets(params), this.FetchOptionMarkets(params)} if !IsTrue(sandboxMode) { // gate does not have a sandbox for spot markets var mainnetOnly interface{} = []interface{}{this.FetchSpotMarkets(params)} rawPromises = this.ArrayConcat(rawPromises, mainnetOnly) } promises:= (<-promiseAll(rawPromises)) PanicOnError(promises) var spotMarkets interface{} = this.SafeValue(promises, 0, []interface{}{}) var contractMarkets interface{} = this.SafeValue(promises, 1, []interface{}{}) var optionMarkets interface{} = this.SafeValue(promises, 2, []interface{}{}) var markets interface{} = this.ArrayConcat(spotMarkets, contractMarkets) ch <- this.ArrayConcat(markets, optionMarkets) return nil }() return ch } func (this *gate) FetchSpotMarkets(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 marginPromise interface{} = this.PublicMarginGetCurrencyPairs(params) var spotMarketsPromise interface{} = this.PublicSpotGetCurrencyPairs(params) marginResponsespotMarketsResponseVariable := (<-promiseAll([]interface{}{marginPromise, spotMarketsPromise})); marginResponse := GetValue(marginResponsespotMarketsResponseVariable,0); spotMarketsResponse := GetValue(marginResponsespotMarketsResponseVariable,1) var marginMarkets interface{} = this.IndexBy(marginResponse, "id") // // Spot // // [ // { // "id": "QTUM_ETH", // "base": "QTUM", // "quote": "ETH", // "fee": "0.2", // "min_base_amount": "0.01", // "min_quote_amount": "0.001", // "amount_precision": 3, // "precision": 6, // "trade_status": "tradable", // "sell_start": 0, // "buy_start": 0 // } // ] // // Margin // // [ // { // "id": "ETH_USDT", // "base": "ETH", // "quote": "USDT", // "leverage": 3, // "min_base_amount": "0.01", // "min_quote_amount": "100", // "max_quote_amount": "1000000" // } // ] // var result interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(spotMarketsResponse)); i++ { var spotMarket interface{} = GetValue(spotMarketsResponse, i) var id interface{} = this.SafeString(spotMarket, "id") var marginMarket interface{} = this.SafeValue(marginMarkets, id) var market interface{} = this.DeepExtend(marginMarket, spotMarket) baseIdquoteIdVariable := Split(id, "_"); baseId := GetValue(baseIdquoteIdVariable,0); quoteId := GetValue(baseIdquoteIdVariable,1) var base interface{} = this.SafeCurrencyCode(baseId) var quote interface{} = this.SafeCurrencyCode(quoteId) var takerPercent interface{} = this.SafeString(market, "fee") var makerPercent interface{} = this.SafeString(market, "maker_fee_rate", takerPercent) var amountPrecision interface{} = this.ParseNumber(this.ParsePrecision(this.SafeString(market, "amount_precision"))) var tradeStatus interface{} = this.SafeString(market, "trade_status") var leverage interface{} = this.SafeNumber(market, "leverage") var margin interface{} = !IsEqual(leverage, nil) AppendToArray(&result,map[string]interface{} { "id": id, "symbol": Add(Add(base, "/"), quote), "base": base, "quote": quote, "settle": nil, "baseId": baseId, "quoteId": quoteId, "settleId": nil, "type": "spot", "spot": true, "margin": margin, "swap": false, "future": false, "option": false, "active": (IsEqual(tradeStatus, "tradable")), "contract": false, "linear": nil, "inverse": nil, "taker": this.ParseNumber(Precise.StringDiv(takerPercent, "100")), "maker": this.ParseNumber(Precise.StringDiv(makerPercent, "100")), "contractSize": nil, "expiry": nil, "expiryDatetime": nil, "strike": nil, "optionType": nil, "precision": map[string]interface{} { "amount": amountPrecision, "price": this.ParseNumber(this.ParsePrecision(this.SafeString(market, "precision"))), }, "limits": map[string]interface{} { "leverage": map[string]interface{} { "min": this.ParseNumber("1"), "max": this.SafeNumber(market, "leverage", 1), }, "amount": map[string]interface{} { "min": this.SafeNumber(spotMarket, "min_base_amount", amountPrecision), "max": nil, }, "price": map[string]interface{} { "min": nil, "max": nil, }, "cost": map[string]interface{} { "min": this.SafeNumber(market, "min_quote_amount"), "max": Ternary(IsTrue(margin), this.SafeNumber(market, "max_quote_amount"), nil), }, }, "created": nil, "info": market, }) } ch <- result return nil }() return ch } func (this *gate) FetchContractMarkets(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 result interface{} = []interface{}{} var swapSettlementCurrencies interface{} = this.GetSettlementCurrencies("swap", "fetchMarkets") var futureSettlementCurrencies interface{} = this.GetSettlementCurrencies("future", "fetchMarkets") for c := 0; IsLessThan(c, GetArrayLength(swapSettlementCurrencies)); c++ { var settleId interface{} = GetValue(swapSettlementCurrencies, c) var request interface{} = map[string]interface{} { "settle": settleId, } response:= (<-this.PublicFuturesGetSettleContracts(this.Extend(request, params))) PanicOnError(response) for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var parsedMarket interface{} = this.ParseContractMarket(GetValue(response, i), settleId) AppendToArray(&result,parsedMarket) } } for c := 0; IsLessThan(c, GetArrayLength(futureSettlementCurrencies)); c++ { var settleId interface{} = GetValue(futureSettlementCurrencies, c) var request interface{} = map[string]interface{} { "settle": settleId, } response:= (<-this.PublicDeliveryGetSettleContracts(this.Extend(request, params))) PanicOnError(response) for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var parsedMarket interface{} = this.ParseContractMarket(GetValue(response, i), settleId) AppendToArray(&result,parsedMarket) } } ch <- result return nil }() return ch } func (this *gate) ParseContractMarket(market interface{}, settleId interface{}) interface{} { // // Perpetual swap // // { // "name": "BTC_USDT", // "type": "direct", // "quanto_multiplier": "0.0001", // "ref_discount_rate": "0", // "order_price_deviate": "0.5", // "maintenance_rate": "0.005", // "mark_type": "index", // "last_price": "38026", // "mark_price": "37985.6", // "index_price": "37954.92", // "funding_rate_indicative": "0.000219", // "mark_price_round": "0.01", // "funding_offset": 0, // "in_delisting": false, // "risk_limit_base": "1000000", // "interest_rate": "0.0003", // "order_price_round": "0.1", // "order_size_min": 1, // "ref_rebate_rate": "0.2", // "funding_interval": 28800, // "risk_limit_step": "1000000", // "leverage_min": "1", // "leverage_max": "100", // "risk_limit_max": "8000000", // "maker_fee_rate": "-0.00025", // "taker_fee_rate": "0.00075", // "funding_rate": "0.002053", // "order_size_max": 1000000, // "funding_next_apply": 1610035200, // "short_users": 977, // "config_change_time": 1609899548, // "trade_size": 28530850594, // "position_size": 5223816, // "long_users": 455, // "funding_impact_value": "60000", // "orders_limit": 50, // "trade_id": 10851092, // "orderbook_id": 2129638396 // } // // Delivery Futures // // { // "name": "BTC_USDT_20200814", // "underlying": "BTC_USDT", // "cycle": "WEEKLY", // "type": "direct", // "quanto_multiplier": "0.0001", // "mark_type": "index", // "last_price": "9017", // "mark_price": "9019", // "index_price": "9005.3", // "basis_rate": "0.185095", // "basis_value": "13.7", // "basis_impact_value": "100000", // "settle_price": "0", // "settle_price_interval": 60, // "settle_price_duration": 1800, // "settle_fee_rate": "0.0015", // "expire_time": 1593763200, // "order_price_round": "0.1", // "mark_price_round": "0.1", // "leverage_min": "1", // "leverage_max": "100", // "maintenance_rate": "1000000", // "risk_limit_base": "140.726652109199", // "risk_limit_step": "1000000", // "risk_limit_max": "8000000", // "maker_fee_rate": "-0.00025", // "taker_fee_rate": "0.00075", // "ref_discount_rate": "0", // "ref_rebate_rate": "0.2", // "order_price_deviate": "0.5", // "order_size_min": 1, // "order_size_max": 1000000, // "orders_limit": 50, // "orderbook_id": 63, // "trade_id": 26, // "trade_size": 435, // "position_size": 130, // "config_change_time": 1593158867, // "in_delisting": false // } // var id interface{} = this.SafeString(market, "name") var parts interface{} = Split(id, "_") var baseId interface{} = this.SafeString(parts, 0) var quoteId interface{} = this.SafeString(parts, 1) var date interface{} = this.SafeString(parts, 2) var base interface{} = this.SafeCurrencyCode(baseId) var quote interface{} = this.SafeCurrencyCode(quoteId) var settle interface{} = this.SafeCurrencyCode(settleId) var expiry interface{} = this.SafeTimestamp(market, "expire_time") var symbol interface{} = "" var marketType interface{} = "swap" if IsTrue(!IsEqual(date, nil)) { symbol = Add(Add(Add(Add(Add(Add(base, "/"), quote), ":"), settle), "-"), this.Yymmdd(expiry, "")) marketType = "future" } else { symbol = Add(Add(Add(Add(base, "/"), quote), ":"), settle) } var priceDeviate interface{} = this.SafeString(market, "order_price_deviate") var markPrice interface{} = this.SafeString(market, "mark_price") var minMultiplier interface{} = Precise.StringSub("1", priceDeviate) var maxMultiplier interface{} = Precise.StringAdd("1", priceDeviate) var minPrice interface{} = Precise.StringMul(minMultiplier, markPrice) var maxPrice interface{} = Precise.StringMul(maxMultiplier, markPrice) var takerPercent interface{} = this.SafeString(market, "taker_fee_rate") var makerPercent interface{} = this.SafeString(market, "maker_fee_rate", takerPercent) var isLinear interface{} = IsEqual(quote, settle) return map[string]interface{} { "id": id, "symbol": symbol, "base": base, "quote": quote, "settle": settle, "baseId": baseId, "quoteId": quoteId, "settleId": settleId, "type": marketType, "spot": false, "margin": false, "swap": IsEqual(marketType, "swap"), "future": IsEqual(marketType, "future"), "option": IsEqual(marketType, "option"), "active": true, "contract": true, "linear": isLinear, "inverse": !IsTrue(isLinear), "taker": this.ParseNumber(Precise.StringDiv(takerPercent, "100")), "maker": this.ParseNumber(Precise.StringDiv(makerPercent, "100")), "contractSize": this.SafeNumber(market, "quanto_multiplier"), "expiry": expiry, "expiryDatetime": this.Iso8601(expiry), "strike": nil, "optionType": nil, "precision": map[string]interface{} { "amount": this.ParseNumber("1"), "price": this.SafeNumber(market, "order_price_round"), }, "limits": map[string]interface{} { "leverage": map[string]interface{} { "min": this.SafeNumber(market, "leverage_min"), "max": this.SafeNumber(market, "leverage_max"), }, "amount": map[string]interface{} { "min": this.SafeNumber(market, "order_size_min"), "max": this.SafeNumber(market, "order_size_max"), }, "price": map[string]interface{} { "min": this.ParseNumber(minPrice), "max": this.ParseNumber(maxPrice), }, "cost": map[string]interface{} { "min": nil, "max": nil, }, }, "created": nil, "info": market, } } func (this *gate) FetchOptionMarkets(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 result interface{} = []interface{}{} underlyings:= (<-this.FetchOptionUnderlyings()) PanicOnError(underlyings) for i := 0; IsLessThan(i, GetArrayLength(underlyings)); i++ { var underlying interface{} = GetValue(underlyings, i) var query interface{} = this.Extend(map[string]interface{} {}, params) AddElementToObject(query, "underlying", underlying) response:= (<-this.PublicOptionsGetContracts(query)) PanicOnError(response) // // [ // { // "orders_limit": "50", // "order_size_max": "100000", // "mark_price_round": "0.1", // "order_size_min": "1", // "position_limit": "1000000", // "orderbook_id": "575967", // "order_price_deviate": "0.9", // "is_call": true, // true means Call false means Put // "last_price": "93.9", // "bid1_size": "0", // "bid1_price": "0", // "taker_fee_rate": "0.0004", // "underlying": "BTC_USDT", // "create_time": "1646381188", // "price_limit_fee_rate": "0.1", // "maker_fee_rate": "0.0004", // "trade_id": "727", // "order_price_round": "0.1", // "settle_fee_rate": "0.0001", // "trade_size": "1982", // "ref_rebate_rate": "0", // "name": "BTC_USDT-20220311-44000-C", // "underlying_price": "39194.26", // "strike_price": "44000", // "multiplier": "0.0001", // "ask1_price": "0", // "ref_discount_rate": "0", // "expiration_time": "1646985600", // "mark_price": "12.15", // "position_size": "4", // "ask1_size": "0", // "tag": "WEEK" // } // ] // for j := 0; IsLessThan(j, GetArrayLength(response)); j++ { var market interface{} = GetValue(response, j) var id interface{} = this.SafeString(market, "name") var parts interface{} = Split(underlying, "_") var baseId interface{} = this.SafeString(parts, 0) var quoteId interface{} = this.SafeString(parts, 1) var base interface{} = this.SafeCurrencyCode(baseId) var quote interface{} = this.SafeCurrencyCode(quoteId) var symbol interface{} = Add(Add(base, "/"), quote) var expiry interface{} = this.SafeTimestamp(market, "expiration_time") var strike interface{} = this.SafeString(market, "strike_price") var isCall interface{} = this.SafeValue(market, "is_call") var optionLetter interface{} = Ternary(IsTrue(isCall), "C", "P") var optionType interface{} = Ternary(IsTrue(isCall), "call", "put") symbol = Add(Add(Add(Add(Add(Add(Add(Add(symbol, ":"), quote), "-"), this.Yymmdd(expiry)), "-"), strike), "-"), optionLetter) var priceDeviate interface{} = this.SafeString(market, "order_price_deviate") var markPrice interface{} = this.SafeString(market, "mark_price") var minMultiplier interface{} = Precise.StringSub("1", priceDeviate) var maxMultiplier interface{} = Precise.StringAdd("1", priceDeviate) var minPrice interface{} = Precise.StringMul(minMultiplier, markPrice) var maxPrice interface{} = Precise.StringMul(maxMultiplier, markPrice) var takerPercent interface{} = this.SafeString(market, "taker_fee_rate") var makerPercent interface{} = this.SafeString(market, "maker_fee_rate", takerPercent) AppendToArray(&result,map[string]interface{} { "id": id, "symbol": symbol, "base": base, "quote": quote, "settle": quote, "baseId": baseId, "quoteId": quoteId, "settleId": quoteId, "type": "option", "spot": false, "margin": false, "swap": false, "future": false, "option": true, "active": true, "contract": true, "linear": true, "inverse": false, "taker": this.ParseNumber(Precise.StringDiv(takerPercent, "100")), "maker": this.ParseNumber(Precise.StringDiv(makerPercent, "100")), "contractSize": this.ParseNumber("1"), "expiry": expiry, "expiryDatetime": this.Iso8601(expiry), "strike": strike, "optionType": optionType, "precision": map[string]interface{} { "amount": this.ParseNumber("1"), "price": this.SafeNumber(market, "order_price_round"), }, "limits": map[string]interface{} { "leverage": map[string]interface{} { "min": nil, "max": nil, }, "amount": map[string]interface{} { "min": this.SafeNumber(market, "order_size_min"), "max": this.SafeNumber(market, "order_size_max"), }, "price": map[string]interface{} { "min": this.ParseNumber(minPrice), "max": this.ParseNumber(maxPrice), }, "cost": map[string]interface{} { "min": nil, "max": nil, }, }, "created": this.SafeTimestamp(market, "create_time"), "info": market, }) } } ch <- result return nil }() return ch } func (this *gate) FetchOptionUnderlyings() <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) underlyingsResponse:= (<-this.PublicOptionsGetUnderlyings()) PanicOnError(underlyingsResponse) // // [ // { // "index_time": "1646915796", // "name": "BTC_USDT", // "index_price": "39142.73" // } // ] // var underlyings interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(underlyingsResponse)); i++ { var underlying interface{} = GetValue(underlyingsResponse, i) var name interface{} = this.SafeString(underlying, "name") if IsTrue(!IsEqual(name, nil)) { AppendToArray(&underlyings,name) } } ch <- underlyings return nil }() return ch } func (this *gate) PrepareRequest(optionalArgs ...interface{}) interface{} { /** * @ignore * @method * @name gate#prepareRequest * @description Fills request params contract, settle, currency_pair, market and account where applicable * @param {object} market CCXT market, required when type is undefined * @param {string} type 'spot', 'swap', or 'future', required when market is undefined * @param {object} [params] request parameters * @returns the api request object, and the new params object with non-needed parameters removed */ // * Do not call for multi spot order methods like cancelAllOrders and fetchOpenOrders. Use multiOrderSpotPrepareRequest instead market := GetArg(optionalArgs, 0, nil) _ = market typeVar := GetArg(optionalArgs, 1, nil) _ = typeVar params := GetArg(optionalArgs, 2, map[string]interface{} {}) _ = params var request interface{} = map[string]interface{} {} if IsTrue(!IsEqual(market, nil)) { if IsTrue(GetValue(market, "contract")) { AddElementToObject(request, "contract", GetValue(market, "id")) if !IsTrue(GetValue(market, "option")) { AddElementToObject(request, "settle", GetValue(market, "settleId")) } } else { AddElementToObject(request, "currency_pair", GetValue(market, "id")) } } else { var swap interface{} = IsEqual(typeVar, "swap") var future interface{} = IsEqual(typeVar, "future") if IsTrue(IsTrue(swap) || IsTrue(future)) { var defaultSettle interface{} = Ternary(IsTrue(swap), "usdt", "btc") var settle interface{} = this.SafeStringLower(params, "settle", defaultSettle) params = this.Omit(params, "settle") AddElementToObject(request, "settle", settle) } } return []interface{}{request, params} } func (this *gate) SpotOrderPrepareRequest(optionalArgs ...interface{}) interface{} { /** * @ignore * @method * @name gate#multiOrderSpotPrepareRequest * @description Fills request params currency_pair, market and account where applicable for spot order methods like fetchOpenOrders, cancelAllOrders * @param {object} market CCXT market * @param {bool} trigger true if for a trigger order * @param {object} [params] request parameters * @returns the api request object, and the new params object with non-needed parameters removed */ market := GetArg(optionalArgs, 0, nil) _ = market trigger := GetArg(optionalArgs, 1, false) _ = trigger params := GetArg(optionalArgs, 2, map[string]interface{} {}) _ = params marginModequeryVariable := this.GetMarginMode(trigger, params); marginMode := GetValue(marginModequeryVariable,0); query := GetValue(marginModequeryVariable,1) var request interface{} = map[string]interface{} {} if !IsTrue(trigger) { if IsTrue(IsEqual(market, nil)) { panic(ArgumentsRequired(Add(this.Id, " spotOrderPrepareRequest() requires a market argument for non-trigger orders"))) } AddElementToObject(request, "account", marginMode) AddElementToObject(request, "currency_pair", GetValue(market, "id")) // Should always be set for non-trigger } return []interface{}{request, query} } func (this *gate) MultiOrderSpotPrepareRequest(optionalArgs ...interface{}) interface{} { /** * @ignore * @method * @name gate#multiOrderSpotPrepareRequest * @description Fills request params currency_pair, market and account where applicable for spot order methods like fetchOpenOrders, cancelAllOrders * @param {object} market CCXT market * @param {bool} trigger true if for a trigger order * @param {object} [params] request parameters * @returns the api request object, and the new params object with non-needed parameters removed */ market := GetArg(optionalArgs, 0, nil) _ = market trigger := GetArg(optionalArgs, 1, false) _ = trigger params := GetArg(optionalArgs, 2, map[string]interface{} {}) _ = params marginModequeryVariable := this.GetMarginMode(trigger, params); marginMode := GetValue(marginModequeryVariable,0); query := GetValue(marginModequeryVariable,1) var request interface{} = map[string]interface{} { "account": marginMode, } if IsTrue(!IsEqual(market, nil)) { if IsTrue(trigger) { // gate spot and margin trigger orders use the term market instead of currency_pair, and normal instead of spot. Neither parameter is used when fetching/cancelling a single order. They are used for creating a single trigger order, but createOrder does not call this method AddElementToObject(request, "market", GetValue(market, "id")) } else { AddElementToObject(request, "currency_pair", GetValue(market, "id")) } } return []interface{}{request, query} } func (this *gate) GetMarginMode(trigger interface{}, params interface{}) interface{} { /** * @ignore * @method * @name gate#getMarginMode * @description Gets the margin type for this api call * @param {bool} trigger True if for a trigger order * @param {object} [params] Request params * @returns The marginMode and the updated request params with marginMode removed, marginMode value is the value that can be read by the "account" property specified in gates api docs */ var defaultMarginMode interface{} = this.SafeStringLower2(this.Options, "defaultMarginMode", "marginMode", "spot") // 'margin' is isolated margin on gate's api var marginMode interface{} = this.SafeStringLower2(params, "marginMode", "account", defaultMarginMode) params = this.Omit(params, []interface{}{"marginMode", "account"}) if IsTrue(IsEqual(marginMode, "cross")) { marginMode = "cross_margin" } else if IsTrue(IsEqual(marginMode, "isolated")) { marginMode = "margin" } else if IsTrue(IsEqual(marginMode, "")) { marginMode = "spot" } if IsTrue(trigger) { if IsTrue(IsEqual(marginMode, "spot")) { // gate spot trigger orders use the term normal instead of spot marginMode = "normal" } if IsTrue(IsEqual(marginMode, "cross_margin")) { panic(BadRequest(Add(this.Id, " getMarginMode() does not support trigger orders for cross margin"))) } } var isUnifiedAccount interface{} = false isUnifiedAccountparamsVariable := this.HandleOptionAndParams(params, "getMarginMode", "unifiedAccount"); isUnifiedAccount = GetValue(isUnifiedAccountparamsVariable,0); params = GetValue(isUnifiedAccountparamsVariable,1) if IsTrue(isUnifiedAccount) { marginMode = "unified" } return []interface{}{marginMode, params} } func (this *gate) GetSettlementCurrencies(typeVar interface{}, method interface{}) interface{} { var options interface{} = this.SafeValue(this.Options, typeVar, map[string]interface{} {}) // [ 'BTC', 'USDT' ] unified codes var fetchMarketsContractOptions interface{} = this.SafeValue(options, method, map[string]interface{} {}) var defaultSettle interface{} = Ternary(IsTrue((IsEqual(typeVar, "swap"))), []interface{}{"usdt"}, []interface{}{"btc"}) return this.SafeValue(fetchMarketsContractOptions, "settlementCurrencies", defaultSettle) } /** * @method * @name gate#fetchCurrencies * @description fetches all available currencies on an exchange * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-currencies-details * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} an associative dictionary of currencies */ func (this *gate) FetchCurrencies(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) // sandbox/testnet only supports future markets params := GetArg(optionalArgs, 0, map[string]interface{} {}) _ = params var apiBackup interface{} = this.SafeValue(this.Urls, "apiBackup") if IsTrue(!IsEqual(apiBackup, nil)) { return nil } if IsTrue(this.CheckRequiredCredentials(false)) { retRes183412 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes183412) } response:= (<-this.PublicSpotGetCurrencies(params)) PanicOnError(response) // // [ // { // "currency": "USDT_ETH", // "name": "Tether", // "delisted": false, // "withdraw_disabled": false, // "withdraw_delayed": false, // "deposit_disabled": false, // "trade_disabled": true, // "chain": "ETH" // }, // ] // var indexedCurrencies interface{} = this.IndexBy(response, "currency") var result interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) var currencyId interface{} = this.SafeString(entry, "currency") var parts interface{} = Split(currencyId, "_") var partFirst interface{} = this.SafeString(parts, 0) // if there's an underscore then the second part is always the chain name (except the _OLD suffix) var currencyName interface{} = Ternary(IsTrue(EndsWith(currencyId, "_OLD")), currencyId, partFirst) var withdrawEnabled interface{} = !IsTrue(this.SafeBool(entry, "withdraw_disabled")) var depositEnabled interface{} = !IsTrue(this.SafeBool(entry, "deposit_disabled")) var tradeDisabled interface{} = !IsTrue(this.SafeBool(entry, "trade_disabled")) var precision interface{} = this.ParseNumber("0.0001") // temporary safe default, because no value provided from API var code interface{} = this.SafeCurrencyCode(currencyName) // check leveraged tokens (e.g. BTC3S, ETH5L) var isLeveragedToken interface{} = false if IsTrue(IsTrue(IsTrue(IsTrue(EndsWith(currencyId, "3S")) || IsTrue(EndsWith(currencyId, "3L"))) || IsTrue(EndsWith(currencyId, "5S"))) || IsTrue(EndsWith(currencyId, "5L"))) { var realCurrencyId interface{} = Slice(currencyId, 0, OpNeg(2)) if IsTrue(InOp(indexedCurrencies, realCurrencyId)) { isLeveragedToken = true } } var typeVar interface{} = Ternary(IsTrue(isLeveragedToken), "leveraged", "crypto") // some networks are null, they are mostly obsolete & unsupported dead tokens, so we can default their networkId to their tokenname var networkId interface{} = this.SafeString(entry, "chain", currencyId) var networkCode interface{} = this.NetworkIdToCode(networkId, code) var networkEntry interface{} = map[string]interface{} { "info": entry, "id": networkId, "network": networkCode, "limits": map[string]interface{} { "deposit": map[string]interface{} { "min": nil, "max": nil, }, "withdraw": map[string]interface{} { "min": nil, "max": nil, }, }, "active": !IsTrue(tradeDisabled), "deposit": depositEnabled, "withdraw": withdrawEnabled, "fee": nil, "precision": precision, } // check if first entry for the specific currency if !IsTrue((InOp(result, code))) { AddElementToObject(result, code, map[string]interface{} { "id": currencyName, "lowerCaseId": ToLower(currencyName), "code": code, "type": typeVar, "precision": precision, "limits": this.Limits, "networks": map[string]interface{} {}, "info": []interface{}{}, }) } AddElementToObject(GetValue(GetValue(result, code), "networks"), networkCode, networkEntry) var info interface{} = this.SafeList(GetValue(result, code), "info", []interface{}{}) AppendToArray(&info,entry) AddElementToObject(GetValue(result, code), "info", info) AddElementToObject(result, code, this.SafeCurrencyStructure(GetValue(result, code))) // this is needed after adding network entry } ch <- result return nil }() return ch } /** * @method * @name gate#fetchFundingRate * @description fetch the current funding rate * @see https://www.gate.io/docs/developers/apiv4/en/#get-a-single-contract * @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 *gate) 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 retRes19298 := (<-this.LoadMarkets()) PanicOnError(retRes19298) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "swap")) { panic(BadSymbol(Add(this.Id, " fetchFundingRate() supports swap contracts only"))) } requestqueryVariable := this.PrepareRequest(market, nil, params); request := GetValue(requestqueryVariable,0); query := GetValue(requestqueryVariable,1) response:= (<-this.PublicFuturesGetSettleContractsContract(this.Extend(request, query))) PanicOnError(response) // // [ // { // "name": "BTC_USDT", // "type": "direct", // "quanto_multiplier": "0.0001", // "ref_discount_rate": "0", // "order_price_deviate": "0.5", // "maintenance_rate": "0.005", // "mark_type": "index", // "last_price": "38026", // "mark_price": "37985.6", // "index_price": "37954.92", // "funding_rate_indicative": "0.000219", // "mark_price_round": "0.01", // "funding_offset": 0, // "in_delisting": false, // "risk_limit_base": "1000000", // "interest_rate": "0.0003", // "order_price_round": "0.1", // "order_size_min": 1, // "ref_rebate_rate": "0.2", // "funding_interval": 28800, // "risk_limit_step": "1000000", // "leverage_min": "1", // "leverage_max": "100", // "risk_limit_max": "8000000", // "maker_fee_rate": "-0.00025", // "taker_fee_rate": "0.00075", // "funding_rate": "0.002053", // "order_size_max": 1000000, // "funding_next_apply": 1610035200, // "short_users": 977, // "config_change_time": 1609899548, // "trade_size": 28530850594, // "position_size": 5223816, // "long_users": 455, // "funding_impact_value": "60000", // "orders_limit": 50, // "trade_id": 10851092, // "orderbook_id": 2129638396 // } // ] // ch <- this.ParseFundingRate(response) return nil }() return ch } /** * @method * @name gate#fetchFundingRates * @description fetch the funding rate for multiple markets * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts * @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 [funding rate structures]{@link https://docs.ccxt.com/#/?id=funding-rates-structure}, indexed by market symbols */ func (this *gate) 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 retRes19938 := (<-this.LoadMarkets()) PanicOnError(retRes19938) symbols = this.MarketSymbols(symbols) requestqueryVariable := this.PrepareRequest(nil, "swap", params); request := GetValue(requestqueryVariable,0); query := GetValue(requestqueryVariable,1) response:= (<-this.PublicFuturesGetSettleContracts(this.Extend(request, query))) PanicOnError(response) // // [ // { // "name": "BTC_USDT", // "type": "direct", // "quanto_multiplier": "0.0001", // "ref_discount_rate": "0", // "order_price_deviate": "0.5", // "maintenance_rate": "0.005", // "mark_type": "index", // "last_price": "38026", // "mark_price": "37985.6", // "index_price": "37954.92", // "funding_rate_indicative": "0.000219", // "mark_price_round": "0.01", // "funding_offset": 0, // "in_delisting": false, // "risk_limit_base": "1000000", // "interest_rate": "0.0003", // "order_price_round": "0.1", // "order_size_min": 1, // "ref_rebate_rate": "0.2", // "funding_interval": 28800, // "risk_limit_step": "1000000", // "leverage_min": "1", // "leverage_max": "100", // "risk_limit_max": "8000000", // "maker_fee_rate": "-0.00025", // "taker_fee_rate": "0.00075", // "funding_rate": "0.002053", // "order_size_max": 1000000, // "funding_next_apply": 1610035200, // "short_users": 977, // "config_change_time": 1609899548, // "trade_size": 28530850594, // "position_size": 5223816, // "long_users": 455, // "funding_impact_value": "60000", // "orders_limit": 50, // "trade_id": 10851092, // "orderbook_id": 2129638396 // } // ] // ch <- this.ParseFundingRates(response, symbols) return nil }() return ch } func (this *gate) ParseFundingRate(contract interface{}, optionalArgs ...interface{}) interface{} { // // { // "name": "BTC_USDT", // "type": "direct", // "quanto_multiplier": "0.0001", // "ref_discount_rate": "0", // "order_price_deviate": "0.5", // "maintenance_rate": "0.005", // "mark_type": "index", // "last_price": "38026", // "mark_price": "37985.6", // "index_price": "37954.92", // "funding_rate_indicative": "0.000219", // "mark_price_round": "0.01", // "funding_offset": 0, // "in_delisting": false, // "risk_limit_base": "1000000", // "interest_rate": "0.0003", // "order_price_round": "0.1", // "order_size_min": 1, // "ref_rebate_rate": "0.2", // "funding_interval": 28800, // "risk_limit_step": "1000000", // "leverage_min": "1", // "leverage_max": "100", // "risk_limit_max": "8000000", // "maker_fee_rate": "-0.00025", // "taker_fee_rate": "0.00075", // "funding_rate": "0.002053", // "order_size_max": 1000000, // "funding_next_apply": 1610035200, // "short_users": 977, // "config_change_time": 1609899548, // "trade_size": 28530850594, // "position_size": 5223816, // "long_users": 455, // "funding_impact_value": "60000", // "orders_limit": 50, // "trade_id": 10851092, // "orderbook_id": 2129638396 // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(contract, "name") var symbol interface{} = this.SafeSymbol(marketId, market, "_", "swap") var markPrice interface{} = this.SafeNumber(contract, "mark_price") var indexPrice interface{} = this.SafeNumber(contract, "index_price") var interestRate interface{} = this.SafeNumber(contract, "interest_rate") var fundingRate interface{} = this.SafeNumber(contract, "funding_rate") var fundingTime interface{} = this.SafeTimestamp(contract, "funding_next_apply") var fundingRateIndicative interface{} = this.SafeNumber(contract, "funding_rate_indicative") var fundingInterval interface{} = Precise.StringMul("1000", this.SafeString(contract, "funding_interval")) return map[string]interface{} { "info": contract, "symbol": symbol, "markPrice": markPrice, "indexPrice": indexPrice, "interestRate": interestRate, "estimatedSettlePrice": nil, "timestamp": nil, "datetime": nil, "fundingRate": fundingRate, "fundingTimestamp": fundingTime, "fundingDatetime": this.Iso8601(fundingTime), "nextFundingRate": fundingRateIndicative, "nextFundingTimestamp": nil, "nextFundingDatetime": nil, "previousFundingRate": nil, "previousFundingTimestamp": nil, "previousFundingDatetime": nil, "interval": this.ParseFundingInterval(fundingInterval), } } func (this *gate) ParseFundingInterval(interval interface{}) interface{} { var intervals interface{} = map[string]interface{} { "3600000": "1h", "14400000": "4h", "28800000": "8h", "57600000": "16h", "86400000": "24h", } return this.SafeString(intervals, interval, interval) } func (this *gate) FetchNetworkDepositAddress(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 retRes21308 := (<-this.LoadMarkets()) PanicOnError(retRes21308) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "currency": GetValue(currency, "id"), } response:= (<-this.PrivateWalletGetDepositAddress(this.Extend(request, params))) PanicOnError(response) var addresses interface{} = this.SafeValue(response, "multichain_addresses") var currencyId interface{} = this.SafeString(response, "currency") code = this.SafeCurrencyCode(currencyId) var result interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(addresses)); i++ { var entry interface{} = GetValue(addresses, i) // // { // "chain": "ETH", // "address": "0x359a697945E79C7e17b634675BD73B33324E9408", // "payment_id": "", // "payment_name": "", // "obtain_failed": "0" // } // var obtainFailed interface{} = this.SafeInteger(entry, "obtain_failed") if IsTrue(obtainFailed) { continue } var network interface{} = this.SafeString(entry, "chain") var address interface{} = this.SafeString(entry, "address") var tag interface{} = this.SafeString(entry, "payment_id") AddElementToObject(result, network, map[string]interface{} { "info": entry, "code": code, "currency": code, "address": address, "tag": tag, }) } ch <- result return nil }() return ch } /** * @method * @name gate#fetchDepositAddressesByNetwork * @description fetch a dictionary of addresses for a currency, indexed by network * @param {string} code unified currency code of the currency for the deposit address * @param {object} [params] extra parameters specific to the api endpoint * @returns {object} a dictionary of [address structures]{@link https://docs.ccxt.com/#/?id=address-structure} indexed by the network */ func (this *gate) FetchDepositAddressesByNetwork(code interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) params := GetArg(optionalArgs, 0, map[string]interface{} {}) _ = params retRes21788 := (<-this.LoadMarkets()) PanicOnError(retRes21788) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "currency": GetValue(currency, "id"), } response:= (<-this.PrivateWalletGetDepositAddress(this.Extend(request, params))) PanicOnError(response) var chains interface{} = this.SafeValue(response, "multichain_addresses", []interface{}{}) var currencyId interface{} = this.SafeString(response, "currency") currency = this.SafeCurrency(currencyId, currency) var parsed interface{} = this.ParseDepositAddresses(chains, []interface{}{GetValue(currency, "code")}, false, map[string]interface{} { "currency": GetValue(currency, "id"), }) ch <- this.IndexBy(parsed, "network") return nil }() return ch } /** * @method * @name gate#fetchDepositAddress * @description fetch the deposit address for a currency associated with this account * @see https://www.gate.io/docs/developers/apiv4/en/#generate-currency-deposit-address * @param {string} code unified currency code * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.network] unified network code (not used directly by gate.io but used by ccxt to filter the response) * @returns {object} an [address structure]{@link https://docs.ccxt.com/#/?id=address-structure} */ func (this *gate) 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 retRes22048 := (<-this.LoadMarkets()) PanicOnError(retRes22048) var networkCode interface{} = nil networkCodeparamsVariable := this.HandleNetworkCodeAndParams(params); networkCode = GetValue(networkCodeparamsVariable,0); params = GetValue(networkCodeparamsVariable,1) chainsIndexedById:= (<-this.FetchDepositAddressesByNetwork(code, params)) PanicOnError(chainsIndexedById) var selectedNetworkId interface{} = this.SelectNetworkCodeFromUnifiedNetworks(code, networkCode, chainsIndexedById) ch <- GetValue(chainsIndexedById, selectedNetworkId) return nil }() return ch } func (this *gate) ParseDepositAddress(depositAddress interface{}, optionalArgs ...interface{}) interface{} { // // { // chain: "BTC", // address: "1Nxu.......Ys", // payment_id: "", // payment_name: "", // obtain_failed: "0", // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var address interface{} = this.SafeString(depositAddress, "address") this.CheckAddress(address) return map[string]interface{} { "info": depositAddress, "currency": this.SafeString(currency, "code"), "address": address, "tag": this.SafeString(depositAddress, "payment_id"), "network": this.NetworkIdToCode(this.SafeString(depositAddress, "chain")), } } /** * @method * @name gate#fetchTradingFee * @description fetch the trading fees for a market * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-personal-trading-fee * @param {string} symbol unified market symbol * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [fee structure]{@link https://docs.ccxt.com/#/?id=fee-structure} */ func (this *gate) 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 retRes22438 := (<-this.LoadMarkets()) PanicOnError(retRes22438) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "currency_pair": GetValue(market, "id"), } response:= (<-this.PrivateWalletGetFee(this.Extend(request, params))) PanicOnError(response) // // { // "user_id": 1486602, // "taker_fee": "0.002", // "maker_fee": "0.002", // "gt_discount": true, // "gt_taker_fee": "0.0015", // "gt_maker_fee": "0.0015", // "loan_fee": "0.18", // "point_type": "0", // "futures_taker_fee": "0.0005", // "futures_maker_fee": "0" // } // ch <- this.ParseTradingFee(response, market) return nil }() return ch } /** * @method * @name gate#fetchTradingFees * @description fetch the trading fees for multiple markets * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-personal-trading-fee * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a dictionary of [fee structures]{@link https://docs.ccxt.com/#/?id=fee-structure} indexed by market symbols */ func (this *gate) 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 retRes22758 := (<-this.LoadMarkets()) PanicOnError(retRes22758) response:= (<-this.PrivateWalletGetFee(params)) PanicOnError(response) // // { // "user_id": 1486602, // "taker_fee": "0.002", // "maker_fee": "0.002", // "gt_discount": true, // "gt_taker_fee": "0.0015", // "gt_maker_fee": "0.0015", // "loan_fee": "0.18", // "point_type": "0", // "futures_taker_fee": "0.0005", // "futures_maker_fee": "0" // } // ch <- this.ParseTradingFees(response) return nil }() return ch } func (this *gate) ParseTradingFees(response interface{}) interface{} { var result interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(this.Symbols)); i++ { var symbol interface{} = GetValue(this.Symbols, i) var market interface{} = this.Market(symbol) AddElementToObject(result, symbol, this.ParseTradingFee(response, market)) } return result } func (this *gate) ParseTradingFee(info interface{}, optionalArgs ...interface{}) interface{} { // // { // "user_id": 1486602, // "taker_fee": "0.002", // "maker_fee": "0.002", // "gt_discount": true, // "gt_taker_fee": "0.0015", // "gt_maker_fee": "0.0015", // "loan_fee": "0.18", // "point_type": "0", // "futures_taker_fee": "0.0005", // "futures_maker_fee": "0" // } // market := GetArg(optionalArgs, 0, nil) _ = market var gtDiscount interface{} = this.SafeValue(info, "gt_discount") var taker interface{} = Ternary(IsTrue(gtDiscount), "gt_taker_fee", "taker_fee") var maker interface{} = Ternary(IsTrue(gtDiscount), "gt_maker_fee", "maker_fee") var contract interface{} = this.SafeValue(market, "contract") var takerKey interface{} = Ternary(IsTrue(contract), "futures_taker_fee", taker) var makerKey interface{} = Ternary(IsTrue(contract), "futures_maker_fee", maker) return map[string]interface{} { "info": info, "symbol": this.SafeString(market, "symbol"), "maker": this.SafeNumber(info, makerKey), "taker": this.SafeNumber(info, takerKey), "percentage": nil, "tierBased": nil, } } /** * @method * @name gate#fetchTransactionFees * @deprecated * @description please use fetchDepositWithdrawFees instead * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-withdrawal-status * @param {string[]|undefined} codes list of unified currency codes * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a list of [fee structures]{@link https://docs.ccxt.com/#/?id=fee-structure} */ func (this *gate) 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 retRes23468 := (<-this.LoadMarkets()) PanicOnError(retRes23468) response:= (<-this.PrivateWalletGetWithdrawStatus(params)) PanicOnError(response) // // { // "currency": "MTN", // "name": "Medicalchain", // "name_cn": "Medicalchain", // "deposit": "0", // "withdraw_percent": "0%", // "withdraw_fix": "900", // "withdraw_day_limit": "500000", // "withdraw_day_limit_remain": "500000", // "withdraw_amount_mini": "900.1", // "withdraw_eachtime_limit": "90000000000", // "withdraw_fix_on_chains": { // "ETH": "900" // } // } // var result interface{} = map[string]interface{} {} var withdrawFees interface{} = map[string]interface{} {} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { withdrawFees = map[string]interface{} {} var entry interface{} = GetValue(response, i) var currencyId interface{} = this.SafeString(entry, "currency") var code interface{} = this.SafeCurrencyCode(currencyId) if IsTrue(IsTrue((!IsEqual(codes, nil))) && !IsTrue(this.InArray(code, codes))) { continue } var withdrawFixOnChains interface{} = this.SafeValue(entry, "withdraw_fix_on_chains") if IsTrue(IsEqual(withdrawFixOnChains, nil)) { withdrawFees = this.SafeNumber(entry, "withdraw_fix") } else { var chainKeys interface{} = ObjectKeys(withdrawFixOnChains) for j := 0; IsLessThan(j, GetArrayLength(chainKeys)); j++ { var chainKey interface{} = GetValue(chainKeys, j) AddElementToObject(withdrawFees, chainKey, this.ParseNumber(GetValue(withdrawFixOnChains, chainKey))) } } AddElementToObject(result, code, map[string]interface{} { "withdraw": withdrawFees, "deposit": nil, "info": entry, }) } ch <- result return nil }() return ch } /** * @method * @name gate#fetchDepositWithdrawFees * @description fetch deposit and withdraw fees * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-withdrawal-status * @param {string[]|undefined} codes list of unified currency codes * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a list of [fee structures]{@link https://docs.ccxt.com/#/?id=fee-structure} */ func (this *gate) 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 retRes24048 := (<-this.LoadMarkets()) PanicOnError(retRes24048) response:= (<-this.PrivateWalletGetWithdrawStatus(params)) PanicOnError(response) // // [ // { // "currency": "MTN", // "name": "Medicalchain", // "name_cn": "Medicalchain", // "deposit": "0", // "withdraw_percent": "0%", // "withdraw_fix": "900", // "withdraw_day_limit": "500000", // "withdraw_day_limit_remain": "500000", // "withdraw_amount_mini": "900.1", // "withdraw_eachtime_limit": "90000000000", // "withdraw_fix_on_chains": { // "ETH": "900" // } // } // ] // ch <- this.ParseDepositWithdrawFees(response, codes, "currency") return nil }() return ch } func (this *gate) ParseDepositWithdrawFee(fee interface{}, optionalArgs ...interface{}) interface{} { // // { // "currency": "MTN", // "name": "Medicalchain", // "name_cn": "Medicalchain", // "deposit": "0", // "withdraw_percent": "0%", // "withdraw_fix": "900", // "withdraw_day_limit": "500000", // "withdraw_day_limit_remain": "500000", // "withdraw_amount_mini": "900.1", // "withdraw_eachtime_limit": "90000000000", // "withdraw_fix_on_chains": { // "ETH": "900" // } // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var withdrawFixOnChains interface{} = this.SafeValue(fee, "withdraw_fix_on_chains") var result interface{} = map[string]interface{} { "info": fee, "withdraw": map[string]interface{} { "fee": this.SafeNumber(fee, "withdraw_fix"), "percentage": false, }, "deposit": map[string]interface{} { "fee": this.SafeNumber(fee, "deposit"), "percentage": false, }, "networks": map[string]interface{} {}, } if IsTrue(!IsEqual(withdrawFixOnChains, nil)) { var chainKeys interface{} = ObjectKeys(withdrawFixOnChains) for i := 0; IsLessThan(i, GetArrayLength(chainKeys)); i++ { var chainKey interface{} = GetValue(chainKeys, i) var networkCode interface{} = this.NetworkIdToCode(chainKey, this.SafeString(fee, "currency")) AddElementToObject(GetValue(result, "networks"), networkCode, map[string]interface{} { "withdraw": map[string]interface{} { "fee": this.ParseNumber(GetValue(withdrawFixOnChains, chainKey)), "percentage": false, }, "deposit": map[string]interface{} { "fee": nil, "percentage": nil, }, }) } } return result } /** * @method * @name gate#fetchFundingHistory * @description fetch the history of funding payments paid and received on this account * @see https://www.gate.io/docs/developers/apiv4/en/#query-account-book-2 * @see https://www.gate.io/docs/developers/apiv4/en/#query-account-book-3 * @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 * @returns {object} a [funding history structure]{@link https://docs.ccxt.com/#/?id=funding-history-structure} */ func (this *gate) 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 retRes24928 := (<-this.LoadMarkets()) PanicOnError(retRes24928) // let defaultType = 'future'; var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) symbol = GetValue(market, "symbol") } typeVarqueryVariable := this.HandleMarketTypeAndParams("fetchFundingHistory", market, params); typeVar := GetValue(typeVarqueryVariable,0); query := GetValue(typeVarqueryVariable,1) requestrequestParamsVariable := this.PrepareRequest(market, typeVar, query); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) AddElementToObject(request, "type", "fund") // 'dnw' 'pnl' 'fee' 'refr' 'fund' 'point_dnw' 'point_fee' 'point_refr' if IsTrue(!IsEqual(since, nil)) { // from should be integer AddElementToObject(request, "from", this.ParseToInt(Divide(since, 1000))) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } var response interface{} = nil if IsTrue(IsEqual(typeVar, "swap")) { response = (<-this.PrivateFuturesGetSettleAccountBook(this.Extend(request, requestParams))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "future")) { response = (<-this.PrivateDeliveryGetSettleAccountBook(this.Extend(request, requestParams))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchFundingHistory() only support swap & future market type"))) } // // [ // { // "time": 1646899200, // "change": "-0.027722", // "balance": "11.653120591841", // "text": "XRP_USDT", // "type": "fund" // }, // ... // ] // ch <- this.ParseFundingHistories(response, symbol, since, limit) return nil }() return ch } func (this *gate) ParseFundingHistories(response interface{}, symbol interface{}, since interface{}, limit interface{}) interface{} { var result interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) var funding interface{} = this.ParseFundingHistory(entry) AppendToArray(&result,funding) } var sorted interface{} = this.SortBy(result, "timestamp") return this.FilterBySymbolSinceLimit(sorted, symbol, since, limit) } func (this *gate) ParseFundingHistory(info interface{}, optionalArgs ...interface{}) interface{} { // // { // "time": 1646899200, // "change": "-0.027722", // "balance": "11.653120591841", // "text": "XRP_USDT", // "type": "fund" // } // market := GetArg(optionalArgs, 0, nil) _ = market var timestamp interface{} = this.SafeTimestamp(info, "time") var marketId interface{} = this.SafeString(info, "text") market = this.SafeMarket(marketId, market, "_", "swap") return map[string]interface{} { "info": info, "symbol": this.SafeString(market, "symbol"), "code": this.SafeString(market, "settle"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "id": nil, "amount": this.SafeNumber(info, "change"), } } /** * @method * @name gate#fetchOrderBook * @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-order-book * @see https://www.gate.io/docs/developers/apiv4/en/#futures-order-book * @see https://www.gate.io/docs/developers/apiv4/en/#futures-order-book-2 * @see https://www.gate.io/docs/developers/apiv4/en/#options-order-book * @param {string} symbol unified symbol of the market to fetch the order book for * @param {int} [limit] the maximum amount of order book entries to return * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/#/?id=order-book-structure} indexed by market symbols */ func (this *gate) 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 retRes25818 := (<-this.LoadMarkets()) PanicOnError(retRes25818) var market interface{} = this.Market(symbol) // // const request: Dict = { // 'currency_pair': market['id'], // 'interval': '0', // depth, 0 means no aggregation is applied, default to 0 // 'limit': limit, // maximum number of order depth data in asks or bids // 'with_id': true, // return order book ID // }; // requestqueryVariable := this.PrepareRequest(market, GetValue(market, "type"), params); request := GetValue(requestqueryVariable,0); query := GetValue(requestqueryVariable,1) if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) // default 10, max 100 } AddElementToObject(request, "with_id", true) var response interface{} = nil if IsTrue(IsTrue(GetValue(market, "spot")) || IsTrue(GetValue(market, "margin"))) { response = (<-this.PublicSpotGetOrderBook(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "swap")) { response = (<-this.PublicFuturesGetSettleOrderBook(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "future")) { response = (<-this.PublicDeliveryGetSettleOrderBook(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "option")) { response = (<-this.PublicOptionsGetOrderBook(this.Extend(request, query))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchOrderBook() not support this market type"))) } // // spot // // { // "id": 6358770031 // "current": 1634345973275, // "update": 1634345973271, // "asks": [ // ["2.2241","12449.827"], // ["2.2242","200"], // ["2.2244","826.931"], // ["2.2248","3876.107"], // ["2.225","2377.252"], // ["2.22509","439.484"], // ["2.2251","1489.313"], // ["2.2253","714.582"], // ["2.2254","1349.784"], // ["2.2256","234.701"]], // "bids": [ // ["2.2236","32.465"], // ["2.2232","243.983"], // ["2.2231","32.207"], // ["2.223","449.827"], // ["2.2228","7.918"], // ["2.2227","12703.482"], // ["2.2226","143.033"], // ["2.2225","143.027"], // ["2.2224","1369.352"], // ["2.2223","756.063"] // ] // } // // swap, future and option // // { // "id": 6358770031 // "current": 1634350208.745, // "asks": [ // {"s": 24909, "p": "61264.8"}, // {"s": 81, "p": "61266.6"}, // {"s": 2000, "p": "61267.6"}, // {"s": 490, "p": "61270.2"}, // {"s": 12, "p": "61270.4"}, // {"s": 11782, "p": "61273.2"}, // {"s": 14666, "p": "61273.3"}, // {"s": 22541, "p": "61273.4"}, // {"s": 33, "p": "61273.6"}, // {"s": 11980, "p": "61274.5"} // ], // "bids": [ // {"s": 41844, "p": "61264.7"}, // {"s": 13783, "p": "61263.3"}, // {"s": 1143, "p": "61259.8"}, // {"s": 81, "p": "61258.7"}, // {"s": 2471, "p": "61257.8"}, // {"s": 2471, "p": "61257.7"}, // {"s": 2471, "p": "61256.5"}, // {"s": 3, "p": "61254.2"}, // {"s": 114, "p": "61252.4"}, // {"s": 14372, "p": "61248.6"} // ], // "update": 1634350208.724 // } // var timestamp interface{} = this.SafeInteger(response, "current") if !IsTrue(GetValue(market, "spot")) { timestamp = Multiply(timestamp, 1000) } var priceKey interface{} = Ternary(IsTrue(GetValue(market, "spot")), 0, "p") var amountKey interface{} = Ternary(IsTrue(GetValue(market, "spot")), 1, "s") var nonce interface{} = this.SafeInteger(response, "id") var result interface{} = this.ParseOrderBook(response, symbol, timestamp, "bids", "asks", priceKey, amountKey) AddElementToObject(result, "nonce", nonce) ch <- result return nil }() return ch } /** * @method * @name gate#fetchTicker * @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market * @see https://www.gate.io/docs/developers/apiv4/en/#get-details-of-a-specifc-order * @see https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers * @see https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers-2 * @see https://www.gate.io/docs/developers/apiv4/en/#list-tickers-of-options-contracts * @param {string} symbol unified symbol of the market to fetch the ticker for * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ func (this *gate) 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 retRes26978 := (<-this.LoadMarkets()) PanicOnError(retRes26978) var market interface{} = this.Market(symbol) requestqueryVariable := this.PrepareRequest(market, nil, params); request := GetValue(requestqueryVariable,0); query := GetValue(requestqueryVariable,1) var response interface{} = nil if IsTrue(IsTrue(GetValue(market, "spot")) || IsTrue(GetValue(market, "margin"))) { response = (<-this.PublicSpotGetTickers(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "swap")) { response = (<-this.PublicFuturesGetSettleTickers(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "future")) { response = (<-this.PublicDeliveryGetSettleTickers(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "option")) { var marketId interface{} = GetValue(market, "id") var optionParts interface{} = Split(marketId, "-") AddElementToObject(request, "underlying", this.SafeString(optionParts, 0)) response = (<-this.PublicOptionsGetTickers(this.Extend(request, query))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchTicker() not support this market type"))) } var ticker interface{} = nil if IsTrue(GetValue(market, "option")) { for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) if IsTrue(IsEqual(GetValue(entry, "name"), GetValue(market, "id"))) { ticker = entry break } } } else { ticker = this.SafeValue(response, 0) } ch <- this.ParseTicker(ticker, market) return nil }() return ch } func (this *gate) ParseTicker(ticker interface{}, optionalArgs ...interface{}) interface{} { // // SPOT // // { // "currency_pair": "KFC_USDT", // "last": "7.255", // "lowest_ask": "7.298", // "highest_bid": "7.218", // "change_percentage": "-1.18", // "base_volume": "1219.053687865", // "quote_volume": "8807.40299875455", // "high_24h": "7.262", // "low_24h": "7.095" // } // // LINEAR/DELIVERY // // { // "contract": "BTC_USDT", // "last": "6432", // "low_24h": "6278", // "high_24h": "6790", // "change_percentage": "4.43", // "total_size": "32323904", // "volume_24h": "184040233284", // "volume_24h_btc": "28613220", // "volume_24h_usd": "184040233284", // "volume_24h_base": "28613220", // "volume_24h_quote": "184040233284", // "volume_24h_settle": "28613220", // "mark_price": "6534", // "funding_rate": "0.0001", // "funding_rate_indicative": "0.0001", // "index_price": "6531" // } // // bookTicker // { // "t": 1671363004228, // "u": 9793320464, // "s": "BTC_USDT", // "b": "16716.8", // best bid price // "B": "0.0134", // best bid size // "a": "16716.9", // best ask price // "A": "0.0353" // best ask size // } // // option // // { // "vega": "0.00002", // "leverage": "12.277188268663", // "ask_iv": "0", // "delta": "-0.99999", // "last_price": "0", // "theta": "-0.00661", // "bid1_price": "1096", // "mark_iv": "0.7799", // "name": "BTC_USDT-20230608-28500-P", // "bid_iv": "0", // "ask1_price": "2935", // "mark_price": "2147.3", // "position_size": 0, // "bid1_size": 12, // "ask1_size": -14, // "gamma": "0" // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeStringN(ticker, []interface{}{"currency_pair", "contract", "name"}) var marketType interface{} = Ternary(IsTrue((InOp(ticker, "mark_price"))), "contract", "spot") var symbol interface{} = this.SafeSymbol(marketId, market, "_", marketType) var last interface{} = this.SafeString2(ticker, "last", "last_price") var ask interface{} = this.SafeStringN(ticker, []interface{}{"lowest_ask", "a", "ask1_price"}) var bid interface{} = this.SafeStringN(ticker, []interface{}{"highest_bid", "b", "bid1_price"}) var high interface{} = this.SafeString(ticker, "high_24h") var low interface{} = this.SafeString(ticker, "low_24h") var bidVolume interface{} = this.SafeString2(ticker, "B", "bid1_size") var askVolume interface{} = this.SafeString2(ticker, "A", "ask1_size") var timestamp interface{} = this.SafeInteger(ticker, "t") var baseVolume interface{} = this.SafeString2(ticker, "base_volume", "volume_24h_base") if IsTrue(IsEqual(baseVolume, "nan")) { baseVolume = "0" } var quoteVolume interface{} = this.SafeString2(ticker, "quote_volume", "volume_24h_quote") if IsTrue(IsEqual(quoteVolume, "nan")) { quoteVolume = "0" } var percentage interface{} = this.SafeString(ticker, "change_percentage") return this.SafeTicker(map[string]interface{} { "symbol": symbol, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "high": high, "low": low, "bid": bid, "bidVolume": bidVolume, "ask": ask, "askVolume": askVolume, "vwap": nil, "open": nil, "close": last, "last": last, "previousClose": nil, "change": nil, "percentage": percentage, "average": nil, "baseVolume": baseVolume, "quoteVolume": quoteVolume, "markPrice": this.SafeString(ticker, "mark_price"), "indexPrice": this.SafeString(ticker, "index_price"), "info": ticker, }, market) } /** * @method * @name gate#fetchTickers * @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market * @see https://www.gate.io/docs/developers/apiv4/en/#get-details-of-a-specifc-order * @see https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers * @see https://www.gate.io/docs/developers/apiv4/en/#list-futures-tickers-2 * @see https://www.gate.io/docs/developers/apiv4/en/#list-tickers-of-options-contracts * @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure} */ func (this *gate) 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 retRes28588 := (<-this.LoadMarkets()) PanicOnError(retRes28588) symbols = this.MarketSymbols(symbols) var first interface{} = this.SafeString(symbols, 0) var market interface{} = nil if IsTrue(!IsEqual(first, nil)) { market = this.Market(first) } typeVarqueryVariable := this.HandleMarketTypeAndParams("fetchTickers", market, params); typeVar := GetValue(typeVarqueryVariable,0); query := GetValue(typeVarqueryVariable,1) requestrequestParamsVariable := this.PrepareRequest(nil, typeVar, query); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) var response interface{} = nil AddElementToObject(request, "timezone", "utc0") // default to utc if IsTrue(IsTrue(IsEqual(typeVar, "spot")) || IsTrue(IsEqual(typeVar, "margin"))) { response = (<-this.PublicSpotGetTickers(this.Extend(request, requestParams))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "swap")) { response = (<-this.PublicFuturesGetSettleTickers(this.Extend(request, requestParams))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "future")) { response = (<-this.PublicDeliveryGetSettleTickers(this.Extend(request, requestParams))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "option")) { this.CheckRequiredArgument("fetchTickers", symbols, "symbols") var marketId interface{} = GetValue(market, "id") var optionParts interface{} = Split(marketId, "-") AddElementToObject(request, "underlying", this.SafeString(optionParts, 0)) response = (<-this.PublicOptionsGetTickers(this.Extend(request, requestParams))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchTickers() not support this market type, provide symbols or set params[\"defaultType\"] to one from spot/margin/swap/future/option"))) } ch <- this.ParseTickers(response, symbols) return nil }() return ch } func (this *gate) ParseBalanceHelper(entry interface{}) interface{} { var account interface{} = this.Account() AddElementToObject(account, "used", this.SafeString2(entry, "freeze", "locked")) AddElementToObject(account, "free", this.SafeString(entry, "available")) AddElementToObject(account, "total", this.SafeString(entry, "total")) if IsTrue(InOp(entry, "borrowed")) { AddElementToObject(account, "debt", this.SafeString(entry, "borrowed")) } return account } /** * @method * @name gate#fetchBalance * @param {object} [params] exchange specific parameters * @param {string} [params.type] spot, margin, swap or future, if not provided this.options['defaultType'] is used * @param {string} [params.settle] 'btc' or 'usdt' - settle currency for perpetual swap and future - default="usdt" for swap and "btc" for future * @param {string} [params.marginMode] 'cross' or 'isolated' - marginMode for margin trading if not provided this.options['defaultMarginMode'] is used * @param {string} [params.symbol] margin only - unified ccxt symbol * @param {boolean} [params.unifiedAccount] default false, set to true for fetching the unified account balance * @returns {object} a [balance structure]{@link https://docs.ccxt.com/#/?id=balance-structure} */ func (this *gate) 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 retRes29108 := (<-this.LoadMarkets()) PanicOnError(retRes29108) retRes29118 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes29118) var symbol interface{} = this.SafeString(params, "symbol") params = this.Omit(params, "symbol") var isUnifiedAccount interface{} = false isUnifiedAccountparamsVariable := this.HandleOptionAndParams(params, "fetchBalance", "unifiedAccount"); isUnifiedAccount = GetValue(isUnifiedAccountparamsVariable,0); params = GetValue(isUnifiedAccountparamsVariable,1) typeVarqueryVariable := this.HandleMarketTypeAndParams("fetchBalance", nil, params); typeVar := GetValue(typeVarqueryVariable,0); query := GetValue(typeVarqueryVariable,1) requestrequestParamsVariable := this.PrepareRequest(nil, typeVar, query); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) marginModerequestQueryVariable := this.GetMarginMode(false, requestParams); marginMode := GetValue(marginModerequestQueryVariable,0); requestQuery := GetValue(marginModerequestQueryVariable,1) if IsTrue(!IsEqual(symbol, nil)) { var market interface{} = this.Market(symbol) AddElementToObject(request, "currency_pair", GetValue(market, "id")) } var response interface{} = nil if IsTrue(isUnifiedAccount) { response = (<-this.PrivateUnifiedGetAccounts(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "spot")) { if IsTrue(IsEqual(marginMode, "spot")) { response = (<-this.PrivateSpotGetAccounts(this.Extend(request, requestQuery))) PanicOnError(response) } else if IsTrue(IsEqual(marginMode, "margin")) { response = (<-this.PrivateMarginGetAccounts(this.Extend(request, requestQuery))) PanicOnError(response) } else if IsTrue(IsEqual(marginMode, "cross_margin")) { response = (<-this.PrivateMarginGetCrossAccounts(this.Extend(request, requestQuery))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchBalance() not support this marginMode"))) } } else if IsTrue(IsEqual(typeVar, "funding")) { response = (<-this.PrivateMarginGetFundingAccounts(this.Extend(request, requestQuery))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "swap")) { response = (<-this.PrivateFuturesGetSettleAccounts(this.Extend(request, requestQuery))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "future")) { response = (<-this.PrivateDeliveryGetSettleAccounts(this.Extend(request, requestQuery))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.PrivateOptionsGetAccounts(this.Extend(request, requestQuery))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchBalance() not support this market type"))) } var contract interface{} = (IsTrue(IsTrue((IsEqual(typeVar, "swap"))) || IsTrue((IsEqual(typeVar, "future")))) || IsTrue((IsEqual(typeVar, "option")))) if IsTrue(contract) { response = []interface{}{response} } // // Spot / margin funding // // [ // { // "currency": "DBC", // "available": "0", // "locked": "0" // "lent": "0", // margin funding only // "total_lent": "0" // margin funding only // }, // ... // ] // // Margin // // [ // { // "currency_pair": "DOGE_USDT", // "locked": false, // "risk": "9999.99", // "base": { // "currency": "DOGE", // "available": "0", // "locked": "0", // "borrowed": "0", // "interest": "0" // }, // "quote": { // "currency": "USDT", // "available": "0.73402", // "locked": "0", // "borrowed": "0", // "interest": "0" // } // }, // ... // ] // // Cross margin // // { // "user_id": 10406147, // "locked": false, // "balances": { // "USDT": { // "available": "1", // "freeze": "0", // "borrowed": "0", // "interest": "0" // } // }, // "total": "1", // "borrowed": "0", // "interest": "0", // "risk": "9999.99" // } // // Perpetual Swap // // { // "order_margin": "0", // "point": "0", // "bonus": "0", // "history": { // "dnw": "2.1321", // "pnl": "11.5351", // "refr": "0", // "point_fee": "0", // "fund": "-0.32340576684", // "bonus_dnw": "0", // "point_refr": "0", // "bonus_offset": "0", // "fee": "-0.20132775", // "point_dnw": "0", // }, // "unrealised_pnl": "13.315100000006", // "total": "12.51345151332", // "available": "0", // "in_dual_mode": false, // "currency": "USDT", // "position_margin": "12.51345151332", // "user": "6333333", // } // // Delivery Future // // { // "order_margin": "0", // "point": "0", // "history": { // "dnw": "1", // "pnl": "0", // "refr": "0", // "point_fee": "0", // "point_dnw": "0", // "settle": "0", // "settle_fee": "0", // "point_refr": "0", // "fee": "0", // }, // "unrealised_pnl": "0", // "total": "1", // "available": "1", // "currency": "USDT", // "position_margin": "0", // "user": "6333333", // } // // option // // { // "order_margin": "0", // "bid_order_margin": "0", // "init_margin": "0", // "history": { // "dnw": "32", // "set": "0", // "point_fee": "0", // "point_dnw": "0", // "prem": "0", // "point_refr": "0", // "insur": "0", // "fee": "0", // "refr": "0" // }, // "total": "32", // "available": "32", // "liq_triggered": false, // "maint_margin": "0", // "ask_order_margin": "0", // "point": "0", // "position_notional_limit": "2000000", // "unrealised_pnl": "0", // "equity": "32", // "user": 5691076, // "currency": "USDT", // "short_enabled": false, // "orders_limit": 10 // } // // unified // // { // "user_id": 10001, // "locked": false, // "balances": { // "ETH": { // "available": "0", // "freeze": "0", // "borrowed": "0.075393666654", // "negative_liab": "0", // "futures_pos_liab": "0", // "equity": "1016.1", // "total_freeze": "0", // "total_liab": "0" // }, // "POINT": { // "available": "9999999999.017023138734", // "freeze": "0", // "borrowed": "0", // "negative_liab": "0", // "futures_pos_liab": "0", // "equity": "12016.1", // "total_freeze": "0", // "total_liab": "0" // }, // "USDT": { // "available": "0.00000062023", // "freeze": "0", // "borrowed": "0", // "negative_liab": "0", // "futures_pos_liab": "0", // "equity": "16.1", // "total_freeze": "0", // "total_liab": "0" // } // }, // "total": "230.94621713", // "borrowed": "161.66395521", // "total_initial_margin": "1025.0524665088", // "total_margin_balance": "3382495.944473949183", // "total_maintenance_margin": "205.01049330176", // "total_initial_margin_rate": "3299.827135672679", // "total_maintenance_margin_rate": "16499.135678363399", // "total_available_margin": "3381470.892007440383", // "unified_account_total": "3381470.892007440383", // "unified_account_total_liab": "0", // "unified_account_total_equity": "100016.1", // "leverage": "2" // } // var result interface{} = map[string]interface{} { "info": response, } var isolated interface{} = IsEqual(marginMode, "margin") var data interface{} = response if IsTrue(InOp(data, "balances")) { var flatBalances interface{} = []interface{}{} var balances interface{} = this.SafeValue(data, "balances", []interface{}{}) // inject currency and create an artificial balance object // so it can follow the existent flow var keys interface{} = ObjectKeys(balances) for i := 0; IsLessThan(i, GetArrayLength(keys)); i++ { var currencyId interface{} = GetValue(keys, i) var content interface{} = GetValue(balances, currencyId) AddElementToObject(content, "currency", currencyId) AppendToArray(&flatBalances,content) } data = flatBalances } for i := 0; IsLessThan(i, GetArrayLength(data)); i++ { var entry interface{} = GetValue(data, i) if IsTrue(isolated) { var marketId interface{} = this.SafeString(entry, "currency_pair") var symbolInner interface{} = this.SafeSymbol(marketId, nil, "_", "margin") var base interface{} = this.SafeValue(entry, "base", map[string]interface{} {}) var quote interface{} = this.SafeValue(entry, "quote", map[string]interface{} {}) var baseCode interface{} = this.SafeCurrencyCode(this.SafeString(base, "currency")) var quoteCode interface{} = this.SafeCurrencyCode(this.SafeString(quote, "currency")) var subResult interface{} = map[string]interface{} {} AddElementToObject(subResult, baseCode, this.ParseBalanceHelper(base)) AddElementToObject(subResult, quoteCode, this.ParseBalanceHelper(quote)) AddElementToObject(result, symbolInner, this.SafeBalance(subResult)) } else { var code interface{} = this.SafeCurrencyCode(this.SafeString(entry, "currency")) AddElementToObject(result, code, this.ParseBalanceHelper(entry)) } } var returnResult interface{} = Ternary(IsTrue(isolated), result, this.SafeBalance(result)) ch <- returnResult return nil }() return ch } /** * @method * @name gateio#fetchOHLCV * @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market * @see https://www.gate.io/docs/developers/apiv4/en/#market-candlesticks // spot * @see https://www.gate.io/docs/developers/apiv4/en/#get-futures-candlesticks // swap * @see https://www.gate.io/docs/developers/apiv4/en/#market-candlesticks // future * @see https://www.gate.io/docs/developers/apiv4/en/#get-options-candlesticks // option * @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, limit is conflicted with since and params["until"], If either since and params["until"] is specified, request will be rejected * @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 [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume (units in quote currency) */ func (this *gate) 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 retRes32038 := (<-this.LoadMarkets()) PanicOnError(retRes32038) var market interface{} = this.Market(symbol) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOHLCV", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes320819 := (<-this.FetchPaginatedCallDeterministic("fetchOHLCV", symbol, since, limit, timeframe, params, 1000)) PanicOnError(retRes320819) ch <- retRes320819 return nil } if IsTrue(GetValue(market, "option")) { retRes321119 := (<-this.FetchOptionOHLCV(symbol, timeframe, since, limit, params)) PanicOnError(retRes321119) ch <- retRes321119 return nil } var price interface{} = this.SafeString(params, "price") var request interface{} = map[string]interface{} {} requestparamsVariable := this.PrepareRequest(market, nil, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) AddElementToObject(request, "interval", this.SafeString(this.Timeframes, timeframe, timeframe)) var maxLimit interface{} = Ternary(IsTrue(GetValue(market, "contract")), 1999, 1000) limit = Ternary(IsTrue((IsEqual(limit, nil))), maxLimit, mathMin(limit, maxLimit)) var until interface{} = this.SafeInteger(params, "until") if IsTrue(!IsEqual(until, nil)) { until = this.ParseToInt(Divide(until, 1000)) params = this.Omit(params, "until") } if IsTrue(!IsEqual(since, nil)) { var duration interface{} = this.ParseTimeframe(timeframe) AddElementToObject(request, "from", this.ParseToInt(Divide(since, 1000))) var distance interface{} = Multiply((Subtract(limit, 1)), duration) var toTimestamp interface{} = this.Sum(GetValue(request, "from"), distance) var currentTimestamp interface{} = this.Seconds() var to interface{} = mathMin(toTimestamp, currentTimestamp) if IsTrue(!IsEqual(until, nil)) { AddElementToObject(request, "to", mathMin(to, until)) } else { AddElementToObject(request, "to", to) } } else { if IsTrue(!IsEqual(until, nil)) { AddElementToObject(request, "to", until) } AddElementToObject(request, "limit", limit) } var response interface{} = nil if IsTrue(GetValue(market, "contract")) { var isMark interface{} = (IsEqual(price, "mark")) var isIndex interface{} = (IsEqual(price, "index")) if IsTrue(IsTrue(isMark) || IsTrue(isIndex)) { AddElementToObject(request, "contract", Add(Add(price, "_"), GetValue(market, "id"))) params = this.Omit(params, "price") } if IsTrue(GetValue(market, "future")) { response = (<-this.PublicDeliveryGetSettleCandlesticks(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "swap")) { response = (<-this.PublicFuturesGetSettleCandlesticks(this.Extend(request, params))) PanicOnError(response) } } else { response = (<-this.PublicSpotGetCandlesticks(this.Extend(request, params))) PanicOnError(response) } ch <- this.ParseOHLCVs(response, market, timeframe, since, limit) return nil }() return ch } func (this *gate) FetchOptionOHLCV(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) // separated option logic because the from, to and limit parameters weren't functioning 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 retRes32638 := (<-this.LoadMarkets()) PanicOnError(retRes32638) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} {} requestparamsVariable := this.PrepareRequest(market, nil, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) AddElementToObject(request, "interval", this.SafeString(this.Timeframes, timeframe, timeframe)) response:= (<-this.PublicOptionsGetCandlesticks(this.Extend(request, params))) PanicOnError(response) ch <- this.ParseOHLCVs(response, market, timeframe, since, limit) return nil }() return ch } /** * @method * @name gate#fetchFundingRateHistory * @description fetches historical funding rate prices * @see https://www.gate.io/docs/developers/apiv4/en/#funding-rate-history * @param {string} symbol unified symbol of the market to fetch the funding rate history for * @param {int} [since] timestamp in ms of the earliest funding rate to fetch * @param {int} [limit] the maximum amount of [funding rate structures]{@link https://docs.ccxt.com/#/?id=funding-rate-history-structure} to fetch * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.until] timestamp in ms of the latest funding rate to fetch * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/#/?id=funding-rate-history-structure} */ func (this *gate) FetchFundingRateHistory(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) symbol := GetArg(optionalArgs, 0, nil) _ = symbol since := GetArg(optionalArgs, 1, nil) _ = since limit := GetArg(optionalArgs, 2, nil) _ = limit params := GetArg(optionalArgs, 3, map[string]interface{} {}) _ = params if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchFundingRateHistory() requires a symbol argument"))) } retRes32898 := (<-this.LoadMarkets()) PanicOnError(retRes32898) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchFundingRateHistory", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes329319 := (<-this.FetchPaginatedCallDeterministic("fetchFundingRateHistory", symbol, since, limit, "8h", params)) PanicOnError(retRes329319) ch <- retRes329319 return nil } var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "swap")) { panic(BadSymbol(Add(this.Id, " fetchFundingRateHistory() supports swap contracts only"))) } var request interface{} = map[string]interface{} {} requestparamsVariable := this.PrepareRequest(market, nil, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", this.ParseToInt(Divide(since, 1000))) } var until interface{} = this.SafeInteger(params, "until") if IsTrue(!IsEqual(until, nil)) { params = this.Omit(params, "until") AddElementToObject(request, "to", this.ParseToInt(Divide(until, 1000))) } response:= (<-this.PublicFuturesGetSettleFundingRate(this.Extend(request, params))) PanicOnError(response) // // { // "r": "0.00063521", // "t": "1621267200000", // } // var rates interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) var timestamp interface{} = this.SafeTimestamp(entry, "t") AppendToArray(&rates,map[string]interface{} { "info": entry, "symbol": symbol, "fundingRate": this.SafeNumber(entry, "r"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), }) } var sorted interface{} = this.SortBy(rates, "timestamp") ch <- this.FilterBySymbolSinceLimit(sorted, GetValue(market, "symbol"), since, limit) return nil }() return ch } func (this *gate) ParseOHLCV(ohlcv interface{}, optionalArgs ...interface{}) interface{} { // // Spot market candles // // [ // "1660957920", // timestamp // "6227.070147198573", // quote volume // "0.0000133485", // close // "0.0000133615", // high // "0.0000133347", // low // "0.0000133468", // open // "466641934.99" // base volume // ] // // // Swap, Future, Option, Mark and Index price candles // // { // "t":1632873600, // Unix timestamp in seconds // "o": "41025", // Open price // "h": "41882.17", // Highest price // "c": "41776.92", // Close price // "l": "40783.94" // Lowest price // } // // Swap, Future, Option, Mark and Index price candles market := GetArg(optionalArgs, 0, nil) _ = market if IsTrue(IsArray(ohlcv)) { return []interface{}{this.SafeTimestamp(ohlcv, 0), this.SafeNumber(ohlcv, 5), this.SafeNumber(ohlcv, 3), this.SafeNumber(ohlcv, 4), this.SafeNumber(ohlcv, 2), this.SafeNumber(ohlcv, 6)} } else { return []interface{}{this.SafeTimestamp(ohlcv, "t"), this.SafeNumber(ohlcv, "o"), this.SafeNumber(ohlcv, "h"), this.SafeNumber(ohlcv, "l"), this.SafeNumber(ohlcv, "c"), this.SafeNumber(ohlcv, "v")} } } /** * @method * @name gate#fetchTrades * @description get the list of most recent trades for a particular symbol * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-market-trades * @see https://www.gate.io/docs/developers/apiv4/en/#futures-trading-history * @see https://www.gate.io/docs/developers/apiv4/en/#futures-trading-history-2 * @see https://www.gate.io/docs/developers/apiv4/en/#options-trade-history * @param {string} symbol unified symbol of the market to fetch trades for * @param {int} [since] timestamp in ms of the earliest trade to fetch * @param {int} [limit] the maximum amount of trades to fetch * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.until] timestamp in ms of the latest trade to fetch * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades} */ func (this *gate) 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 retRes33998 := (<-this.LoadMarkets()) PanicOnError(retRes33998) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchTrades", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes340319 := (<-this.FetchPaginatedCallDynamic("fetchTrades", symbol, since, limit, params)) PanicOnError(retRes340319) ch <- retRes340319 return nil } var market interface{} = this.Market(symbol) // // spot // // const request: Dict = { // 'currency_pair': market['id'], // 'limit': limit, // maximum number of records to be returned in a single list // 'last_id': 'id', // specify list staring point using the id of last record in previous list-query results // 'reverse': false, // true to retrieve records where id is smaller than the specified last_id, false to retrieve records where id is larger than the specified last_id // }; // // swap, future // // const request: Dict = { // 'settle': market['settleId'], // 'contract': market['id'], // 'limit': limit, // maximum number of records to be returned in a single list // 'last_id': 'id', // specify list staring point using the id of last record in previous list-query results // 'from': since / 1000), // starting time in seconds, if not specified, to and limit will be used to limit response items // 'to': this.seconds (), // end time in seconds, default to current time // }; // requestqueryVariable := this.PrepareRequest(market, nil, params); request := GetValue(requestqueryVariable,0); query := GetValue(requestqueryVariable,1) var until interface{} = this.SafeInteger2(params, "to", "until") if IsTrue(!IsEqual(until, nil)) { params = this.Omit(params, []interface{}{"until"}) AddElementToObject(request, "to", this.ParseToInt(Divide(until, 1000))) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", mathMin(limit, 1000)) // default 100, max 1000 } if IsTrue(IsTrue(!IsEqual(since, nil)) && IsTrue((GetValue(market, "contract")))) { AddElementToObject(request, "from", this.ParseToInt(Divide(since, 1000))) } var response interface{} = nil if IsTrue(IsTrue(IsEqual(GetValue(market, "type"), "spot")) || IsTrue(IsEqual(GetValue(market, "type"), "margin"))) { response = (<-this.PublicSpotGetTrades(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "swap")) { response = (<-this.PublicFuturesGetSettleTrades(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "future")) { response = (<-this.PublicDeliveryGetSettleTrades(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(IsEqual(GetValue(market, "type"), "option")) { response = (<-this.PublicOptionsGetTrades(this.Extend(request, query))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchTrades() not support this market type."))) } // // spot // // [ // { // "id": "1852958144", // "create_time": "1634673259", // "create_time_ms": "1634673259378.105000", // "currency_pair": "ADA_USDT", // "side": "sell", // "amount": "307.078", // "price": "2.104", // } // ] // // perpetual swap // // [ // { // "size": "2", // "id": "2522911", // "create_time_ms": "1634673380.182", // "create_time": "1634673380.182", // "contract": "ADA_USDT", // "price": "2.10486", // } // ] // // option // // [ // { // "size": -5, // "id": 25, // "create_time": 1682378573, // "contract": "ETH_USDT-20230526-2000-P", // "price": "209.1" // } // ] // ch <- this.ParseTrades(response, market, since, limit) return nil }() return ch } /** * @method * @name gate#fetchOrderTrades * @description fetch all the trades made from a single order * @see https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history * @see https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-2 * @see https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-3 * @see https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-4 * @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 *gate) 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"))) } retRes35138 := (<-this.LoadMarkets()) PanicOnError(retRes35138) // // [ // { // "id":"3711449544", // "create_time":"1655486040", // "create_time_ms":"1655486040177.599900", // "currency_pair":"SHIB_USDT", // "side":"buy", // "role":"taker", // "amount":"1360039", // "price":"0.0000081084", // "order_id":"169717399644", // "fee":"2720.078", // "fee_currency":"SHIB", // "point_fee":"0", // "gt_fee":"0" // } // ] // response:= (<-this.FetchMyTrades(symbol, since, limit, map[string]interface{} { "order_id": id, })) PanicOnError(response) ch <- response return nil }() return ch } /** * @method * @name gate#fetchMyTrades * @description Fetch personal trading history * @see https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history * @see https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-2 * @see https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-3 * @see https://www.gate.io/docs/developers/apiv4/en/#list-personal-trading-history-4 * @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 {string} [params.marginMode] 'cross' or 'isolated' - marginMode for margin trading if not provided this.options['defaultMarginMode'] is used * @param {string} [params.type] 'spot', 'swap', or 'future', if not provided this.options['defaultMarginMode'] is used * @param {int} [params.until] The latest timestamp, in ms, that fetched trades were made * @param {int} [params.page] *spot only* Page number * @param {string} [params.order_id] *spot only* Filter trades with specified order ID. symbol is also required if this field is present * @param {string} [params.order] *contract only* Futures order ID, return related data only if specified * @param {int} [params.offset] *contract only* list offset, starting from 0 * @param {string} [params.last_id] *contract only* specify list staring point using the id of last record in previous list-query results * @param {int} [params.count_total] *contract only* whether to return total number matched, default to 0(no return) * @param {bool} [params.unifiedAccount] set to true for fetching trades in a unified account * @param {bool} [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 {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure} */ func (this *gate) 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 retRes35638 := (<-this.LoadMarkets()) PanicOnError(retRes35638) retRes35648 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes35648) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchMyTrades", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes356819 := (<-this.FetchPaginatedCallDynamic("fetchMyTrades", symbol, since, limit, params)) PanicOnError(retRes356819) ch <- retRes356819 return nil } var typeVar interface{} = nil var marginMode interface{} = nil var request interface{} = map[string]interface{} {} var market interface{} = Ternary(IsTrue((!IsEqual(symbol, nil))), this.Market(symbol), nil) var until interface{} = this.SafeInteger(params, "until") params = this.Omit(params, []interface{}{"until"}) typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchMyTrades", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var contract interface{} = IsTrue(IsTrue((IsEqual(typeVar, "swap"))) || IsTrue((IsEqual(typeVar, "future")))) || IsTrue((IsEqual(typeVar, "option"))) if IsTrue(contract) { requestparamsVariable := this.PrepareRequest(market, typeVar, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) if IsTrue(IsEqual(typeVar, "option")) { params = this.Omit(params, "order_id") } } else { if IsTrue(!IsEqual(market, nil)) { AddElementToObject(request, "currency_pair", GetValue(market, "id")) // Should always be set for non-trigger } marginModeparamsVariable := this.GetMarginMode(false, params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) AddElementToObject(request, "account", marginMode) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) // default 100, max 1000 } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", this.ParseToInt(Divide(since, 1000))) } if IsTrue(!IsEqual(until, nil)) { AddElementToObject(request, "to", this.ParseToInt(Divide(until, 1000))) } var response interface{} = nil if IsTrue(IsTrue(IsEqual(typeVar, "spot")) || IsTrue(IsEqual(typeVar, "margin"))) { response = (<-this.PrivateSpotGetMyTrades(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "swap")) { response = (<-this.PrivateFuturesGetSettleMyTradesTimerange(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "future")) { response = (<-this.PrivateDeliveryGetSettleMyTrades(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.PrivateOptionsGetMyTrades(this.Extend(request, params))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchMyTrades() not support this market type."))) } // // spot // // [ // { // "id": "2876130500", // "create_time": "1645464610", // "create_time_ms": "1645464610777.399200", // "currency_pair": "DOGE_USDT", // "side": "sell", // "role": "taker", // "amount": "10.97", // "price": "0.137384", // "order_id": "125924049993", // "fee": "0.00301420496", // "fee_currency": "USDT", // "point_fee": "0", // "gt_fee": "0" // } // ] // // perpetual swap // // [ // { // "size": -5, // "order_id": "130264979823", // "id": 26884791, // "role": "taker", // "create_time": 1645465199.5472, // "contract": "DOGE_USDT", // "price": "0.136888" // } // ] // // future // // [ // { // "id": 121234231, // "create_time": 1514764800.123, // "contract": "BTC_USDT", // "order_id": "21893289839", // "size": 100, // "price": "100.123", // "role": "taker" // } // ] // // option // // [ // { // "underlying_price": "26817.84", // "size": -1, // "contract": "BTC_USDT-20230602-26500-C", // "id": 16, // "role": "taker", // "create_time": 1685594770, // "order_id": 2611026125, // "price": "333" // } // ] // ch <- this.ParseTrades(response, market, since, limit) return nil }() return ch } func (this *gate) ParseTrade(trade interface{}, optionalArgs ...interface{}) interface{} { // // public // // spot: // { // "id": "1334253759", // "create_time": "1626342738", // "create_time_ms": "1626342738331.497000", // "currency_pair": "BTC_USDT", // "side": "sell", // "amount": "0.0022", // "price": "32452.16" // } // // swap: // // { // "id": "442288327", // "contract": "BTC_USDT", // "create_time": "1739814676.707", // "create_time_ms": "1739814676.707", // "size": "-105", // "price": "95594.8" // } // // // public ws // // { // "id": 221994511, // "time": 1580311438.618647, // "price": "9309", // "amount": "0.0019", // "type": "sell" // } // // spot rest // // { // "id": "2876130500", // "create_time": "1645464610", // "create_time_ms": "1645464610777.399200", // "currency_pair": "DOGE_USDT", // "side": "sell", // "role": "taker", // "amount": "10.97", // "price": "0.137384", // "order_id": "125924049993", // "fee": "0.00301420496", // "fee_currency": "USDT", // "point_fee": "1.1", // "gt_fee":"2.2" // } // // perpetual swap rest // // { // "size": -5, // "order_id": "130264979823", // "id": 26884791, // "role": "taker", // "create_time": 1645465199.5472, // "contract": "DOGE_USDT", // "price": "0.136888" // } // // future rest // // { // "id": 121234231, // "create_time": 1514764800.123, // "contract": "BTC_USDT", // "order_id": "21893289839", // "size": 100, // "price": "100.123", // "role": "taker" // } // // fetchTrades: option // // { // "size": -5, // "id": 25, // "create_time": 1682378573, // "contract": "ETH_USDT-20230526-2000-P", // "price": "209.1" // } // // fetchMyTrades: option // // { // "underlying_price": "26817.84", // "size": -1, // "contract": "BTC_USDT-20230602-26500-C", // "id": 16, // "role": "taker", // "create_time": 1685594770, // "order_id": 2611026125, // "price": "333" // } // market := GetArg(optionalArgs, 0, nil) _ = market var id interface{} = this.SafeString2(trade, "id", "trade_id") var timestamp interface{} = nil var msString interface{} = this.SafeString(trade, "create_time_ms") if IsTrue(!IsEqual(msString, nil)) { msString = Precise.StringMul(msString, "1000") msString = Slice(msString, 0, 13) timestamp = this.ParseToInt(msString) } else { timestamp = this.SafeTimestamp2(trade, "time", "create_time") } var marketId interface{} = this.SafeString2(trade, "currency_pair", "contract") var marketType interface{} = Ternary(IsTrue((InOp(trade, "contract"))), "contract", "spot") market = this.SafeMarket(marketId, market, "_", marketType) var amountString interface{} = this.SafeString2(trade, "amount", "size") var priceString interface{} = this.SafeString(trade, "price") var contractSide interface{} = Ternary(IsTrue(Precise.StringLt(amountString, "0")), "sell", "buy") amountString = Precise.StringAbs(amountString) var side interface{} = this.SafeString2(trade, "side", "type", contractSide) var orderId interface{} = this.SafeString(trade, "order_id") var feeAmount interface{} = this.SafeString(trade, "fee") var gtFee interface{} = this.OmitZero(this.SafeString(trade, "gt_fee")) var pointFee interface{} = this.OmitZero(this.SafeString(trade, "point_fee")) var fees interface{} = []interface{}{} if IsTrue(!IsEqual(feeAmount, nil)) { var feeCurrencyId interface{} = this.SafeString(trade, "fee_currency") var feeCurrencyCode interface{} = this.SafeCurrencyCode(feeCurrencyId) if IsTrue(IsEqual(feeCurrencyCode, nil)) { feeCurrencyCode = this.SafeString(market, "settle") } AppendToArray(&fees,map[string]interface{} { "cost": feeAmount, "currency": feeCurrencyCode, }) } if IsTrue(!IsEqual(gtFee, nil)) { AppendToArray(&fees,map[string]interface{} { "cost": gtFee, "currency": "GT", }) } if IsTrue(!IsEqual(pointFee, nil)) { AppendToArray(&fees,map[string]interface{} { "cost": pointFee, "currency": "GatePoint", }) } var takerOrMaker interface{} = this.SafeString(trade, "role") return this.SafeTrade(map[string]interface{} { "info": trade, "id": id, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "symbol": GetValue(market, "symbol"), "order": orderId, "type": nil, "side": side, "takerOrMaker": takerOrMaker, "price": priceString, "amount": amountString, "cost": nil, "fee": nil, "fees": fees, }, market) } /** * @method * @name gate#fetchDeposits * @description fetch all deposits made to an account * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-deposit-records * @param {string} code unified currency code * @param {int} [since] the earliest time in ms to fetch deposits for * @param {int} [limit] the maximum number of deposits structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.until] end time in ms * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure} */ func (this *gate) 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 retRes38598 := (<-this.LoadMarkets()) PanicOnError(retRes38598) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchDeposits", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes386319 := (<-this.FetchPaginatedCallDynamic("fetchDeposits", code, since, limit, params)) PanicOnError(retRes386319) ch <- retRes386319 return nil } var request interface{} = map[string]interface{} {} var currency interface{} = nil if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) AddElementToObject(request, "currency", GetValue(currency, "id")) // todo: currencies have network-junctions } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } if IsTrue(!IsEqual(since, nil)) { var start interface{} = this.ParseToInt(Divide(since, 1000)) AddElementToObject(request, "from", start) AddElementToObject(request, "to", this.Sum(start, Multiply(Multiply(Multiply(30, 24), 60), 60))) } requestparamsVariable := this.HandleUntilOption("to", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) response:= (<-this.PrivateWalletGetDeposits(this.Extend(request, params))) PanicOnError(response) ch <- this.ParseTransactions(response, currency) return nil }() return ch } /** * @method * @name gate#fetchWithdrawals * @description fetch all withdrawals made from an account * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-withdrawal-records * @param {string} code unified currency code * @param {int} [since] the earliest time in ms to fetch withdrawals for * @param {int} [limit] the maximum number of withdrawals structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {int} [params.until] end time in ms * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure} */ func (this *gate) 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 retRes38988 := (<-this.LoadMarkets()) PanicOnError(retRes38988) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchWithdrawals", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes390219 := (<-this.FetchPaginatedCallDynamic("fetchWithdrawals", code, since, limit, params)) PanicOnError(retRes390219) ch <- retRes390219 return nil } var request interface{} = map[string]interface{} {} var currency interface{} = nil if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) AddElementToObject(request, "currency", GetValue(currency, "id")) // todo: currencies have network-junctions } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } if IsTrue(!IsEqual(since, nil)) { var start interface{} = this.ParseToInt(Divide(since, 1000)) AddElementToObject(request, "from", start) AddElementToObject(request, "to", this.Sum(start, Multiply(Multiply(Multiply(30, 24), 60), 60))) } requestparamsVariable := this.HandleUntilOption("to", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) response:= (<-this.PrivateWalletGetWithdrawals(this.Extend(request, params))) PanicOnError(response) ch <- this.ParseTransactions(response, currency) return nil }() return ch } /** * @method * @name gate#withdraw * @description make a withdrawal * @see https://www.gate.io/docs/developers/apiv4/en/#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 *gate) 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) retRes39388 := (<-this.LoadMarkets()) PanicOnError(retRes39388) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "currency": GetValue(currency, "id"), "address": address, "amount": this.CurrencyToPrecision(code, amount), } if IsTrue(!IsEqual(tag, nil)) { AddElementToObject(request, "memo", tag) } var networkCode interface{} = nil networkCodeparamsVariable := this.HandleNetworkCodeAndParams(params); networkCode = GetValue(networkCodeparamsVariable,0); params = GetValue(networkCodeparamsVariable,1) if IsTrue(!IsEqual(networkCode, nil)) { AddElementToObject(request, "chain", this.NetworkCodeToId(networkCode)) } response:= (<-this.PrivateWithdrawalsPostWithdrawals(this.Extend(request, params))) PanicOnError(response) // // { // "id": "w13389675", // "currency": "USDT", // "amount": "50", // "address": "TUu2rLFrmzUodiWfYki7QCNtv1akL682p1", // "memo": null // } // ch <- this.ParseTransaction(response, currency) return nil }() return ch } func (this *gate) ParseTransactionStatus(status interface{}) interface{} { var statuses interface{} = map[string]interface{} { "PEND": "pending", "REQUEST": "pending", "DMOVE": "pending", "MANUAL": "pending", "VERIFY": "pending", "PROCES": "pending", "EXTPEND": "pending", "SPLITPEND": "pending", "CANCEL": "canceled", "FAIL": "failed", "INVALID": "failed", "DONE": "ok", "BCODE": "ok", } return this.SafeString(statuses, status, status) } func (this *gate) ParseTransactionType(typeVar interface{}) interface{} { var types interface{} = map[string]interface{} { "d": "deposit", "w": "withdrawal", } return this.SafeString(types, typeVar, typeVar) } func (this *gate) ParseTransaction(transaction interface{}, optionalArgs ...interface{}) interface{} { // // fetchDeposits // // { // "id": "d33361395", // "currency": "USDT_TRX", // "address": "TErdnxenuLtXfnMafLbfappYdHtnXQ5U4z", // "amount": "100", // "txid": "ae9374de34e558562fe18cbb1bf9ab4d9eb8aa7669d65541c9fa2a532c1474a0", // "timestamp": "1626345819", // "status": "DONE", // "memo": "" // } // // withdraw // // { // "id":"w64413318", // "currency":"usdt", // "amount":"10150", // "address":"0x0ab891497116f7f5532a4c2f4f7b1784488628e1", // "memo":null, // "status":"REQUEST", // "chain":"eth", // "withdraw_order_id":"", // "fee_amount":"4.15000000" // } // // fetchWithdrawals // // { // "id": "210496", // "timestamp": "1542000000", // "withdraw_order_id": "order_123456", // "currency": "USDT", // "address": "1HkxtBAMrA3tP5ENnYY2CZortjZvFDH5Cs", // "txid": "128988928203223323290", // "block_number": "41575382", // "amount": "222.61", // "fee": "0.01", // "memo": "", // "status": "DONE", // "chain": "TRX" // } // // { // "id": "w13389675", // "currency": "USDT", // "amount": "50", // "address": "TUu2rLFrmzUodiWfYki7QCNtv1akL682p1", // "memo": null // } // // { // "currency":"usdt", // "address":"0x01c0A9b7b4CdE774AF0f3E47CB4f1c2CCdBa0806", // "amount":"1880", // "chain":"eth" // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var id interface{} = this.SafeString(transaction, "id") var typeVar interface{} = nil var amountString interface{} = this.SafeString(transaction, "amount") if IsTrue(!IsEqual(id, nil)) { if IsTrue(IsEqual(GetValue(id, 0), "b")) { // GateCode handling typeVar = Ternary(IsTrue(Precise.StringGt(amountString, "0")), "deposit", "withdrawal") amountString = Precise.StringAbs(amountString) } else { typeVar = this.ParseTransactionType(GetValue(id, 0)) } } var feeCostString interface{} = this.SafeString2(transaction, "fee", "fee_amount") if IsTrue(IsEqual(typeVar, "withdrawal")) { amountString = Precise.StringSub(amountString, feeCostString) } var networkId interface{} = this.SafeStringUpper(transaction, "chain") var currencyId interface{} = this.SafeString(transaction, "currency") var code interface{} = this.SafeCurrencyCode(currencyId) var txid interface{} = this.SafeString(transaction, "txid") var rawStatus interface{} = this.SafeString(transaction, "status") var status interface{} = this.ParseTransactionStatus(rawStatus) var address interface{} = this.SafeString(transaction, "address") var tag interface{} = this.SafeString(transaction, "memo") var timestamp interface{} = this.SafeTimestamp(transaction, "timestamp") return map[string]interface{} { "info": transaction, "id": id, "txid": txid, "currency": code, "amount": this.ParseNumber(amountString), "network": this.NetworkIdToCode(networkId), "address": address, "addressTo": nil, "addressFrom": nil, "tag": tag, "tagTo": nil, "tagFrom": nil, "status": status, "type": typeVar, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "updated": nil, "internal": nil, "comment": nil, "fee": map[string]interface{} { "currency": code, "cost": this.ParseNumber(feeCostString), }, } } /** * @method * @name gate#createOrder * @description Create an order on the exchange * @see https://www.gate.io/docs/developers/apiv4/en/#create-an-order * @see https://www.gate.io/docs/developers/apiv4/en/#create-a-price-triggered-order * @see https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order * @see https://www.gate.io/docs/developers/apiv4/en/#create-a-price-triggered-order-2 * @see https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order-2 * @see https://www.gate.io/docs/developers/apiv4/en/#create-a-price-triggered-order-3 * @see https://www.gate.io/docs/developers/apiv4/en/#create-an-options-order * @param {string} symbol Unified CCXT market symbol * @param {string} type 'limit' or 'market' *"market" is contract only* * @param {string} side 'buy' or 'sell' * @param {float} amount the amount of currency to trade * @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 {float} [params.triggerPrice] The price at which a trigger order is triggered at * @param {string} [params.timeInForce] "GTC", "IOC", or "PO" * @param {float} [params.stopLossPrice] The price at which a stop loss order is triggered at * @param {float} [params.takeProfitPrice] The price at which a take profit order is triggered at * @param {string} [params.marginMode] 'cross' or 'isolated' - marginMode for margin trading if not provided this.options['defaultMarginMode'] is used * @param {int} [params.iceberg] Amount to display for the iceberg order, Null or 0 for normal orders, Set to -1 to hide the order completely * @param {string} [params.text] User defined information * @param {string} [params.account] *spot and margin only* "spot", "margin" or "cross_margin" * @param {bool} [params.auto_borrow] *margin only* Used in margin or cross margin trading to allow automatic loan of insufficient amount if balance is not enough * @param {string} [params.settle] *contract only* Unified Currency Code for settle currency * @param {bool} [params.reduceOnly] *contract only* Indicates if this order is to reduce the size of a position * @param {bool} [params.close] *contract only* Set as true to close the position, with size set to 0 * @param {bool} [params.auto_size] *contract only* Set side to close dual-mode position, close_long closes the long side, while close_short the short one, size also needs to be set to 0 * @param {int} [params.price_type] *contract only* 0 latest deal price, 1 mark price, 2 index price * @param {float} [params.cost] *spot market buy only* the quote quantity that can be used as an alternative for the amount * @param {bool} [params.unifiedAccount] set to true for creating an order in the unified account * @returns {object|undefined} [An order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) 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 retRes41428 := (<-this.LoadMarkets()) PanicOnError(retRes41428) retRes41438 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes41438) var market interface{} = this.Market(symbol) var trigger interface{} = this.SafeValue(params, "trigger") var triggerPrice interface{} = this.SafeValue2(params, "triggerPrice", "stopPrice") var stopLossPrice interface{} = this.SafeValue(params, "stopLossPrice", triggerPrice) var takeProfitPrice interface{} = this.SafeValue(params, "takeProfitPrice") var isStopLossOrder interface{} = !IsEqual(stopLossPrice, nil) var isTakeProfitOrder interface{} = !IsEqual(takeProfitPrice, nil) var isTpsl interface{} = IsTrue(isStopLossOrder) || IsTrue(isTakeProfitOrder) var nonTriggerOrder interface{} = !IsTrue(isTpsl) && IsTrue((IsEqual(trigger, nil))) var orderRequest interface{} = this.CreateOrderRequest(symbol, typeVar, side, amount, price, params) var response interface{} = nil if IsTrue(IsTrue(GetValue(market, "spot")) || IsTrue(GetValue(market, "margin"))) { if IsTrue(nonTriggerOrder) { response = (<-this.PrivateSpotPostOrders(orderRequest)) PanicOnError(response) } else { response = (<-this.PrivateSpotPostPriceOrders(orderRequest)) PanicOnError(response) } } else if IsTrue(GetValue(market, "swap")) { if IsTrue(nonTriggerOrder) { response = (<-this.PrivateFuturesPostSettleOrders(orderRequest)) PanicOnError(response) } else { response = (<-this.PrivateFuturesPostSettlePriceOrders(orderRequest)) PanicOnError(response) } } else if IsTrue(GetValue(market, "future")) { if IsTrue(nonTriggerOrder) { response = (<-this.PrivateDeliveryPostSettleOrders(orderRequest)) PanicOnError(response) } else { response = (<-this.PrivateDeliveryPostSettlePriceOrders(orderRequest)) PanicOnError(response) } } else { response = (<-this.PrivateOptionsPostOrders(orderRequest)) PanicOnError(response) } // const response = await this[method] (this.deepExtend (request, params)); // // spot // // { // "id": "95282841887", // "text": "apiv4", // "create_time": "1637383156", // "update_time": "1637383156", // "create_time_ms": 1637383156017, // "update_time_ms": 1637383156017, // "status": "open", // "currency_pair": "ETH_USDT", // "type": "limit", // "account": "spot", // "side": "buy", // "amount": "0.01", // "price": "3500", // "time_in_force": "gtc", // "iceberg": "0", // "left": "0.01", // "fill_price": "0", // "filled_total": "0", // "fee": "0", // "fee_currency": "ETH", // "point_fee": "0", // "gt_fee": "0", // "gt_discount": false, // "rebated_fee": "0", // "rebated_fee_currency": "USDT" // } // // spot conditional // // {"id": 5891843} // // futures, perpetual swaps and options // // { // "id": 95938572327, // "contract": "ETH_USDT", // "mkfr": "0", // "tkfr": "0.0005", // "tif": "gtc", // "is_reduce_only": false, // "create_time": 1637384600.08, // "price": "3000", // "size": 1, // "refr": "0", // "left": 1, // "text": "api", // "fill_price": "0", // "user": 2436035, // "status": "open", // "is_liq": false, // "refu": 0, // "is_close": false, // "iceberg": 0 // } // // futures and perpetual swaps conditionals // // {"id": 7615567} // ch <- this.ParseOrder(response, market) return nil }() return ch } func (this *gate) CreateOrdersRequest(orders interface{}, optionalArgs ...interface{}) interface{} { params := GetArg(optionalArgs, 0, map[string]interface{} {}) _ = params var ordersRequests interface{} = []interface{}{} var orderSymbols interface{} = []interface{}{} var ordersLength interface{} = GetArrayLength(orders) if IsTrue(IsEqual(ordersLength, 0)) { panic(BadRequest(Add(this.Id, " createOrders() requires at least one order"))) } if IsTrue(IsGreaterThan(ordersLength, 10)) { panic(BadRequest(Add(this.Id, " createOrders() accepts a maximum of 10 orders at a time"))) } 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.SafeValue(rawOrder, "params", map[string]interface{} {}) var extendedParams interface{} = this.Extend(orderParams, params) // the request does not accept extra params since it's a list, so we're extending each order with the common params var triggerValue interface{} = this.SafeValueN(orderParams, []interface{}{"triggerPrice", "stopPrice", "takeProfitPrice", "stopLossPrice"}) if IsTrue(!IsEqual(triggerValue, nil)) { panic(NotSupported(Add(this.Id, " createOrders() does not support advanced order properties (stopPrice, takeProfitPrice, stopLossPrice)"))) } AddElementToObject(extendedParams, "textIsRequired", true) // Gate.io requires a text parameter for each order here var orderRequest interface{} = this.CreateOrderRequest(marketId, typeVar, side, amount, price, extendedParams) AppendToArray(&ordersRequests,orderRequest) } var symbols interface{} = this.MarketSymbols(orderSymbols, nil, false, true, true) var market interface{} = this.Market(GetValue(symbols, 0)) if IsTrue(IsTrue(GetValue(market, "future")) || IsTrue(GetValue(market, "option"))) { panic(NotSupported(Add(this.Id, " createOrders() does not support futures or options markets"))) } return ordersRequests } /** * @method * @name gate#createOrders * @description create a list of trade orders * @see https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-2 * @see https://www.gate.io/docs/developers/apiv4/en/#create-a-batch-of-orders * @see https://www.gate.io/docs/developers/apiv4/en/#create-a-batch-of-futures-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 *gate) 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 retRes42918 := (<-this.LoadMarkets()) PanicOnError(retRes42918) retRes42928 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes42928) var ordersRequests interface{} = this.CreateOrdersRequest(orders, params) var firstOrder interface{} = GetValue(orders, 0) var market interface{} = this.Market(GetValue(firstOrder, "symbol")) var response interface{} = nil if IsTrue(GetValue(market, "spot")) { response = (<-this.PrivateSpotPostBatchOrders(ordersRequests)) PanicOnError(response) } else if IsTrue(GetValue(market, "swap")) { response = (<-this.PrivateFuturesPostSettleBatchOrders(ordersRequests)) PanicOnError(response) } ch <- this.ParseOrders(response) return nil }() return ch } func (this *gate) CreateOrderRequest(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) var contract interface{} = GetValue(market, "contract") var trigger interface{} = this.SafeValue(params, "trigger") var triggerPrice interface{} = this.SafeValue2(params, "triggerPrice", "stopPrice") var stopLossPrice interface{} = this.SafeValue(params, "stopLossPrice", triggerPrice) var takeProfitPrice interface{} = this.SafeValue(params, "takeProfitPrice") var isStopLossOrder interface{} = !IsEqual(stopLossPrice, nil) var isTakeProfitOrder interface{} = !IsEqual(takeProfitPrice, nil) var isTpsl interface{} = IsTrue(isStopLossOrder) || IsTrue(isTakeProfitOrder) if IsTrue(IsTrue(isStopLossOrder) && IsTrue(isTakeProfitOrder)) { panic(ExchangeError(Add(this.Id, " createOrder() stopLossPrice and takeProfitPrice cannot both be defined"))) } var reduceOnly interface{} = this.SafeValue(params, "reduceOnly") var exchangeSpecificTimeInForce interface{} = this.SafeStringLowerN(params, []interface{}{"timeInForce", "tif", "time_in_force"}) var postOnly interface{} = nil postOnlyparamsVariable := this.HandlePostOnly(IsEqual(typeVar, "market"), IsEqual(exchangeSpecificTimeInForce, "poc"), params); postOnly = GetValue(postOnlyparamsVariable,0); params = GetValue(postOnlyparamsVariable,1) var timeInForce interface{} = this.HandleTimeInForce(params) if IsTrue(postOnly) { timeInForce = "poc" } // we only omit the unified params here // this is because the other params will get extended into the request params = this.Omit(params, []interface{}{"stopPrice", "triggerPrice", "stopLossPrice", "takeProfitPrice", "reduceOnly", "timeInForce", "postOnly"}) var isLimitOrder interface{} = (IsEqual(typeVar, "limit")) var isMarketOrder interface{} = (IsEqual(typeVar, "market")) if IsTrue(IsTrue(isLimitOrder) && IsTrue(IsEqual(price, nil))) { panic(ArgumentsRequired(Add(Add(Add(this.Id, " createOrder () requires a price argument for "), typeVar), " orders"))) } if IsTrue(isMarketOrder) { if IsTrue(IsTrue((IsEqual(timeInForce, "poc"))) || IsTrue((IsEqual(timeInForce, "gtc")))) { panic(ExchangeError(Add(this.Id, " createOrder () timeInForce for market order can only be \"FOK\" or \"IOC\""))) } else { if IsTrue(IsEqual(timeInForce, nil)) { var defaultTif interface{} = this.SafeString(this.Options, "defaultTimeInForce", "IOC") var exchangeSpecificTif interface{} = this.SafeString(GetValue(this.Options, "timeInForce"), defaultTif, "ioc") timeInForce = exchangeSpecificTif } } if IsTrue(contract) { price = 0 } } if IsTrue(contract) { var isClose interface{} = this.SafeValue(params, "close") if IsTrue(isClose) { amount = 0 } else { var amountToPrecision interface{} = this.AmountToPrecision(symbol, amount) var signedAmount interface{} = Ternary(IsTrue((IsEqual(side, "sell"))), Precise.StringNeg(amountToPrecision), amountToPrecision) amount = ParseInt(signedAmount) } } var request interface{} = nil var nonTriggerOrder interface{} = !IsTrue(isTpsl) && IsTrue((IsEqual(trigger, nil))) if IsTrue(nonTriggerOrder) { if IsTrue(contract) { // contract order request = map[string]interface{} { "contract": GetValue(market, "id"), "size": amount, } if !IsTrue(GetValue(market, "option")) { AddElementToObject(request, "settle", GetValue(market, "settleId")) // filled in prepareRequest above } if IsTrue(isMarketOrder) { AddElementToObject(request, "price", "0") // set to 0 for market orders } else { AddElementToObject(request, "price", Ternary(IsTrue((IsEqual(price, 0))), "0", this.PriceToPrecision(symbol, price))) } if IsTrue(!IsEqual(reduceOnly, nil)) { AddElementToObject(request, "reduce_only", reduceOnly) } if IsTrue(!IsEqual(timeInForce, nil)) { AddElementToObject(request, "tif", timeInForce) } } else { var marginMode interface{} = nil marginModeparamsVariable := this.GetMarginMode(false, params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) // spot order request = map[string]interface{} { "currency_pair": GetValue(market, "id"), "type": typeVar, "account": marginMode, "side": side, } if IsTrue(IsTrue(isMarketOrder) && IsTrue((IsEqual(side, "buy")))) { var quoteAmount interface{} = nil var createMarketBuyOrderRequiresPrice interface{} = true createMarketBuyOrderRequiresPriceparamsVariable := this.HandleOptionAndParams(params, "createOrder", "createMarketBuyOrderRequiresPrice", true); createMarketBuyOrderRequiresPrice = GetValue(createMarketBuyOrderRequiresPriceparamsVariable,0); params = GetValue(createMarketBuyOrderRequiresPriceparamsVariable,1) var cost interface{} = this.SafeNumber(params, "cost") params = this.Omit(params, "cost") if IsTrue(!IsEqual(cost, nil)) { quoteAmount = this.CostToPrecision(symbol, cost) } else if IsTrue(createMarketBuyOrderRequiresPrice) { if IsTrue(IsEqual(price, nil)) { panic(InvalidOrder(Add(this.Id, " createOrder() requires the price argument for market buy orders to calculate the total cost to spend (amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to false and pass the cost to spend (quote quantity) in the amount argument"))) } else { var amountString interface{} = this.NumberToString(amount) var priceString interface{} = this.NumberToString(price) var costRequest interface{} = Precise.StringMul(amountString, priceString) quoteAmount = this.CostToPrecision(symbol, costRequest) } } else { quoteAmount = this.CostToPrecision(symbol, amount) } AddElementToObject(request, "amount", quoteAmount) } else { AddElementToObject(request, "amount", this.AmountToPrecision(symbol, amount)) } if IsTrue(isLimitOrder) { AddElementToObject(request, "price", this.PriceToPrecision(symbol, price)) } if IsTrue(!IsEqual(timeInForce, nil)) { AddElementToObject(request, "time_in_force", timeInForce) } } var clientOrderId interface{} = this.SafeString2(params, "text", "clientOrderId") var textIsRequired interface{} = this.SafeBool(params, "textIsRequired", false) if IsTrue(!IsEqual(clientOrderId, nil)) { // user-defined, must follow the rules if not empty // prefixed with t- // no longer than 28 bytes without t- prefix // can only include 0-9, A-Z, a-z, underscores (_), hyphens (-) or dots (.) if IsTrue(IsGreaterThan(GetLength(clientOrderId), 28)) { panic(BadRequest(Add(this.Id, " createOrder () clientOrderId or text param must be up to 28 characters"))) } params = this.Omit(params, []interface{}{"text", "clientOrderId", "textIsRequired"}) if IsTrue(!IsEqual(GetValue(clientOrderId, 0), "t")) { clientOrderId = Add("t-", clientOrderId) } AddElementToObject(request, "text", clientOrderId) } else { if IsTrue(textIsRequired) { // batchOrders requires text in the request AddElementToObject(request, "text", Add("t-", this.Uuid16())) } } } else { if IsTrue(GetValue(market, "option")) { panic(NotSupported(Add(this.Id, " createOrder() conditional option orders are not supported"))) } if IsTrue(contract) { // contract conditional order request = map[string]interface{} { "initial": map[string]interface{} { "contract": GetValue(market, "id"), "size": amount, }, "settle": GetValue(market, "settleId"), } if IsTrue(IsEqual(typeVar, "market")) { AddElementToObject(GetValue(request, "initial"), "price", "0") } else { AddElementToObject(GetValue(request, "initial"), "price", Ternary(IsTrue((IsEqual(price, 0))), "0", this.PriceToPrecision(symbol, price))) } if IsTrue(IsEqual(trigger, nil)) { var rule interface{} = nil var triggerOrderPrice interface{} = nil if IsTrue(isStopLossOrder) { // we let trigger orders be aliases for stopLoss orders because // gateio doesn't accept conventional trigger orders for spot markets rule = Ternary(IsTrue((IsEqual(side, "buy"))), 1, 2) triggerOrderPrice = this.PriceToPrecision(symbol, stopLossPrice) } else if IsTrue(isTakeProfitOrder) { rule = Ternary(IsTrue((IsEqual(side, "buy"))), 2, 1) triggerOrderPrice = this.PriceToPrecision(symbol, takeProfitPrice) } var priceType interface{} = this.SafeInteger(params, "price_type", 0) if IsTrue(IsTrue(IsLessThan(priceType, 0)) || IsTrue(IsGreaterThan(priceType, 2))) { panic(BadRequest(Add(this.Id, " createOrder () price_type should be 0 latest deal price, 1 mark price, 2 index price"))) } params = this.Omit(params, []interface{}{"price_type"}) AddElementToObject(request, "trigger", map[string]interface{} { "price_type": priceType, "price": this.PriceToPrecision(symbol, triggerOrderPrice), "rule": rule, }) } if IsTrue(!IsEqual(reduceOnly, nil)) { AddElementToObject(GetValue(request, "initial"), "reduce_only", reduceOnly) } if IsTrue(!IsEqual(timeInForce, nil)) { AddElementToObject(GetValue(request, "initial"), "tif", timeInForce) } } else { // spot conditional order var options interface{} = this.SafeValue(this.Options, "createOrder", map[string]interface{} {}) var marginMode interface{} = nil marginModeparamsVariable := this.GetMarginMode(true, params); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) if IsTrue(IsEqual(timeInForce, nil)) { timeInForce = "gtc" } request = map[string]interface{} { "put": map[string]interface{} { "type": typeVar, "side": side, "price": this.PriceToPrecision(symbol, price), "amount": this.AmountToPrecision(symbol, amount), "account": marginMode, "time_in_force": timeInForce, }, "market": GetValue(market, "id"), } if IsTrue(IsEqual(trigger, nil)) { var defaultExpiration interface{} = this.SafeInteger(options, "expiration") var expiration interface{} = this.SafeInteger(params, "expiration", defaultExpiration) var rule interface{} = nil var triggerOrderPrice interface{} = nil if IsTrue(isStopLossOrder) { // we let trigger orders be aliases for stopLoss orders because // gateio doesn't accept conventional trigger orders for spot markets rule = Ternary(IsTrue((IsEqual(side, "buy"))), ">=", "<=") triggerOrderPrice = this.PriceToPrecision(symbol, stopLossPrice) } else if IsTrue(isTakeProfitOrder) { rule = Ternary(IsTrue((IsEqual(side, "buy"))), "<=", ">=") triggerOrderPrice = this.PriceToPrecision(symbol, takeProfitPrice) } AddElementToObject(request, "trigger", map[string]interface{} { "price": this.PriceToPrecision(symbol, triggerOrderPrice), "rule": rule, "expiration": expiration, }) } } } return this.Extend(request, params) } /** * @method * @name gate#createMarketBuyOrderWithCost * @description create a market buy order by providing the symbol and cost * @see https://www.gate.io/docs/developers/apiv4/en/#create-an-order * @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 * @param {bool} [params.unifiedAccount] set to true for creating a unified account order * @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) 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 retRes45648 := (<-this.LoadMarkets()) PanicOnError(retRes45648) retRes45658 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes45658) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "spot")) { panic(NotSupported(Add(this.Id, " createMarketBuyOrderWithCost() supports spot orders only"))) } AddElementToObject(params, "createMarketBuyOrderRequiresPrice", false) retRes457115 := (<-this.CreateOrder(symbol, "market", "buy", cost, nil, params)) PanicOnError(retRes457115) ch <- retRes457115 return nil }() return ch } func (this *gate) EditOrderRequest(id interface{}, symbol interface{}, typeVar interface{}, side interface{}, optionalArgs ...interface{}) interface{} { amount := GetArg(optionalArgs, 0, nil) _ = amount price := GetArg(optionalArgs, 1, nil) _ = price params := GetArg(optionalArgs, 2, map[string]interface{} {}) _ = params var market interface{} = this.Market(symbol) var marketType interface{} = nil marketTypeparamsVariable := this.HandleMarketTypeAndParams("editOrder", market, params); marketType = GetValue(marketTypeparamsVariable,0); params = GetValue(marketTypeparamsVariable,1) var account interface{} = this.ConvertTypeToAccount(marketType) var isUnifiedAccount interface{} = false isUnifiedAccountparamsVariable := this.HandleOptionAndParams(params, "editOrder", "unifiedAccount"); isUnifiedAccount = GetValue(isUnifiedAccountparamsVariable,0); params = GetValue(isUnifiedAccountparamsVariable,1) if IsTrue(isUnifiedAccount) { account = "unified" } var isLimitOrder interface{} = (IsEqual(typeVar, "limit")) if IsTrue(IsEqual(account, "spot")) { if !IsTrue(isLimitOrder) { panic(InvalidOrder(Add(Add(Add(Add(Add(this.Id, " editOrder() does not support "), typeVar), " orders for "), marketType), " markets"))) } } var request interface{} = map[string]interface{} { "order_id": ToString(id), "currency_pair": GetValue(market, "id"), "account": account, } if IsTrue(!IsEqual(amount, nil)) { if IsTrue(GetValue(market, "spot")) { AddElementToObject(request, "amount", this.AmountToPrecision(symbol, amount)) } else { if IsTrue(IsEqual(side, "sell")) { AddElementToObject(request, "size", this.ParseToNumeric(Precise.StringNeg(this.AmountToPrecision(symbol, amount)))) } else { AddElementToObject(request, "size", this.ParseToNumeric(this.AmountToPrecision(symbol, amount))) } } } if IsTrue(!IsEqual(price, nil)) { AddElementToObject(request, "price", this.PriceToPrecision(symbol, price)) } if !IsTrue(GetValue(market, "spot")) { AddElementToObject(request, "settle", GetValue(market, "settleId")) } return this.Extend(request, params) } /** * @method * @name gate#editOrder * @description edit a trade order, gate currently only supports the modification of the price or amount fields * @see https://www.gate.io/docs/developers/apiv4/en/#amend-an-order * @see https://www.gate.io/docs/developers/apiv4/en/#amend-an-order-2 * @param {string} id order id * @param {string} symbol unified symbol of the market to create an order in * @param {string} type 'market' or 'limit' * @param {string} side 'buy' or 'sell' * @param {float} amount how much of the currency you want to trade in units of the base currency * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {bool} [params.unifiedAccount] set to true for editing an order in a unified account * @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) 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 retRes46338 := (<-this.LoadMarkets()) PanicOnError(retRes46338) retRes46348 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes46348) var market interface{} = this.Market(symbol) var extendedRequest interface{} = this.EditOrderRequest(id, symbol, typeVar, side, amount, price, params) var response interface{} = nil if IsTrue(GetValue(market, "spot")) { response = (<-this.PrivateSpotPatchOrdersOrderId(extendedRequest)) PanicOnError(response) } else { response = (<-this.PrivateFuturesPutSettleOrdersOrderId(extendedRequest)) PanicOnError(response) } // // { // "id": "243233276443", // "text": "apiv4", // "create_time": "1670908873", // "update_time": "1670914102", // "create_time_ms": 1670908873077, // "update_time_ms": 1670914102241, // "status": "open", // "currency_pair": "ADA_USDT", // "type": "limit", // "account": "spot", // "side": "sell", // "amount": "10", // "price": "0.6", // "time_in_force": "gtc", // "iceberg": "0", // "left": "10", // "fill_price": "0", // "filled_total": "0", // "fee": "0", // "fee_currency": "USDT", // "point_fee": "0", // "gt_fee": "0", // "gt_maker_fee": "0", // "gt_taker_fee": "0", // "gt_discount": false, // "rebated_fee": "0", // "rebated_fee_currency": "ADA" // } // ch <- this.ParseOrder(response, market) return nil }() return ch } func (this *gate) ParseOrderStatus(status interface{}) interface{} { var statuses interface{} = map[string]interface{} { "open": "open", "_new": "open", "filled": "closed", "cancelled": "canceled", "liquidated": "closed", "ioc": "canceled", "failed": "canceled", "expired": "canceled", "finished": "closed", "finish": "closed", "succeeded": "closed", } return this.SafeString(statuses, status, status) } func (this *gate) ParseOrder(order interface{}, optionalArgs ...interface{}) interface{} { // // SPOT // createOrder/cancelOrder/fetchOrder/editOrder // // { // "id": "62364648575", // "text": "apiv4", // "create_time": "1626354834", // "update_time": "1626354834", // "create_time_ms": "1626354833544", // "update_time_ms": "1626354833544", // "status": "open", // "currency_pair": "BTC_USDT", // "type": "limit", // "account": "spot", // "side": "buy", // "amount": "0.0001", // "price": "30000", // "time_in_force": "gtc", // "iceberg": "0", // "left": "0.0001", // "fill_price": "0", // "filled_total": "0", // "fee": "0", // "fee_currency": "BTC", // "point_fee": "0", // "gt_fee": "0", // "gt_discount": true, // "rebated_fee": "0", // "rebated_fee_currency": "USDT" // } // // SPOT TRIGGER ORDERS // createOrder // // { // "id": 12604556 // } // // fetchOrder/cancelOrder // // { // "market": "ADA_USDT", // "user": 6392049, // "trigger": { // "price": "1.08", // stopPrice // "rule": "\u003e=", // "expiration": 86400 // }, // "put": { // "type": "limit", // "side": "buy", // "price": "1.08", // order price // "amount": "1.00000000000000000000", // "account": "normal", // "time_in_force": "gtc" // }, // "id": 71639298, // "ctime": 1643945985, // "status": "open" // } // // FUTURE, SWAP AND OPTION // createOrder/cancelOrder/fetchOrder // // { // "id": 123028481731, // "contract": "ADA_USDT", // "mkfr": "-0.00005", // "tkfr": "0.00048", // "tif": "ioc", // "is_reduce_only": false, // "create_time": 1643950262.68, // "finish_time": 1643950262.68, // "price": "0", // "size": 1, // "refr": "0", // "left":0, // "text": "api", // "fill_price": "1.05273", // "user":6329238, // "finish_as": "filled", // "status": "finished", // "is_liq": false, // "refu":0, // "is_close": false, // "iceberg": 0 // } // // TRIGGER ORDERS (FUTURE AND SWAP) // createOrder // // { // "id": 12604556 // } // // fetchOrder/cancelOrder // // { // "user": 6320300, // "trigger": { // "strategy_type": 0, // "price_type": 0, // "price": "1.03", // stopPrice // "rule": 2, // "expiration": 0 // }, // "initial": { // "contract": "ADA_USDT", // "size": -1, // "price": "1.02", // "tif": "gtc", // "text": "", // "iceberg": 0, // "is_close": false, // "is_reduce_only": false, // "auto_size": "" // }, // "id": 126393906, // "trade_id": 0, // "status": "open", // "reason": "", // "create_time": 1643953482, // "finish_time": 1643953482, // "is_stop_order": false, // "stop_trigger": { // "rule": 0, // "trigger_price": "", // "order_price": "" // }, // "me_order_id": 0, // "order_type": "" // } // // { // "text": "t-d18baf9ac44d82e2", // "succeeded": false, // "label": "BALANCE_NOT_ENOUGH", // "message": "Not enough balance" // } // // {"user_id":10406147,"id":"id","succeeded":false,"message":"INVALID_PROTOCOL","label":"INVALID_PROTOCOL"} // market := GetArg(optionalArgs, 0, nil) _ = market var succeeded interface{} = this.SafeBool(order, "succeeded", true) if !IsTrue(succeeded) { // cancelOrders response return this.SafeOrder(map[string]interface{} { "clientOrderId": this.SafeString(order, "text"), "info": order, "status": "rejected", "id": this.SafeString(order, "id"), }) } var put interface{} = this.SafeValue2(order, "put", "initial", map[string]interface{} {}) var trigger interface{} = this.SafeValue(order, "trigger", map[string]interface{} {}) var contract interface{} = this.SafeString(put, "contract") var typeVar interface{} = this.SafeString(put, "type") var timeInForce interface{} = this.SafeStringUpper2(put, "time_in_force", "tif") var amount interface{} = this.SafeString2(put, "amount", "size") var side interface{} = this.SafeString(put, "side") var price interface{} = this.SafeString(put, "price") contract = this.SafeString(order, "contract", contract) typeVar = this.SafeString(order, "type", typeVar) timeInForce = this.SafeStringUpper2(order, "time_in_force", "tif", timeInForce) if IsTrue(IsEqual(timeInForce, "POC")) { timeInForce = "PO" } var postOnly interface{} = (IsEqual(timeInForce, "PO")) amount = this.SafeString2(order, "amount", "size", amount) side = this.SafeString(order, "side", side) price = this.SafeString(order, "price", price) var remainingString interface{} = this.SafeString(order, "left") var cost interface{} = this.SafeString(order, "filled_total") var triggerPrice interface{} = this.SafeNumber(trigger, "price") var average interface{} = this.SafeNumber2(order, "avg_deal_price", "fill_price") if IsTrue(triggerPrice) { remainingString = amount cost = "0" } if IsTrue(contract) { var isMarketOrder interface{} = IsTrue(Precise.StringEquals(price, "0")) && IsTrue((IsEqual(timeInForce, "IOC"))) typeVar = Ternary(IsTrue(isMarketOrder), "market", "limit") side = Ternary(IsTrue(Precise.StringGt(amount, "0")), "buy", "sell") } var rawStatus interface{} = this.SafeStringN(order, []interface{}{"finish_as", "status", "open"}) var timestamp interface{} = this.SafeInteger(order, "create_time_ms") if IsTrue(IsEqual(timestamp, nil)) { timestamp = this.SafeTimestamp2(order, "create_time", "ctime") } var lastTradeTimestamp interface{} = this.SafeInteger(order, "update_time_ms") if IsTrue(IsEqual(lastTradeTimestamp, nil)) { lastTradeTimestamp = this.SafeTimestamp2(order, "update_time", "finish_time") } var marketType interface{} = "contract" if IsTrue(IsTrue((InOp(order, "currency_pair"))) || IsTrue((InOp(order, "market")))) { marketType = "spot" } var exchangeSymbol interface{} = this.SafeString2(order, "currency_pair", "market", contract) var symbol interface{} = this.SafeSymbol(exchangeSymbol, market, "_", marketType) // Everything below this(above return) is related to fees var fees interface{} = []interface{}{} var gtFee interface{} = this.SafeString(order, "gt_fee") if IsTrue(!IsEqual(gtFee, nil)) { AppendToArray(&fees,map[string]interface{} { "currency": "GT", "cost": gtFee, }) } var fee interface{} = this.SafeString(order, "fee") if IsTrue(!IsEqual(fee, nil)) { AppendToArray(&fees,map[string]interface{} { "currency": this.SafeCurrencyCode(this.SafeString(order, "fee_currency")), "cost": fee, }) } var rebate interface{} = this.SafeString(order, "rebated_fee") if IsTrue(!IsEqual(rebate, nil)) { AppendToArray(&fees,map[string]interface{} { "currency": this.SafeCurrencyCode(this.SafeString(order, "rebated_fee_currency")), "cost": Precise.StringNeg(rebate), }) } var numFeeCurrencies interface{} = GetArrayLength(fees) var multipleFeeCurrencies interface{} = IsGreaterThan(numFeeCurrencies, 1) var status interface{} = this.ParseOrderStatus(rawStatus) var remaining interface{} = Precise.StringAbs(remainingString) // handle spot market buy var account interface{} = this.SafeString(order, "account") // using this instead of market type because of the conflicting ids if IsTrue(IsEqual(account, "spot")) { var averageString interface{} = this.SafeString(order, "avg_deal_price") average = this.ParseNumber(averageString) if IsTrue(IsTrue((IsEqual(typeVar, "market"))) && IsTrue((IsEqual(side, "buy")))) { remaining = Precise.StringDiv(remainingString, averageString) price = nil // arrives as 0 cost = amount amount = Precise.StringDiv(amount, averageString) } } return this.SafeOrder(map[string]interface{} { "id": this.SafeString(order, "id"), "clientOrderId": this.SafeString(order, "text"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "lastTradeTimestamp": lastTradeTimestamp, "status": status, "symbol": symbol, "type": typeVar, "timeInForce": timeInForce, "postOnly": postOnly, "reduceOnly": this.SafeValue(order, "is_reduce_only"), "side": side, "price": price, "triggerPrice": triggerPrice, "average": average, "amount": Precise.StringAbs(amount), "cost": Precise.StringAbs(cost), "filled": nil, "remaining": remaining, "fee": Ternary(IsTrue(multipleFeeCurrencies), nil, this.SafeValue(fees, 0)), "fees": Ternary(IsTrue(multipleFeeCurrencies), fees, []interface{}{}), "trades": nil, "info": order, }, market) } func (this *gate) FetchOrderRequest(id interface{}, optionalArgs ...interface{}) interface{} { symbol := GetArg(optionalArgs, 0, nil) _ = symbol params := GetArg(optionalArgs, 1, map[string]interface{} {}) _ = params var market interface{} = Ternary(IsTrue((IsEqual(symbol, nil))), nil, this.Market(symbol)) var trigger interface{} = this.SafeBoolN(params, []interface{}{"trigger", "is_stop_order", "stop"}, false) params = this.Omit(params, []interface{}{"is_stop_order", "stop", "trigger"}) var clientOrderId interface{} = this.SafeString2(params, "text", "clientOrderId") var orderId interface{} = id if IsTrue(!IsEqual(clientOrderId, nil)) { params = this.Omit(params, []interface{}{"text", "clientOrderId"}) if IsTrue(!IsEqual(GetValue(clientOrderId, 0), "t")) { clientOrderId = Add("t-", clientOrderId) } orderId = clientOrderId } typeVarqueryVariable := this.HandleMarketTypeAndParams("fetchOrder", market, params); typeVar := GetValue(typeVarqueryVariable,0); query := GetValue(typeVarqueryVariable,1) var contract interface{} = IsTrue(IsTrue((IsEqual(typeVar, "swap"))) || IsTrue((IsEqual(typeVar, "future")))) || IsTrue((IsEqual(typeVar, "option"))) requestrequestParamsVariable := Ternary(IsTrue(contract), this.PrepareRequest(market, typeVar, query), this.SpotOrderPrepareRequest(market, trigger, query)); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) AddElementToObject(request, "order_id", ToString(orderId)) return []interface{}{request, requestParams} } /** * @method * @name gate#fetchOrder * @description Retrieves information on an order * @see https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order * @see https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-2 * @see https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-3 * @see https://www.gate.io/docs/developers/apiv4/en/#get-a-single-order-4 * @param {string} id Order id * @param {string} symbol Unified market symbol, *required for spot and margin* * @param {object} [params] Parameters specified by the exchange api * @param {bool} [params.trigger] True if the order being fetched is a trigger order * @param {string} [params.marginMode] 'cross' or 'isolated' - marginMode for margin trading if not provided this.options['defaultMarginMode'] is used * @param {string} [params.type] 'spot', 'swap', or 'future', if not provided this.options['defaultMarginMode'] is used * @param {string} [params.settle] 'btc' or 'usdt' - settle currency for perpetual swap and future - market settle currency is used if symbol !== undefined, default="usdt" for swap and "btc" for future * @param {bool} [params.unifiedAccount] set to true for fetching a unified account order * @returns An [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) 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 retRes49998 := (<-this.LoadMarkets()) PanicOnError(retRes49998) retRes50008 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes50008) var market interface{} = Ternary(IsTrue((IsEqual(symbol, nil))), nil, this.Market(symbol)) var result interface{} = this.HandleMarketTypeAndParams("fetchOrder", market, params) var typeVar interface{} = this.SafeString(result, 0) var trigger interface{} = this.SafeBoolN(params, []interface{}{"trigger", "is_stop_order", "stop"}, false) requestrequestParamsVariable := this.FetchOrderRequest(id, symbol, params); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) var response interface{} = nil if IsTrue(IsTrue(IsEqual(typeVar, "spot")) || IsTrue(IsEqual(typeVar, "margin"))) { if IsTrue(trigger) { response = (<-this.PrivateSpotGetPriceOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateSpotGetOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "swap")) { if IsTrue(trigger) { response = (<-this.PrivateFuturesGetSettlePriceOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateFuturesGetSettleOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "future")) { if IsTrue(trigger) { response = (<-this.PrivateDeliveryGetSettlePriceOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateDeliveryGetSettleOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.PrivateOptionsGetOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchOrder() not support this market type"))) } ch <- this.ParseOrder(response, market) return nil }() return ch } /** * @method * @name gate#fetchOpenOrders * @description fetch all unfilled currently open orders * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-open-orders * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-running-auto-order-list * @param {string} symbol unified market symbol * @param {int} [since] the earliest time in ms to fetch open orders for * @param {int} [limit] the maximum number of open orders structures to retrieve * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {bool} [params.trigger] true for fetching trigger orders * @param {string} [params.type] spot, margin, swap or future, if not provided this.options['defaultType'] is used * @param {string} [params.marginMode] 'cross' or 'isolated' - marginMode for type='margin', if not provided this.options['defaultMarginMode'] is used * @param {bool} [params.unifiedAccount] set to true for fetching unified account orders * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) 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 retRes505015 := (<-this.FetchOrdersByStatus("open", symbol, since, limit, params)) PanicOnError(retRes505015) ch <- retRes505015 return nil }() return ch } /** * @method * @name gate#fetchClosedOrders * @description fetches information on multiple closed orders made by the user * @see https://www.gate.io/docs/developers/apiv4/en/#list-orders * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-running-auto-order-list * @see https://www.gate.io/docs/developers/apiv4/en/#list-futures-orders * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-auto-orders * @see https://www.gate.io/docs/developers/apiv4/en/#list-futures-orders-2 * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-auto-orders-2 * @see https://www.gate.io/docs/developers/apiv4/en/#list-options-orders * @see https://www.gate.io/docs/developers/apiv4/en/#list-futures-orders-by-time-range * @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 {bool} [params.trigger] true for fetching trigger orders * @param {string} [params.type] spot, swap or future, if not provided this.options['defaultType'] is used * @param {string} [params.marginMode] 'cross' or 'isolated' - marginMode for margin trading if not provided this.options['defaultMarginMode'] is used * @param {boolean} [params.historical] *swap only* true for using historical endpoint * @param {bool} [params.unifiedAccount] set to true for fetching unified account orders * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) 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 retRes50778 := (<-this.LoadMarkets()) PanicOnError(retRes50778) retRes50788 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes50788) var until interface{} = this.SafeInteger(params, "until") var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) symbol = GetValue(market, "symbol") } var res interface{} = this.HandleMarketTypeAndParams("fetchClosedOrders", market, params) var typeVar interface{} = this.SafeString(res, 0) var useHistorical interface{} = false useHistoricalparamsVariable := this.HandleOptionAndParams(params, "fetchClosedOrders", "historical", false); useHistorical = GetValue(useHistoricalparamsVariable,0); params = GetValue(useHistoricalparamsVariable,1) if IsTrue(!IsTrue(useHistorical) && IsTrue((IsTrue((IsTrue(IsEqual(since, nil)) && IsTrue(IsEqual(until, nil)))) || IsTrue((!IsEqual(typeVar, "swap")))))) { retRes509019 := (<-this.FetchOrdersByStatus("finished", symbol, since, limit, params)) PanicOnError(retRes509019) ch <- retRes509019 return nil } params = this.Omit(params, "type") var request interface{} = map[string]interface{} {} requestparamsVariable := this.PrepareRequest(market, typeVar, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", this.ParseToInt(Divide(since, 1000))) } if IsTrue(!IsEqual(until, nil)) { params = this.Omit(params, "until") AddElementToObject(request, "to", this.ParseToInt(Divide(until, 1000))) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } response:= (<-this.PrivateFuturesGetSettleOrdersTimerange(this.Extend(request, params))) PanicOnError(response) ch <- this.ParseOrders(response, market, since, limit) return nil }() return ch } func (this *gate) PrepareOrdersByStatusRequest(status interface{}, optionalArgs ...interface{}) interface{} { 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 var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) symbol = GetValue(market, "symbol") } var trigger interface{} = nil triggerparamsVariable := this.HandleParamBool2(params, "trigger", "stop"); trigger = GetValue(triggerparamsVariable,0); params = GetValue(triggerparamsVariable,1) var typeVar interface{} = nil typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchOrdersByStatus", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var spot interface{} = IsTrue((IsEqual(typeVar, "spot"))) || IsTrue((IsEqual(typeVar, "margin"))) var request interface{} = map[string]interface{} {} requestparamsVariable := Ternary(IsTrue(spot), this.MultiOrderSpotPrepareRequest(market, trigger, params), this.PrepareRequest(market, typeVar, params)); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) if IsTrue(IsTrue(spot) && IsTrue(trigger)) { request = this.Omit(request, "account") } if IsTrue(IsEqual(status, "closed")) { status = "finished" } AddElementToObject(request, "status", status) if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } if IsTrue(spot) { if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", this.ParseToInt(Divide(since, 1000))) } var until interface{} = this.SafeInteger(params, "until") if IsTrue(!IsEqual(until, nil)) { params = this.Omit(params, "until") AddElementToObject(request, "to", this.ParseToInt(Divide(until, 1000))) } } lastIdfinalParamsVariable := this.HandleParamString2(params, "lastId", "last_id"); lastId := GetValue(lastIdfinalParamsVariable,0); finalParams := GetValue(lastIdfinalParamsVariable,1) if IsTrue(!IsEqual(lastId, nil)) { AddElementToObject(request, "last_id", lastId) } return []interface{}{request, finalParams} } func (this *gate) FetchOrdersByStatus(status 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 retRes51508 := (<-this.LoadMarkets()) PanicOnError(retRes51508) retRes51518 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes51518) var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) symbol = GetValue(market, "symbol") } // don't omit here, omits done in prepareOrdersByStatusRequest var trigger interface{} = this.SafeBool2(params, "trigger", "stop") var res interface{} = this.HandleMarketTypeAndParams("fetchOrdersByStatus", market, params) var typeVar interface{} = this.SafeString(res, 0) requestrequestParamsVariable := this.PrepareOrdersByStatusRequest(status, symbol, since, limit, params); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) var spot interface{} = IsTrue((IsEqual(typeVar, "spot"))) || IsTrue((IsEqual(typeVar, "margin"))) var openStatus interface{} = (IsEqual(status, "open")) var openSpotOrders interface{} = IsTrue(IsTrue(spot) && IsTrue(openStatus)) && !IsTrue(trigger) var response interface{} = nil if IsTrue(spot) { if !IsTrue(trigger) { if IsTrue(openStatus) { response = (<-this.PrivateSpotGetOpenOrders(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateSpotGetOrders(this.Extend(request, requestParams))) PanicOnError(response) } } else { response = (<-this.PrivateSpotGetPriceOrders(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "swap")) { if IsTrue(trigger) { response = (<-this.PrivateFuturesGetSettlePriceOrders(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateFuturesGetSettleOrders(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "future")) { if IsTrue(trigger) { response = (<-this.PrivateDeliveryGetSettlePriceOrders(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateDeliveryGetSettleOrders(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.PrivateOptionsGetOrders(this.Extend(request, requestParams))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchOrders() not support this market type"))) } // // spot open orders // // [ // { // "currency_pair": "ADA_USDT", // "total": 2, // "orders": [ // { // "id": "155498539874", // "text": "apiv4", // "create_time": "1652406843", // "update_time": "1652406843", // "create_time_ms": 1652406843295, // "update_time_ms": 1652406843295, // "status": "open", // "currency_pair": "ADA_USDT", // "type": "limit", // "account": "spot", // "side": "buy", // "amount": "3", // "price": "0.35", // "time_in_force": "gtc", // "iceberg": "0", // "left": "3", // "fill_price": "0", // "filled_total": "0", // "fee": "0", // "fee_currency": "ADA", // "point_fee": "0", // "gt_fee": "0", // "gt_discount": false, // "rebated_fee": "0", // "rebated_fee_currency": "USDT" // }, // ... // ] // }, // ... // ] // // spot // // [ // { // "id": "8834234273", // "text": "3", // "create_time": "1635406193", // "update_time": "1635406193", // "create_time_ms": 1635406193361, // "update_time_ms": 1635406193361, // "status": "closed", // "currency_pair": "BTC_USDT", // "type": "limit", // "account": "spot", // margin for margin orders // "side": "sell", // "amount": "0.0002", // "price": "58904.01", // "time_in_force": "gtc", // "iceberg": "0", // "left": "0.0000", // "fill_price": "11.790516", // "filled_total": "11.790516", // "fee": "0.023581032", // "fee_currency": "USDT", // "point_fee": "0", // "gt_fee": "0", // "gt_discount": false, // "rebated_fee_currency": "BTC" // } // ] // // spot trigger // // [ // { // "market": "ADA_USDT", // "user": 10406147, // "trigger": { // "price": "0.65", // "rule": "\u003c=", // "expiration": 86400 // }, // "put": { // "type": "limit", // "side": "sell", // "price": "0.65", // "amount": "2.00000000000000000000", // "account": "normal", // margin for margin orders // "time_in_force": "gtc" // }, // "id": 8449909, // "ctime": 1652188982, // "status": "open" // } // ] // // swap // // [ // { // "status": "finished", // "size": -1, // "left": 0, // "id": 82750739203, // "is_liq": false, // "is_close": false, // "contract": "BTC_USDT", // "text": "web", // "fill_price": "60721.3", // "finish_as": "filled", // "iceberg": 0, // "tif": "ioc", // "is_reduce_only": true, // "create_time": 1635403475.412, // "finish_time": 1635403475.4127, // "price": "0" // } // ] // // option // // [ // { // "id": 2593450699, // "contract": "BTC_USDT-20230601-27500-C", // "mkfr": "0.0003", // "tkfr": "0.0003", // "tif": "gtc", // "is_reduce_only": false, // "create_time": 1685503873, // "price": "200", // "size": 1, // "refr": "0", // "left": 1, // "text": "api", // "fill_price": "0", // "user": 5691076, // "status": "open", // "is_liq": false, // "refu": 0, // "is_close": false, // "iceberg": 0 // } // ] // var result interface{} = response if IsTrue(openSpotOrders) { result = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var ordersInner interface{} = this.SafeValue(GetValue(response, i), "orders") result = this.ArrayConcat(result, ordersInner) } } var orders interface{} = this.ParseOrders(result, market, since, limit) ch <- this.FilterBySymbolSinceLimit(orders, symbol, since, limit) return nil }() return ch } /** * @method * @name gate#cancelOrder * @description Cancels an open order * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order-2 * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order-3 * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-a-single-order-4 * @param {string} id Order id * @param {string} symbol Unified market symbol * @param {object} [params] Parameters specified by the exchange api * @param {bool} [params.trigger] True if the order to be cancelled is a trigger order * @param {bool} [params.unifiedAccount] set to true for canceling unified account orders * @returns An [order structure]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) 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 retRes53678 := (<-this.LoadMarkets()) PanicOnError(retRes53678) retRes53688 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes53688) var market interface{} = Ternary(IsTrue((IsEqual(symbol, nil))), nil, this.Market(symbol)) var trigger interface{} = this.SafeBoolN(params, []interface{}{"is_stop_order", "stop", "trigger"}, false) params = this.Omit(params, []interface{}{"is_stop_order", "stop", "trigger"}) typeVarqueryVariable := this.HandleMarketTypeAndParams("cancelOrder", market, params); typeVar := GetValue(typeVarqueryVariable,0); query := GetValue(typeVarqueryVariable,1) requestrequestParamsVariable := Ternary(IsTrue((IsTrue(IsEqual(typeVar, "spot")) || IsTrue(IsEqual(typeVar, "margin")))), this.SpotOrderPrepareRequest(market, trigger, query), this.PrepareRequest(market, typeVar, query)); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) AddElementToObject(request, "order_id", id) var response interface{} = nil if IsTrue(IsTrue(IsEqual(typeVar, "spot")) || IsTrue(IsEqual(typeVar, "margin"))) { if IsTrue(trigger) { response = (<-this.PrivateSpotDeletePriceOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateSpotDeleteOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "swap")) { if IsTrue(trigger) { response = (<-this.PrivateFuturesDeleteSettlePriceOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateFuturesDeleteSettleOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "future")) { if IsTrue(trigger) { response = (<-this.PrivateDeliveryDeleteSettlePriceOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateDeliveryDeleteSettleOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.PrivateOptionsDeleteOrdersOrderId(this.Extend(request, requestParams))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " cancelOrder() not support this market type"))) } // // spot // // { // "id": "95282841887", // "text": "apiv4", // "create_time": "1637383156", // "update_time": "1637383235", // "create_time_ms": 1637383156017, // "update_time_ms": 1637383235085, // "status": "cancelled", // "currency_pair": "ETH_USDT", // "type": "limit", // "account": "spot", // "side": "buy", // "amount": "0.01", // "price": "3500", // "time_in_force": "gtc", // "iceberg": "0", // "left": "0.01", // "fill_price": "0", // "filled_total": "0", // "fee": "0", // "fee_currency": "ETH", // "point_fee": "0", // "gt_fee": "0", // "gt_discount": false, // "rebated_fee": "0", // "rebated_fee_currency": "USDT" // } // // spot conditional // // { // "market": "ETH_USDT", // "user": 2436035, // "trigger": { // "price": "3500", // "rule": "\u003c=", // "expiration": 86400 // }, // "put": { // "type": "limit", // "side": "buy", // "price": "3500", // "amount": "0.01000000000000000000", // "account": "normal", // "time_in_force": "gtc" // }, // "id": 5891843, // "ctime": 1637382379, // "ftime": 1637382673, // "status": "canceled" // } // // swap, future and option // // { // "id": "82241928192", // "contract": "BTC_USDT", // "mkfr": "0", // "tkfr": "0.0005", // "tif": "gtc", // "is_reduce_only": false, // "create_time": "1635196145.06", // "finish_time": "1635196233.396", // "price": "61000", // "size": "4", // "refr": "0", // "left": "4", // "text": "web", // "fill_price": "0", // "user": "6693577", // "finish_as": "cancelled", // "status": "finished", // "is_liq": false, // "refu": "0", // "is_close": false, // "iceberg": "0", // } // ch <- this.ParseOrder(response, market) return nil }() return ch } /** * @method * @name gate#cancelOrders * @description cancel multiple orders * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-a-batch-of-orders-with-an-id-list * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-a-batch-of-orders-with-an-id-list-2 * @param {string[]} ids order ids * @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 {bool} [params.unifiedAccount] set to true for canceling unified account orders * @returns {object} an list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) 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 retRes54968 := (<-this.LoadMarkets()) PanicOnError(retRes54968) retRes54978 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes54978) var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) } var typeVar interface{} = nil var defaultSettle interface{} = Ternary(IsTrue((IsEqual(market, nil))), "usdt", GetValue(market, "settle")) var settle interface{} = this.SafeStringLower(params, "settle", defaultSettle) typeVarparamsVariable := this.HandleMarketTypeAndParams("cancelOrders", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) var isSpot interface{} = (IsEqual(typeVar, "spot")) if IsTrue(IsTrue(isSpot) && IsTrue((IsEqual(symbol, nil)))) { panic(ArgumentsRequired(Add(this.Id, " cancelOrders requires a symbol argument for spot markets"))) } if IsTrue(isSpot) { var ordersRequests interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(ids)); i++ { var id interface{} = GetValue(ids, i) var orderItem interface{} = map[string]interface{} { "id": id, "symbol": symbol, } AppendToArray(&ordersRequests,orderItem) } retRes552019 := (<-this.CancelOrdersForSymbols(ordersRequests, params)) PanicOnError(retRes552019) ch <- retRes552019 return nil } var request interface{} = map[string]interface{} { "settle": settle, } var finalList interface{} = []interface{}{request} // hacky but needs to be done here for i := 0; IsLessThan(i, GetArrayLength(ids)); i++ { AppendToArray(&finalList,GetValue(ids, i)) } response:= (<-this.PrivateFuturesPostSettleBatchCancelOrders(finalList)) PanicOnError(response) ch <- this.ParseOrders(response) return nil }() return ch } /** * @method * @name gate#cancelOrdersForSymbols * @description cancel multiple orders for multiple symbols * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-a-batch-of-orders-with-an-id-list * @param {CancellationRequest[]} orders list of order ids with symbol, example [{"id": "a", "symbol": "BTC/USDT"}, {"id": "b", "symbol": "ETH/USDT"}] * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string[]} [params.clientOrderIds] client order ids * @param {bool} [params.unifiedAccount] set to true for canceling unified account orders * @returns {object} an list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) CancelOrdersForSymbols(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 retRes55458 := (<-this.LoadMarkets()) PanicOnError(retRes55458) retRes55468 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes55468) var ordersRequests interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(orders)); i++ { var order interface{} = GetValue(orders, i) var symbol interface{} = this.SafeString(order, "symbol") var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "spot")) { panic(NotSupported(Add(this.Id, " cancelOrdersForSymbols() supports only spot markets"))) } var id interface{} = this.SafeString(order, "id") var orderItem interface{} = map[string]interface{} { "id": id, "currency_pair": GetValue(market, "id"), } AppendToArray(&ordersRequests,orderItem) } response:= (<-this.PrivateSpotPostCancelBatchOrders(ordersRequests)) PanicOnError(response) // // [ // { // "currency_pair": "BTC_USDT", // "id": "123456" // } // ] // ch <- this.ParseOrders(response) return nil }() return ch } /** * @method * @name gate#cancelAllOrders * @description cancel all open orders * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-in-specified-currency-pair * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-matched * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-matched-2 * @see https://www.gate.io/docs/developers/apiv4/en/#cancel-all-open-orders-matched-3 * @param {string} symbol unified market symbol, only orders in the market of this symbol are cancelled when symbol is not undefined * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {bool} [params.unifiedAccount] set to true for canceling unified account orders * @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure} */ func (this *gate) 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 retRes55888 := (<-this.LoadMarkets()) PanicOnError(retRes55888) retRes55898 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes55898) var market interface{} = Ternary(IsTrue((IsEqual(symbol, nil))), nil, this.Market(symbol)) var trigger interface{} = this.SafeBool2(params, "stop", "trigger") params = this.Omit(params, []interface{}{"stop", "trigger"}) typeVarqueryVariable := this.HandleMarketTypeAndParams("cancelAllOrders", market, params); typeVar := GetValue(typeVarqueryVariable,0); query := GetValue(typeVarqueryVariable,1) requestrequestParamsVariable := Ternary(IsTrue((IsEqual(typeVar, "spot"))), this.MultiOrderSpotPrepareRequest(market, trigger, query), this.PrepareRequest(market, typeVar, query)); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) var response interface{} = nil if IsTrue(IsTrue(IsEqual(typeVar, "spot")) || IsTrue(IsEqual(typeVar, "margin"))) { if IsTrue(trigger) { response = (<-this.PrivateSpotDeletePriceOrders(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateSpotDeleteOrders(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "swap")) { if IsTrue(trigger) { response = (<-this.PrivateFuturesDeleteSettlePriceOrders(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateFuturesDeleteSettleOrders(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "future")) { if IsTrue(trigger) { response = (<-this.PrivateDeliveryDeleteSettlePriceOrders(this.Extend(request, requestParams))) PanicOnError(response) } else { response = (<-this.PrivateDeliveryDeleteSettleOrders(this.Extend(request, requestParams))) PanicOnError(response) } } else if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.PrivateOptionsDeleteOrders(this.Extend(request, requestParams))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " cancelAllOrders() not support this market type"))) } // // [ // { // "id": 139797004085, // "contract": "ADA_USDT", // "mkfr": "0", // "tkfr": "0.0005", // "tif": "gtc", // "is_reduce_only": false, // "create_time": 1647911169.343, // "finish_time": 1647911226.849, // "price": "0.8", // "size": 1, // "refr": "0.3", // "left": 1, // "text": "api", // "fill_price": "0", // "user": 6693577, // "finish_as": "cancelled", // "status": "finished", // "is_liq": false, // "refu": 2436035, // "is_close": false, // "iceberg": 0 // } // ... // ] // ch <- this.ParseOrders(response, market) return nil }() return ch } /** * @method * @name gate#transfer * @description transfer currency internally between wallets on the same account * @see https://www.gate.io/docs/developers/apiv4/en/#transfer-between-trading-accounts * @param {string} code unified currency code for currency being transferred * @param {float} amount the amount of currency to transfer * @param {string} fromAccount the account to transfer currency from * @param {string} toAccount the account to transfer currency to * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.symbol] Unified market symbol *required for type == margin* * @returns A [transfer structure]{@link https://docs.ccxt.com/#/?id=transfer-structure} */ func (this *gate) 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 retRes56648 := (<-this.LoadMarkets()) PanicOnError(retRes56648) var currency interface{} = this.Currency(code) var fromId interface{} = this.ConvertTypeToAccount(fromAccount) var toId interface{} = this.ConvertTypeToAccount(toAccount) var truncated interface{} = this.CurrencyToPrecision(code, amount) var request interface{} = map[string]interface{} { "currency": GetValue(currency, "id"), "amount": truncated, } if !IsTrue((InOp(GetValue(this.Options, "accountsByType"), fromId))) { AddElementToObject(request, "from", "margin") AddElementToObject(request, "currency_pair", fromId) } else { AddElementToObject(request, "from", fromId) } if !IsTrue((InOp(GetValue(this.Options, "accountsByType"), toId))) { AddElementToObject(request, "to", "margin") AddElementToObject(request, "currency_pair", toId) } else { AddElementToObject(request, "to", toId) } if IsTrue(IsTrue(IsEqual(fromId, "margin")) || IsTrue(IsEqual(toId, "margin"))) { var symbol interface{} = this.SafeString2(params, "symbol", "currency_pair") if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " transfer requires params[\"symbol\"] for isolated margin transfers"))) } var market interface{} = this.Market(symbol) AddElementToObject(request, "currency_pair", GetValue(market, "id")) params = this.Omit(params, "symbol") } if IsTrue(IsTrue(IsTrue(IsTrue((IsEqual(toId, "futures"))) || IsTrue((IsEqual(toId, "delivery")))) || IsTrue((IsEqual(fromId, "futures")))) || IsTrue((IsEqual(fromId, "delivery")))) { AddElementToObject(request, "settle", GetValue(currency, "id")) // todo: currencies have network-junctions } response:= (<-this.PrivateWalletPostTransfers(this.Extend(request, params))) PanicOnError(response) // // according to the docs (however actual response seems to be an empty string '') // // { // "currency": "BTC", // "from": "spot", // "to": "margin", // "amount": "1", // "currency_pair": "BTC_USDT" // } // ch <- this.ParseTransfer(response, currency) return nil }() return ch } func (this *gate) ParseTransfer(transfer interface{}, optionalArgs ...interface{}) interface{} { // // { // "currency": "BTC", // "from": "spot", // "to": "margin", // "amount": "1", // "currency_pair": "BTC_USDT" // } // currency := GetArg(optionalArgs, 0, nil) _ = currency return map[string]interface{} { "id": this.SafeString(transfer, "tx_id"), "timestamp": nil, "datetime": nil, "currency": this.SafeCurrencyCode(nil, currency), "amount": nil, "fromAccount": nil, "toAccount": nil, "status": nil, "info": transfer, } } /** * @method * @name gate#setLeverage * @description set the level of leverage for a market * @see https://www.gate.io/docs/developers/apiv4/en/#update-position-leverage * @see https://www.gate.io/docs/developers/apiv4/en/#update-position-leverage-2 * @param {float} leverage the rate of leverage * @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 *gate) 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, 0))) || IsTrue((IsGreaterThan(leverage, 100)))) { panic(BadRequest(Add(this.Id, " setLeverage() leverage should be between 1 and 100"))) } retRes57558 := (<-this.LoadMarkets()) PanicOnError(retRes57558) var market interface{} = this.Market(symbol) requestqueryVariable := this.PrepareRequest(market, nil, params); request := GetValue(requestqueryVariable,0); query := GetValue(requestqueryVariable,1) var defaultMarginMode interface{} = this.SafeString2(this.Options, "marginMode", "defaultMarginMode") var crossLeverageLimit interface{} = this.SafeString(query, "cross_leverage_limit") var marginMode interface{} = this.SafeString(query, "marginMode", defaultMarginMode) var stringifiedMargin interface{} = this.NumberToString(leverage) if IsTrue(!IsEqual(crossLeverageLimit, nil)) { marginMode = "cross" stringifiedMargin = crossLeverageLimit } if IsTrue(IsTrue(IsEqual(marginMode, "cross")) || IsTrue(IsEqual(marginMode, "cross_margin"))) { AddElementToObject(request, "cross_leverage_limit", stringifiedMargin) AddElementToObject(request, "leverage", "0") } else { AddElementToObject(request, "leverage", stringifiedMargin) } var response interface{} = nil if IsTrue(GetValue(market, "swap")) { response = (<-this.PrivateFuturesPostSettlePositionsContractLeverage(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "future")) { response = (<-this.PrivateDeliveryPostSettlePositionsContractLeverage(this.Extend(request, query))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " setLeverage() not support this market type"))) } // // { // "value": "0", // "leverage": "5", // "mode": "single", // "realised_point": "0", // "contract": "BTC_USDT", // "entry_price": "0", // "mark_price": "62035.86", // "history_point": "0", // "realised_pnl": "0", // "close_order": null, // "size": 0, // "cross_leverage_limit": "0", // "pending_orders": 0, // "adl_ranking": 6, // "maintenance_rate": "0.005", // "unrealised_pnl": "0", // "user": 2436035, // "leverage_max": "100", // "history_pnl": "0", // "risk_limit": "1000000", // "margin": "0", // "last_close_pnl": "0", // "liq_price": "0" // } // ch <- response return nil }() return ch } func (this *gate) ParsePosition(position interface{}, optionalArgs ...interface{}) interface{} { // // swap and future // // { // "value": "4.60516", // "leverage": "0", // "mode": "single", // "realised_point": "0", // "contract": "BTC_USDT", // "entry_price": "46030.3", // "mark_price": "46051.6", // "history_point": "0", // "realised_pnl": "-0.002301515", // "close_order": null, // "size": 1, // "cross_leverage_limit": "0", // "pending_orders": 0, // "adl_ranking": 5, // "maintenance_rate": "0.004", // "unrealised_pnl": "0.00213", // "user": 5691076, // "leverage_max": "125", // "history_pnl": "0", // "risk_limit": "1000000", // "margin": "8.997698485", // "last_close_pnl": "0", // "liq_price": "0", // "update_time": 1705034246, // "update_id": 1, // "initial_margin": "0", // "maintenance_margin": "0", // "open_time": 1705034246, // "trade_max_size": "0" // } // // option // // { // "close_order": null, // "size": 1, // "vega": "5.29756", // "theta": "-98.98917", // "gamma": "0.00056", // "delta": "0.68691", // "contract": "BTC_USDT-20230602-26500-C", // "entry_price": "529", // "unrealised_pnl": "-1.0131", // "user": 5691076, // "mark_price": "427.69", // "underlying_price": "26810.2", // "underlying": "BTC_USDT", // "realised_pnl": "-0.08042877", // "mark_iv": "0.4224", // "pending_orders": 0 // } // // fetchPositionsHistory (swap and future) // // { // "contract": "SLERF_USDT", // Futures contract // "text": "web", // Text of close order // "long_price": "0.766306", // When 'side' is 'long,' it indicates the opening average price; when 'side' is 'short,' it indicates the closing average price. // "pnl": "-23.41702352", // PNL // "pnl_pnl": "-22.7187", // Position P/L // "pnl_fee": "-0.06527125", // Transaction Fees // "pnl_fund": "-0.63305227", // Funding Fees // "accum_size": "100", // "time": 1711279263, // Position close time // "short_price": "0.539119", // When 'side' is 'long,' it indicates the opening average price; when 'side' is 'short,' it indicates the closing average price // "side": "long", // Position side, long or short // "max_size": "100", // Max Trade Size // "first_open_time": 1711037985 // First Open Time // } // market := GetArg(optionalArgs, 0, nil) _ = market var contract interface{} = this.SafeString(position, "contract") market = this.SafeMarket(contract, market, "_", "contract") var size interface{} = this.SafeString2(position, "size", "accum_size") var side interface{} = this.SafeString(position, "side") if IsTrue(IsEqual(side, nil)) { if IsTrue(Precise.StringGt(size, "0")) { side = "long" } else if IsTrue(Precise.StringLt(size, "0")) { side = "short" } } var maintenanceRate interface{} = this.SafeString(position, "maintenance_rate") var notional interface{} = this.SafeString(position, "value") var leverage interface{} = this.SafeString(position, "leverage") var marginMode interface{} = nil if IsTrue(!IsEqual(leverage, nil)) { if IsTrue(IsEqual(leverage, "0")) { marginMode = "cross" } else { marginMode = "isolated" } } // Initial Position Margin = ( Position Value / Leverage ) + Close Position Fee // *The default leverage under the full position is the highest leverage in the market. // *Trading fee is charged as Taker Fee Rate (0.075%). var feePaid interface{} = this.SafeString(position, "pnl_fee") var initialMarginString interface{} = nil if IsTrue(IsEqual(feePaid, nil)) { var takerFee interface{} = "0.00075" feePaid = Precise.StringMul(takerFee, notional) initialMarginString = Precise.StringAdd(Precise.StringDiv(notional, leverage), feePaid) } var timestamp interface{} = this.SafeTimestamp2(position, "open_time", "first_open_time") if IsTrue(IsEqual(timestamp, 0)) { timestamp = nil } return this.SafePosition(map[string]interface{} { "info": position, "id": nil, "symbol": this.SafeString(market, "symbol"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "lastUpdateTimestamp": this.SafeTimestamp2(position, "update_time", "time"), "initialMargin": this.ParseNumber(initialMarginString), "initialMarginPercentage": this.ParseNumber(Precise.StringDiv(initialMarginString, notional)), "maintenanceMargin": this.ParseNumber(Precise.StringMul(maintenanceRate, notional)), "maintenanceMarginPercentage": this.ParseNumber(maintenanceRate), "entryPrice": this.SafeNumber(position, "entry_price"), "notional": this.ParseNumber(notional), "leverage": this.SafeNumber(position, "leverage"), "unrealizedPnl": this.SafeNumber(position, "unrealised_pnl"), "realizedPnl": this.SafeNumber2(position, "realised_pnl", "pnl"), "contracts": this.ParseNumber(Precise.StringAbs(size)), "contractSize": this.SafeNumber(market, "contractSize"), "marginRatio": nil, "liquidationPrice": this.SafeNumber(position, "liq_price"), "markPrice": this.SafeNumber(position, "mark_price"), "lastPrice": nil, "collateral": this.SafeNumber(position, "margin"), "marginMode": marginMode, "side": side, "percentage": nil, "stopLossPrice": nil, "takeProfitPrice": nil, }) } /** * @method * @name gate#fetchPosition * @description fetch data on an open contract position * @see https://www.gate.io/docs/developers/apiv4/en/#get-single-position * @see https://www.gate.io/docs/developers/apiv4/en/#get-single-position-2 * @see https://www.gate.io/docs/developers/apiv4/en/#get-specified-contract-position * @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 *gate) 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 retRes59648 := (<-this.LoadMarkets()) PanicOnError(retRes59648) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "contract")) { panic(BadRequest(Add(this.Id, " fetchPosition() supports contract markets only"))) } var request interface{} = map[string]interface{} {} requestparamsVariable := this.PrepareRequest(market, GetValue(market, "type"), params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) var extendedRequest interface{} = this.Extend(request, params) var response interface{} = nil if IsTrue(GetValue(market, "swap")) { response = (<-this.PrivateFuturesGetSettlePositionsContract(extendedRequest)) PanicOnError(response) } else if IsTrue(GetValue(market, "future")) { response = (<-this.PrivateDeliveryGetSettlePositionsContract(extendedRequest)) PanicOnError(response) } else if IsTrue(IsEqual(GetValue(market, "type"), "option")) { response = (<-this.PrivateOptionsGetPositionsContract(extendedRequest)) PanicOnError(response) } // // swap and future // // { // "value": "4.60516", // "leverage": "0", // "mode": "single", // "realised_point": "0", // "contract": "BTC_USDT", // "entry_price": "46030.3", // "mark_price": "46051.6", // "history_point": "0", // "realised_pnl": "-0.002301515", // "close_order": null, // "size": 1, // "cross_leverage_limit": "0", // "pending_orders": 0, // "adl_ranking": 5, // "maintenance_rate": "0.004", // "unrealised_pnl": "0.00213", // "user": 5691076, // "leverage_max": "125", // "history_pnl": "0", // "risk_limit": "1000000", // "margin": "8.997698485", // "last_close_pnl": "0", // "liq_price": "0", // "update_time": 1705034246, // "update_id": 1, // "initial_margin": "0", // "maintenance_margin": "0", // "open_time": 1705034246, // "trade_max_size": "0" // } // // option // // { // "close_order": null, // "size": 1, // "vega": "5.29756", // "theta": "-98.98917", // "gamma": "0.00056", // "delta": "0.68691", // "contract": "BTC_USDT-20230602-26500-C", // "entry_price": "529", // "unrealised_pnl": "-1.0131", // "user": 5691076, // "mark_price": "427.69", // "underlying_price": "26810.2", // "underlying": "BTC_USDT", // "realised_pnl": "-0.08042877", // "mark_iv": "0.4224", // "pending_orders": 0 // } // ch <- this.ParsePosition(response, market) return nil }() return ch } /** * @method * @name gate#fetchPositions * @description fetch all open positions * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-positions-of-a-user * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-positions-of-a-user-2 * @see https://www.gate.io/docs/developers/apiv4/en/#list-user-s-positions-of-specified-underlying * @param {string[]|undefined} symbols Not used by gate, but parsed internally by CCXT * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.settle] 'btc' or 'usdt' - settle currency for perpetual swap and future - default="usdt" for swap and "btc" for future * @param {string} [params.type] swap, future or option, if not provided this.options['defaultType'] is used * @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/#/?id=position-structure} */ func (this *gate) 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 retRes60538 := (<-this.LoadMarkets()) PanicOnError(retRes60538) var market interface{} = nil symbols = this.MarketSymbols(symbols, nil, true, true, true) if IsTrue(!IsEqual(symbols, nil)) { var symbolsLength interface{} = GetArrayLength(symbols) if IsTrue(IsGreaterThan(symbolsLength, 0)) { market = this.Market(GetValue(symbols, 0)) } } var typeVar interface{} = nil var request interface{} = map[string]interface{} {} typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchPositions", market, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) if IsTrue(IsTrue((IsEqual(typeVar, nil))) || IsTrue((IsEqual(typeVar, "spot")))) { typeVar = "swap" // default to swap } if IsTrue(IsEqual(typeVar, "option")) { if IsTrue(!IsEqual(symbols, nil)) { var marketId interface{} = GetValue(market, "id") var optionParts interface{} = Split(marketId, "-") AddElementToObject(request, "underlying", this.SafeString(optionParts, 0)) } } else { requestparamsVariable := this.PrepareRequest(nil, typeVar, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) } var response interface{} = nil if IsTrue(IsEqual(typeVar, "swap")) { response = (<-this.PrivateFuturesGetSettlePositions(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "future")) { response = (<-this.PrivateDeliveryGetSettlePositions(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.PrivateOptionsGetPositions(this.Extend(request, params))) PanicOnError(response) } // // swap and future // // [ // { // "value": "4.602828", // "leverage": "0", // "mode": "single", // "realised_point": "0", // "contract": "BTC_USDT", // "entry_price": "46030.3", // "mark_price": "46028.28", // "history_point": "0", // "realised_pnl": "-0.002301515", // "close_order": null, // "size": 1, // "cross_leverage_limit": "0", // "pending_orders": 0, // "adl_ranking": 5, // "maintenance_rate": "0.004", // "unrealised_pnl": "-0.000202", // "user": 5691076, // "leverage_max": "125", // "history_pnl": "0", // "risk_limit": "1000000", // "margin": "8.997698485", // "last_close_pnl": "0", // "liq_price": "0", // "update_time": 1705034246, // "update_id": 1, // "initial_margin": "0", // "maintenance_margin": "0", // "open_time": 1705034246, // "trade_max_size": "0" // } // ] // // option // // [ // { // "close_order": null, // "size": 0, // "vega": "0.01907", // "theta": "-3.04888", // "gamma": "0.00001", // "delta": "0.0011", // "contract": "BTC_USDT-20230601-27500-C", // "entry_price": "0", // "unrealised_pnl": "0", // "user": 5691076, // "mark_price": "0.07", // "underlying_price": "26817.27", // "underlying": "BTC_USDT", // "realised_pnl": "0", // "mark_iv": "0.4339", // "pending_orders": 0 // } // ] // ch <- this.ParsePositions(response, symbols) return nil }() return ch } /** * @method * @name gate#fetchLeverageTiers * @description retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-futures-contracts-2 * @param {string[]} [symbols] list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a dictionary of [leverage tiers structures]{@link https://docs.ccxt.com/#/?id=leverage-tiers-structure}, indexed by market symbols */ func (this *gate) 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 retRes61598 := (<-this.LoadMarkets()) PanicOnError(retRes61598) typeVarqueryVariable := this.HandleMarketTypeAndParams("fetchLeverageTiers", nil, params); typeVar := GetValue(typeVarqueryVariable,0); query := GetValue(typeVarqueryVariable,1) requestrequestParamsVariable := this.PrepareRequest(nil, typeVar, query); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) if IsTrue(IsTrue(!IsEqual(typeVar, "future")) && IsTrue(!IsEqual(typeVar, "swap"))) { panic(BadRequest(Add(this.Id, " fetchLeverageTiers only supports swap and future"))) } var response interface{} = nil if IsTrue(IsEqual(typeVar, "swap")) { response = (<-this.PublicFuturesGetSettleContracts(this.Extend(request, requestParams))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "future")) { response = (<-this.PublicDeliveryGetSettleContracts(this.Extend(request, requestParams))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " fetchLeverageTiers() not support this market type"))) } // // Perpetual swap // // [ // { // "name": "BTC_USDT", // "type": "direct", // "quanto_multiplier": "0.0001", // "ref_discount_rate": "0", // "order_price_deviate": "0.5", // "maintenance_rate": "0.005", // "mark_type": "index", // "last_price": "38026", // "mark_price": "37985.6", // "index_price": "37954.92", // "funding_rate_indicative": "0.000219", // "mark_price_round": "0.01", // "funding_offset": 0, // "in_delisting": false, // "risk_limit_base": "1000000", // "interest_rate": "0.0003", // "order_price_round": "0.1", // "order_size_min": 1, // "ref_rebate_rate": "0.2", // "funding_interval": 28800, // "risk_limit_step": "1000000", // "leverage_min": "1", // "leverage_max": "100", // "risk_limit_max": "8000000", // "maker_fee_rate": "-0.00025", // "taker_fee_rate": "0.00075", // "funding_rate": "0.002053", // "order_size_max": 1000000, // "funding_next_apply": 1610035200, // "short_users": 977, // "config_change_time": 1609899548, // "trade_size": 28530850594, // "position_size": 5223816, // "long_users": 455, // "funding_impact_value": "60000", // "orders_limit": 50, // "trade_id": 10851092, // "orderbook_id": 2129638396 // } // ] // // Delivery Futures // // [ // { // "name": "BTC_USDT_20200814", // "underlying": "BTC_USDT", // "cycle": "WEEKLY", // "type": "direct", // "quanto_multiplier": "0.0001", // "mark_type": "index", // "last_price": "9017", // "mark_price": "9019", // "index_price": "9005.3", // "basis_rate": "0.185095", // "basis_value": "13.7", // "basis_impact_value": "100000", // "settle_price": "0", // "settle_price_interval": 60, // "settle_price_duration": 1800, // "settle_fee_rate": "0.0015", // "expire_time": 1593763200, // "order_price_round": "0.1", // "mark_price_round": "0.1", // "leverage_min": "1", // "leverage_max": "100", // "maintenance_rate": "1000000", // "risk_limit_base": "140.726652109199", // "risk_limit_step": "1000000", // "risk_limit_max": "8000000", // "maker_fee_rate": "-0.00025", // "taker_fee_rate": "0.00075", // "ref_discount_rate": "0", // "ref_rebate_rate": "0.2", // "order_price_deviate": "0.5", // "order_size_min": 1, // "order_size_max": 1000000, // "orders_limit": 50, // "orderbook_id": 63, // "trade_id": 26, // "trade_size": 435, // "position_size": 130, // "config_change_time": 1593158867, // "in_delisting": false // } // ] // ch <- this.ParseLeverageTiers(response, symbols, "name") return nil }() return ch } /** * @method * @name gate#fetchMarketLeverageTiers * @description retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market * @see https://www.gate.io/docs/developers/apiv4/en/#list-risk-limit-tiers * @param {string} symbol unified market symbol * @param {object} [params] extra parameters specific to the exchange API endpoint * @returns {object} a [leverage tiers structure]{@link https://docs.ccxt.com/#/?id=leverage-tiers-structure} */ func (this *gate) FetchMarketLeverageTiers(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 retRes62788 := (<-this.LoadMarkets()) PanicOnError(retRes62788) var market interface{} = this.Market(symbol) typeVarqueryVariable := this.HandleMarketTypeAndParams("fetchMarketLeverageTiers", market, params); typeVar := GetValue(typeVarqueryVariable,0); query := GetValue(typeVarqueryVariable,1) requestrequestParamsVariable := this.PrepareRequest(market, typeVar, query); request := GetValue(requestrequestParamsVariable,0); requestParams := GetValue(requestrequestParamsVariable,1) if IsTrue(IsTrue(!IsEqual(typeVar, "future")) && IsTrue(!IsEqual(typeVar, "swap"))) { panic(BadRequest(Add(this.Id, " fetchMarketLeverageTiers only supports swap and future"))) } response:= (<-this.PrivateFuturesGetSettleRiskLimitTiers(this.Extend(request, requestParams))) PanicOnError(response) // // [ // { // "maintenance_rate": "0.004", // "tier": 1, // "initial_rate": "0.008", // "leverage_max": "125", // "risk_limit": "1000000" // } // ] // ch <- this.ParseMarketLeverageTiers(response, market) return nil }() return ch } func (this *gate) ParseEmulatedLeverageTiers(info interface{}, optionalArgs ...interface{}) interface{} { market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(info, "name") var maintenanceMarginUnit interface{} = this.SafeString(info, "maintenance_rate") // '0.005', var leverageMax interface{} = this.SafeString(info, "leverage_max") // '100', var riskLimitStep interface{} = this.SafeString(info, "risk_limit_step") // '1000000', var riskLimitMax interface{} = this.SafeString(info, "risk_limit_max") // '16000000', var initialMarginUnit interface{} = Precise.StringDiv("1", leverageMax) var maintenanceMarginRate interface{} = maintenanceMarginUnit var initialMarginRatio interface{} = initialMarginUnit var floor interface{} = "0" var tiers interface{} = []interface{}{} for Precise.StringLt(floor, riskLimitMax) { var cap interface{} = Precise.StringAdd(floor, riskLimitStep) AppendToArray(&tiers,map[string]interface{} { "tier": this.ParseNumber(Precise.StringDiv(cap, riskLimitStep)), "symbol": this.SafeSymbol(marketId, market, nil, "contract"), "currency": this.SafeString(market, "settle"), "minNotional": this.ParseNumber(floor), "maxNotional": this.ParseNumber(cap), "maintenanceMarginRate": this.ParseNumber(maintenanceMarginRate), "maxLeverage": this.ParseNumber(Precise.StringDiv("1", initialMarginRatio)), "info": info, }) maintenanceMarginRate = Precise.StringAdd(maintenanceMarginRate, maintenanceMarginUnit) initialMarginRatio = Precise.StringAdd(initialMarginRatio, initialMarginUnit) floor = cap } return tiers } func (this *gate) ParseMarketLeverageTiers(info interface{}, optionalArgs ...interface{}) interface{} { // // [ // { // "maintenance_rate": "0.004", // "tier": 1, // "initial_rate": "0.008", // "leverage_max": "125", // "risk_limit": "1000000" // } // ] // market := GetArg(optionalArgs, 0, nil) _ = market if !IsTrue(IsArray(info)) { return this.ParseEmulatedLeverageTiers(info, market) } var minNotional interface{} = 0 var tiers interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(info)); i++ { var item interface{} = GetValue(info, i) var maxNotional interface{} = this.SafeNumber(item, "risk_limit") AppendToArray(&tiers,map[string]interface{} { "tier": this.Sum(i, 1), "symbol": GetValue(market, "symbol"), "currency": GetValue(market, "base"), "minNotional": minNotional, "maxNotional": maxNotional, "maintenanceMarginRate": this.SafeNumber(item, "maintenance_rate"), "maxLeverage": this.SafeNumber(item, "leverage_max"), "info": item, }) minNotional = maxNotional } return tiers } /** * @method * @name gate#repayMargin * @description repay borrowed margin and interest * @see https://www.gate.io/docs/apiv4/en/#repay-a-loan * @param {string} symbol unified market symbol * @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 {string} [params.mode] 'all' or 'partial' payment mode, extra parameter required for isolated margin * @param {string} [params.id] '34267567' loan id, extra parameter required for isolated margin * @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/#/?id=margin-loan-structure} */ func (this *gate) 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 retRes63798 := (<-this.LoadMarkets()) PanicOnError(retRes63798) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "currency": ToUpper(GetValue(currency, "id")), "amount": this.CurrencyToPrecision(code, amount), } var market interface{} = this.Market(symbol) AddElementToObject(request, "currency_pair", GetValue(market, "id")) AddElementToObject(request, "type", "repay") response:= (<-this.PrivateMarginPostUniLoans(this.Extend(request, params))) PanicOnError(response) // // empty response // ch <- this.ParseMarginLoan(response, currency) return nil }() return ch } /** * @method * @name gate#repayCrossMargin * @description repay cross margin borrowed margin and interest * @see https://www.gate.io/docs/developers/apiv4/en/#cross-margin-repayments * @see https://www.gate.io/docs/developers/apiv4/en/#borrow-or-repay * @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 {string} [params.mode] 'all' or 'partial' payment mode, extra parameter required for isolated margin * @param {string} [params.id] '34267567' loan id, extra parameter required for isolated margin * @param {boolean} [params.unifiedAccount] set to true for repaying in the unified account * @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/#/?id=margin-loan-structure} */ func (this *gate) 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 retRes64108 := (<-this.LoadMarkets()) PanicOnError(retRes64108) retRes64118 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes64118) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "currency": ToUpper(GetValue(currency, "id")), "amount": this.CurrencyToPrecision(code, amount), } var isUnifiedAccount interface{} = false isUnifiedAccountparamsVariable := this.HandleOptionAndParams(params, "repayCrossMargin", "unifiedAccount"); isUnifiedAccount = GetValue(isUnifiedAccountparamsVariable,0); params = GetValue(isUnifiedAccountparamsVariable,1) var response interface{} = nil if IsTrue(isUnifiedAccount) { AddElementToObject(request, "type", "repay") response = (<-this.PrivateUnifiedPostLoans(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PrivateMarginPostCrossRepayments(this.Extend(request, params))) PanicOnError(response) response = this.SafeDict(response, 0) } ch <- this.ParseMarginLoan(response, currency) return nil }() return ch } /** * @method * @name gate#borrowIsolatedMargin * @description create a loan to borrow margin * @see https://www.gate.io/docs/developers/apiv4/en/#marginuni * @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 * @param {string} [params.rate] '0.0002' or '0.002' extra parameter required for isolated margin * @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/#/?id=margin-loan-structure} */ func (this *gate) 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 retRes64598 := (<-this.LoadMarkets()) PanicOnError(retRes64598) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "currency": ToUpper(GetValue(currency, "id")), "amount": this.CurrencyToPrecision(code, amount), } var response interface{} = nil var market interface{} = this.Market(symbol) AddElementToObject(request, "currency_pair", GetValue(market, "id")) AddElementToObject(request, "type", "borrow") response = (<-this.PrivateMarginPostUniLoans(this.Extend(request, params))) PanicOnError(response) // // { // "id": "34267567", // "create_time": "1656394778", // "expire_time": "1657258778", // "status": "loaned", // "side": "borrow", // "currency": "USDT", // "rate": "0.0002", // "amount": "100", // "days": 10, // "auto_renew": false, // "currency_pair": "LTC_USDT", // "left": "0", // "repaid": "0", // "paid_interest": "0", // "unpaid_interest": "0.003333333333" // } // ch <- this.ParseMarginLoan(response, currency) return nil }() return ch } /** * @method * @name gate#borrowMargin * @description create a loan to borrow margin * @see https://www.gate.io/docs/apiv4/en/#create-a-cross-margin-borrow-loan * @see https://www.gate.io/docs/developers/apiv4/en/#borrow-or-repay * @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 {string} [params.rate] '0.0002' or '0.002' extra parameter required for isolated margin * @param {boolean} [params.unifiedAccount] set to true for borrowing in the unified account * @returns {object} a [margin loan structure]{@link https://docs.ccxt.com/#/?id=margin-loan-structure} */ func (this *gate) 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 retRes65068 := (<-this.LoadMarkets()) PanicOnError(retRes65068) retRes65078 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes65078) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "currency": ToUpper(GetValue(currency, "id")), "amount": this.CurrencyToPrecision(code, amount), } var isUnifiedAccount interface{} = false isUnifiedAccountparamsVariable := this.HandleOptionAndParams(params, "borrowCrossMargin", "unifiedAccount"); isUnifiedAccount = GetValue(isUnifiedAccountparamsVariable,0); params = GetValue(isUnifiedAccountparamsVariable,1) var response interface{} = nil if IsTrue(isUnifiedAccount) { AddElementToObject(request, "type", "borrow") response = (<-this.PrivateUnifiedPostLoans(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PrivateMarginPostCrossLoans(this.Extend(request, params))) PanicOnError(response) } ch <- this.ParseMarginLoan(response, currency) return nil }() return ch } func (this *gate) ParseMarginLoan(info interface{}, optionalArgs ...interface{}) interface{} { // // Cross // // { // "id": "17", // "create_time": 1620381696159, // "update_time": 1620381696159, // "currency": "EOS", // "amount": "110.553635", // "text": "web", // "status": 2, // "repaid": "110.506649705159", // "repaid_interest": "0.046985294841", // "unpaid_interest": "0.0000074393366667" // } // // Isolated // // { // "id": "34267567", // "create_time": "1656394778", // "expire_time": "1657258778", // "status": "loaned", // "side": "borrow", // "currency": "USDT", // "rate": "0.0002", // "amount": "100", // "days": 10, // "auto_renew": false, // "currency_pair": "LTC_USDT", // "left": "0", // "repaid": "0", // "paid_interest": "0", // "unpaid_interest": "0.003333333333" // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var marginMode interface{} = this.SafeString2(this.Options, "defaultMarginMode", "marginMode", "cross") var timestamp interface{} = this.SafeInteger(info, "create_time") if IsTrue(IsEqual(marginMode, "isolated")) { timestamp = this.SafeTimestamp(info, "create_time") } var currencyId interface{} = this.SafeString(info, "currency") var marketId interface{} = this.SafeString(info, "currency_pair") return map[string]interface{} { "id": this.SafeInteger(info, "id"), "currency": this.SafeCurrencyCode(currencyId, currency), "amount": this.SafeNumber(info, "amount"), "symbol": this.SafeSymbol(marketId, nil, "_", "margin"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "info": info, } } /** * @method * @name gate#fetchBorrowInterest * @description fetch the interest owed by the user for borrowing currency for margin trading * @see https://www.gate.io/docs/developers/apiv4/en/#list-interest-records * @see https://www.gate.io/docs/developers/apiv4/en/#interest-records-for-the-cross-margin-account * @see https://www.gate.io/docs/developers/apiv4/en/#list-interest-records-2 * @param {string} [code] unified currency code * @param {string} [symbol] unified market symbol when fetching interest in isolated markets * @param {int} [since] the earliest time in ms to fetch borrow 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.unifiedAccount] set to true for fetching borrow interest in the unified account * @returns {object[]} a list of [borrow interest structures]{@link https://docs.ccxt.com/#/?id=borrow-interest-structure} */ func (this *gate) 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 retRes66108 := (<-this.LoadMarkets()) PanicOnError(retRes66108) retRes66118 := (<-this.LoadUnifiedStatus()) PanicOnError(retRes66118) var isUnifiedAccount interface{} = false isUnifiedAccountparamsVariable := this.HandleOptionAndParams(params, "fetchBorrowInterest", "unifiedAccount"); isUnifiedAccount = GetValue(isUnifiedAccountparamsVariable,0); params = GetValue(isUnifiedAccountparamsVariable,1) var request interface{} = map[string]interface{} {} requestparamsVariable := this.HandleUntilOption("to", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) var currency interface{} = nil if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) AddElementToObject(request, "currency", GetValue(currency, "id")) } var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { market = this.Market(symbol) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } var response interface{} = nil var marginMode interface{} = nil marginModeparamsVariable := this.HandleMarginModeAndParams("fetchBorrowInterest", params, "cross"); marginMode = GetValue(marginModeparamsVariable,0); params = GetValue(marginModeparamsVariable,1) if IsTrue(isUnifiedAccount) { response = (<-this.PrivateUnifiedGetInterestRecords(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(marginMode, "isolated")) { if IsTrue(!IsEqual(market, nil)) { AddElementToObject(request, "currency_pair", GetValue(market, "id")) } response = (<-this.PrivateMarginGetUniInterestRecords(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(marginMode, "cross")) { response = (<-this.PrivateMarginGetCrossInterestRecords(this.Extend(request, params))) PanicOnError(response) } var interest interface{} = this.ParseBorrowInterests(response, market) ch <- this.FilterByCurrencySinceLimit(interest, code, since, limit) return nil }() return ch } func (this *gate) ParseBorrowInterest(info interface{}, optionalArgs ...interface{}) interface{} { market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(info, "currency_pair") market = this.SafeMarket(marketId, market) var marginMode interface{} = Ternary(IsTrue((!IsEqual(marketId, nil))), "isolated", "cross") var timestamp interface{} = this.SafeInteger(info, "create_time") return map[string]interface{} { "info": info, "symbol": this.SafeString(market, "symbol"), "currency": this.SafeCurrencyCode(this.SafeString(info, "currency")), "interest": this.SafeNumber(info, "interest"), "interestRate": this.SafeNumber(info, "actual_rate"), "amountBorrowed": nil, "marginMode": marginMode, "timestamp": timestamp, "datetime": this.Iso8601(timestamp), } } func (this *gate) Nonce() interface{} { return Subtract(this.Milliseconds(), GetValue(this.Options, "timeDifference")) } func (this *gate) Sign(path interface{}, optionalArgs ...interface{}) interface{} { api := GetArg(optionalArgs, 0, []interface{}{}) _ = 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 authentication interface{} = GetValue(api, 0) // public, private var typeVar interface{} = GetValue(api, 1) // spot, margin, future, delivery var query interface{} = this.Omit(params, this.ExtractParams(path)) var containsSettle interface{} = IsGreaterThan(GetIndexOf(path, "settle"), OpNeg(1)) if IsTrue(IsTrue(containsSettle) && IsTrue(EndsWith(path, "batch_cancel_orders"))) { // special case where we need to extract the settle from the path // but the body is an array of strings var settle interface{} = this.SafeDict(params, 0) path = this.ImplodeParams(path, settle) // remove the first element from params var newParams interface{} = []interface{}{} var anyParams interface{} = params for i := 1; IsLessThan(i, GetArrayLength(anyParams)); i++ { AppendToArray(&newParams,GetValue(params, i)) } params = newParams query = newParams } else if IsTrue(IsArray(params)) { // endpoints like createOrders use an array instead of an object // so we infer the settle from one of the elements // they have to be all the same so relying on the first one is fine var first interface{} = this.SafeValue(params, 0, map[string]interface{} {}) path = this.ImplodeParams(path, first) } else { path = this.ImplodeParams(path, params) } var endPart interface{} = Ternary(IsTrue((IsEqual(path, ""))), "", (Add("/", path))) var entirePath interface{} = Add(Add("/", typeVar), endPart) if IsTrue(IsTrue((IsEqual(typeVar, "subAccounts"))) || IsTrue((IsEqual(typeVar, "withdrawals")))) { entirePath = endPart } var url interface{} = GetValue(GetValue(GetValue(this.Urls, "api"), authentication), typeVar) if IsTrue(IsEqual(url, nil)) { panic(NotSupported(Add(Add(Add(this.Id, " does not have a testnet for the "), typeVar), " market type."))) } url = Add(url, entirePath) if IsTrue(IsEqual(authentication, "public")) { if IsTrue(GetArrayLength(ObjectKeys(query))) { url = Add(url, Add("?", this.Urlencode(query))) } } else { this.CheckRequiredCredentials() var queryString interface{} = "" var requiresURLEncoding interface{} = false if IsTrue(IsTrue((IsTrue((IsEqual(typeVar, "futures"))) || IsTrue((IsEqual(typeVar, "delivery"))))) && IsTrue(IsEqual(method, "POST"))) { var pathParts interface{} = Split(path, "/") var secondPart interface{} = this.SafeString(pathParts, 1, "") requiresURLEncoding = IsTrue((IsGreaterThanOrEqual(GetIndexOf(secondPart, "dual"), 0))) || IsTrue((IsGreaterThanOrEqual(GetIndexOf(secondPart, "positions"), 0))) } if IsTrue(IsTrue(IsTrue(IsTrue((IsEqual(method, "GET"))) || IsTrue((IsEqual(method, "DELETE")))) || IsTrue(requiresURLEncoding)) || IsTrue((IsEqual(method, "PATCH")))) { if IsTrue(GetArrayLength(ObjectKeys(query))) { queryString = this.Urlencode(query) url = Add(url, Add("?", queryString)) } if IsTrue(IsEqual(method, "PATCH")) { body = this.Json(query) } } else { var urlQueryParams interface{} = this.SafeValue(query, "query", map[string]interface{} {}) if IsTrue(GetArrayLength(ObjectKeys(urlQueryParams))) { queryString = this.Urlencode(urlQueryParams) url = Add(url, Add("?", queryString)) } query = this.Omit(query, "query") body = this.Json(query) } var bodyPayload interface{} = Ternary(IsTrue((IsEqual(body, nil))), "", body) var bodySignature interface{} = this.Hash(this.Encode(bodyPayload), sha512) var nonce interface{} = this.Nonce() var timestamp interface{} = this.ParseToInt(Divide(nonce, 1000)) var timestampString interface{} = ToString(timestamp) var signaturePath interface{} = Add(Add("/api/", this.Version), entirePath) var payloadArray interface{} = []interface{}{ToUpper(method), signaturePath, queryString, bodySignature, timestampString} // eslint-disable-next-line quotes var payload interface{} = Join(payloadArray, "\n") var signature interface{} = this.Hmac(this.Encode(payload), this.Encode(this.Secret), sha512) headers = map[string]interface{} { "KEY": this.ApiKey, "Timestamp": timestampString, "SIGN": signature, "Content-Type": "application/json", } } return map[string]interface{} { "url": url, "method": method, "body": body, "headers": headers, } } func (this *gate) ModifyMarginHelper(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 retRes67588 := (<-this.LoadMarkets()) PanicOnError(retRes67588) var market interface{} = this.Market(symbol) requestqueryVariable := this.PrepareRequest(market, nil, params); request := GetValue(requestqueryVariable,0); query := GetValue(requestqueryVariable,1) AddElementToObject(request, "change", this.NumberToString(amount)) var response interface{} = nil if IsTrue(GetValue(market, "swap")) { response = (<-this.PrivateFuturesPostSettlePositionsContractMargin(this.Extend(request, query))) PanicOnError(response) } else if IsTrue(GetValue(market, "future")) { response = (<-this.PrivateDeliveryPostSettlePositionsContractMargin(this.Extend(request, query))) PanicOnError(response) } else { panic(NotSupported(Add(this.Id, " modifyMarginHelper() not support this market type"))) } ch <- this.ParseMarginModification(response, market) return nil }() return ch } func (this *gate) ParseMarginModification(data interface{}, optionalArgs ...interface{}) interface{} { // // { // "value": "11.9257", // "leverage": "5", // "mode": "single", // "realised_point": "0", // "contract": "ETH_USDT", // "entry_price": "1203.45", // "mark_price": "1192.57", // "history_point": "0", // "realised_pnl": "-0.00577656", // "close_order": null, // "size": "1", // "cross_leverage_limit": "0", // "pending_orders": "0", // "adl_ranking": "5", // "maintenance_rate": "0.005", // "unrealised_pnl": "-0.1088", // "user": "1486602", // "leverage_max": "100", // "history_pnl": "0", // "risk_limit": "1000000", // "margin": "5.415925875", // "last_close_pnl": "0", // "liq_price": "665.69" // } // market := GetArg(optionalArgs, 0, nil) _ = market var contract interface{} = this.SafeString(data, "contract") market = this.SafeMarket(contract, market, "_", "contract") var total interface{} = this.SafeNumber(data, "margin") return map[string]interface{} { "info": data, "symbol": GetValue(market, "symbol"), "type": nil, "marginMode": "isolated", "amount": nil, "total": total, "code": this.SafeValue(market, "quote"), "status": "ok", "timestamp": nil, "datetime": nil, } } /** * @method * @name gate#reduceMargin * @description remove margin from a position * @see https://www.gate.io/docs/developers/apiv4/en/#update-position-margin * @see https://www.gate.io/docs/developers/apiv4/en/#update-position-margin-2 * @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 *gate) 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 retRes683015 := (<-this.ModifyMarginHelper(symbol, OpNeg(amount), params)) PanicOnError(retRes683015) ch <- retRes683015 return nil }() return ch } /** * @method * @name gate#addMargin * @description add margin * @see https://www.gate.io/docs/developers/apiv4/en/#update-position-margin * @see https://www.gate.io/docs/developers/apiv4/en/#update-position-margin-2 * @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 *gate) 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 retRes684515 := (<-this.ModifyMarginHelper(symbol, amount, params)) PanicOnError(retRes684515) ch <- retRes684515 return nil }() return ch } /** * @method * @name gate#fetchOpenInterest * @description Retrieves the open interest of a currency * @see https://www.gate.io/docs/developers/apiv4/en/#futures-stats * @param {string} symbol Unified CCXT market symbol * @param {string} timeframe "5m", "15m", "30m", "1h", "4h", "1d" * @param {int} [since] the time(ms) of the earliest record to retrieve as a unix timestamp * @param {int} [limit] default 30 * @param {object} [params] exchange specific parameters * @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 open interest structure{@link https://docs.ccxt.com/#/?id=open-interest-structure} */ func (this *gate) 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 retRes68628 := (<-this.LoadMarkets()) PanicOnError(retRes68628) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOpenInterestHistory", "paginate", false); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes686619 := (<-this.FetchPaginatedCallDeterministic("fetchOpenInterestHistory", symbol, since, limit, timeframe, params, 100)) PanicOnError(retRes686619) ch <- retRes686619 return nil } var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "swap")) { panic(BadRequest(Add(this.Id, " fetchOpenInterest() supports swap markets only"))) } var request interface{} = map[string]interface{} { "contract": GetValue(market, "id"), "settle": GetValue(market, "settleId"), "interval": this.SafeString(this.Timeframes, timeframe, timeframe), } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", since) } response:= (<-this.PublicFuturesGetSettleContractStats(this.Extend(request, params))) PanicOnError(response) // // [ // { // "long_liq_size": "0", // "short_liq_size": "0", // "short_liq_usd": "0", // "lsr_account": "3.2808988764045", // "mark_price": "0.34619", // "top_lsr_size": "0", // "time": "1674057000", // "short_liq_amount": "0", // "long_liq_amount": "0", // "open_interest_usd": "9872386.7775", // "top_lsr_account": "0", // "open_interest": "2851725", // "long_liq_usd": "0", // "lsr_taker": "9.3765153315902" // }, // ... // ] // ch <- this.ParseOpenInterestsHistory(response, market, since, limit) return nil }() return ch } func (this *gate) ParseOpenInterest(interest interface{}, optionalArgs ...interface{}) interface{} { // // { // "long_liq_size": "0", // "short_liq_size": "0", // "short_liq_usd": "0", // "lsr_account": "3.2808988764045", // "mark_price": "0.34619", // "top_lsr_size": "0", // "time": "1674057000", // "short_liq_amount": "0", // "long_liq_amount": "0", // "open_interest_usd": "9872386.7775", // "top_lsr_account": "0", // "open_interest": "2851725", // "long_liq_usd": "0", // "lsr_taker": "9.3765153315902" // } // market := GetArg(optionalArgs, 0, nil) _ = market var timestamp interface{} = this.SafeTimestamp(interest, "time") return map[string]interface{} { "symbol": this.SafeString(market, "symbol"), "openInterestAmount": this.SafeNumber(interest, "open_interest"), "openInterestValue": this.SafeNumber(interest, "open_interest_usd"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "info": interest, } } /** * @method * @name gate#fetchSettlementHistory * @description fetches historical settlement records * @see https://www.gate.io/docs/developers/apiv4/en/#list-settlement-history-2 * @param {string} symbol unified market symbol of the settlement history, required on gate * @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]{@link https://docs.ccxt.com/#/?id=settlement-history-structure} */ func (this *gate) 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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchSettlementHistory() requires a symbol argument"))) } retRes69538 := (<-this.LoadMarkets()) PanicOnError(retRes69538) var market interface{} = 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 marketId interface{} = GetValue(market, "id") var optionParts interface{} = Split(marketId, "-") var request interface{} = map[string]interface{} { "underlying": this.SafeString(optionParts, 0), } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } response:= (<-this.PublicOptionsGetSettlements(this.Extend(request, params))) PanicOnError(response) // // [ // { // "time": 1685952000, // "profit": "18.266806892718", // "settle_price": "26826.68068927182", // "fee": "0.040240021034", // "contract": "BTC_USDT-20230605-25000-C", // "strike_price": "25000" // } // ] // 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 gate#fetchMySettlementHistory * @description fetches historical settlement records of the user * @see https://www.gate.io/docs/developers/apiv4/en/#list-my-options-settlements * @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 *gate) 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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchMySettlementHistory() requires a symbol argument"))) } retRes70048 := (<-this.LoadMarkets()) PanicOnError(retRes70048) var market interface{} = 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 marketId interface{} = GetValue(market, "id") var optionParts interface{} = Split(marketId, "-") var request interface{} = map[string]interface{} { "underlying": this.SafeString(optionParts, 0), "contract": marketId, } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } response:= (<-this.PrivateOptionsGetMySettlements(this.Extend(request, params))) PanicOnError(response) // // [ // { // "size": -1, // "settle_profit": "0", // "contract": "BTC_USDT-20220624-26000-C", // "strike_price": "26000", // "time": 1656057600, // "settle_price": "20917.461281337048", // "underlying": "BTC_USDT", // "realised_pnl": "-0.00116042", // "fee": "0" // } // ] // var result interface{} = this.SafeValue(response, "result", map[string]interface{} {}) var data interface{} = this.SafeValue(result, "list", []interface{}{}) var settlements interface{} = this.ParseSettlements(data, market) var sorted interface{} = this.SortBy(settlements, "timestamp") ch <- this.FilterBySymbolSinceLimit(sorted, GetValue(market, "symbol"), since, limit) return nil }() return ch } func (this *gate) ParseSettlement(settlement interface{}, market interface{}) interface{} { // // fetchSettlementHistory // // { // "time": 1685952000, // "profit": "18.266806892718", // "settle_price": "26826.68068927182", // "fee": "0.040240021034", // "contract": "BTC_USDT-20230605-25000-C", // "strike_price": "25000" // } // // fetchMySettlementHistory // // { // "size": -1, // "settle_profit": "0", // "contract": "BTC_USDT-20220624-26000-C", // "strike_price": "26000", // "time": 1656057600, // "settle_price": "20917.461281337048", // "underlying": "BTC_USDT", // "realised_pnl": "-0.00116042", // "fee": "0" // } // var timestamp interface{} = this.SafeTimestamp(settlement, "time") var marketId interface{} = this.SafeString(settlement, "contract") return map[string]interface{} { "info": settlement, "symbol": this.SafeSymbol(marketId, market), "price": this.SafeNumber(settlement, "settle_price"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), } } func (this *gate) ParseSettlements(settlements interface{}, market interface{}) interface{} { // // fetchSettlementHistory // // [ // { // "time": 1685952000, // "profit": "18.266806892718", // "settle_price": "26826.68068927182", // "fee": "0.040240021034", // "contract": "BTC_USDT-20230605-25000-C", // "strike_price": "25000" // } // ] // // fetchMySettlementHistory // // [ // { // "size": -1, // "settle_profit": "0", // "contract": "BTC_USDT-20220624-26000-C", // "strike_price": "26000", // "time": 1656057600, // "settle_price": "20917.461281337048", // "underlying": "BTC_USDT", // "realised_pnl": "-0.00116042", // "fee": "0" // } // ] // var result interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(settlements)); i++ { AppendToArray(&result,this.ParseSettlement(GetValue(settlements, i), market)) } return result } /** * @method * @name gate#fetchLedger * @description fetch the history of changes, actions done by the user or operations that altered the balance of the user * @see https://www.gate.io/docs/developers/apiv4/en/#query-account-book * @see https://www.gate.io/docs/developers/apiv4/en/#list-margin-account-balance-change-history * @see https://www.gate.io/docs/developers/apiv4/en/#query-account-book-2 * @see https://www.gate.io/docs/developers/apiv4/en/#query-account-book-3 * @see https://www.gate.io/docs/developers/apiv4/en/#list-account-changing-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] end time in ms * @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params) * @returns {object} a [ledger structure]{@link https://docs.ccxt.com/#/?id=ledger} */ func (this *gate) 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 retRes71408 := (<-this.LoadMarkets()) PanicOnError(retRes71408) var paginate interface{} = false paginateparamsVariable := this.HandleOptionAndParams(params, "fetchLedger", "paginate"); paginate = GetValue(paginateparamsVariable,0); params = GetValue(paginateparamsVariable,1) if IsTrue(paginate) { retRes714419 := (<-this.FetchPaginatedCallDynamic("fetchLedger", code, since, limit, params)) PanicOnError(retRes714419) ch <- retRes714419 return nil } var typeVar interface{} = nil var currency interface{} = nil var response interface{} = nil var request interface{} = map[string]interface{} {} typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchLedger", nil, params); typeVar = GetValue(typeVarparamsVariable,0); params = GetValue(typeVarparamsVariable,1) if IsTrue(IsTrue((IsEqual(typeVar, "spot"))) || IsTrue((IsEqual(typeVar, "margin")))) { if IsTrue(!IsEqual(code, nil)) { currency = this.Currency(code) AddElementToObject(request, "currency", GetValue(currency, "id")) // todo: currencies have network-junctions } } if IsTrue(IsTrue((IsEqual(typeVar, "swap"))) || IsTrue((IsEqual(typeVar, "future")))) { var defaultSettle interface{} = Ternary(IsTrue((IsEqual(typeVar, "swap"))), "usdt", "btc") var settle interface{} = this.SafeStringLower(params, "settle", defaultSettle) params = this.Omit(params, "settle") AddElementToObject(request, "settle", settle) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } requestparamsVariable := this.HandleUntilOption("to", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) if IsTrue(IsEqual(typeVar, "spot")) { response = (<-this.PrivateSpotGetAccountBook(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "margin")) { response = (<-this.PrivateMarginGetAccountBook(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "swap")) { response = (<-this.PrivateFuturesGetSettleAccountBook(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "future")) { response = (<-this.PrivateDeliveryGetSettleAccountBook(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(typeVar, "option")) { response = (<-this.PrivateOptionsGetAccountBook(this.Extend(request, params))) PanicOnError(response) } // // spot // // [ // { // "id": "123456", // "time": 1547633726123, // "currency": "BTC", // "change": "1.03", // "balance": "4.59316525194", // "type": "margin_in" // } // ] // // margin // // [ // { // "id": "123456", // "time": "1547633726", // "time_ms": 1547633726123, // "currency": "BTC", // "currency_pair": "BTC_USDT", // "change": "1.03", // "balance": "4.59316525194" // } // ] // // swap and future // // [ // { // "time": 1682294400.123456, // "change": "0.000010152188", // "balance": "4.59316525194", // "text": "ETH_USD:6086261", // "type": "fee" // } // ] // // option // // [ // { // "time": 1685594770, // "change": "3.33", // "balance": "29.87911771", // "text": "BTC_USDT-20230602-26500-C:2611026125", // "type": "prem" // } // ] // ch <- this.ParseLedger(response, currency, since, limit) return nil }() return ch } func (this *gate) ParseLedgerEntry(item interface{}, optionalArgs ...interface{}) interface{} { // // spot // // { // "id": "123456", // "time": 1547633726123, // "currency": "BTC", // "change": "1.03", // "balance": "4.59316525194", // "type": "margin_in" // } // // margin // // { // "id": "123456", // "time": "1547633726", // "time_ms": 1547633726123, // "currency": "BTC", // "currency_pair": "BTC_USDT", // "change": "1.03", // "balance": "4.59316525194" // } // // swap and future // // { // "time": 1682294400.123456, // "change": "0.000010152188", // "balance": "4.59316525194", // "text": "ETH_USD:6086261", // "type": "fee" // } // // option // // { // "time": 1685594770, // "change": "3.33", // "balance": "29.87911771", // "text": "BTC_USDT-20230602-26500-C:2611026125", // "type": "prem" // } // currency := GetArg(optionalArgs, 0, nil) _ = currency var direction interface{} = nil var amount interface{} = this.SafeString(item, "change") if IsTrue(Precise.StringLt(amount, "0")) { direction = "out" amount = Precise.StringAbs(amount) } else { direction = "in" } var currencyId interface{} = this.SafeString(item, "currency") currency = this.SafeCurrency(currencyId, currency) var typeVar interface{} = this.SafeString(item, "type") var rawTimestamp interface{} = this.SafeString(item, "time") var timestamp interface{} = nil if IsTrue(IsGreaterThan(GetLength(rawTimestamp), 10)) { timestamp = ParseInt(rawTimestamp) } else { timestamp = Multiply(ParseInt(rawTimestamp), 1000) } var balanceString interface{} = this.SafeString(item, "balance") var changeString interface{} = this.SafeString(item, "change") var before interface{} = this.ParseNumber(Precise.StringSub(balanceString, changeString)) return this.SafeLedgerEntry(map[string]interface{} { "info": item, "id": this.SafeString(item, "id"), "direction": direction, "account": nil, "referenceAccount": nil, "referenceId": nil, "type": this.ParseLedgerEntryType(typeVar), "currency": this.SafeCurrencyCode(currencyId, currency), "amount": this.ParseNumber(amount), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "before": before, "after": this.SafeNumber(item, "balance"), "status": nil, "fee": nil, }, currency) } func (this *gate) ParseLedgerEntryType(typeVar interface{}) interface{} { var ledgerType interface{} = map[string]interface{} { "deposit": "deposit", "withdraw": "withdrawal", "sub_account_transfer": "transfer", "margin_in": "transfer", "margin_out": "transfer", "margin_funding_in": "transfer", "margin_funding_out": "transfer", "cross_margin_in": "transfer", "cross_margin_out": "transfer", "copy_trading_in": "transfer", "copy_trading_out": "transfer", "quant_in": "transfer", "quant_out": "transfer", "futures_in": "transfer", "futures_out": "transfer", "delivery_in": "transfer", "delivery_out": "transfer", "new_order": "trade", "order_fill": "trade", "referral_fee": "rebate", "order_fee": "fee", "interest": "interest", "lend": "loan", "redeem": "loan", "profit": "interest", "flash_swap_buy": "trade", "flash_swap_sell": "trade", "unknown": "unknown", "set": "settlement", "prem": "trade", "point_refr": "rebate", "point_fee": "fee", "point_dnw": "deposit/withdraw", "fund": "fee", "refr": "rebate", "fee": "fee", "pnl": "trade", "dnw": "deposit/withdraw", } return this.SafeString(ledgerType, typeVar, typeVar) } /** * @method * @name gate#setPositionMode * @description set dual/hedged mode to true or false for a swap market, make sure all positions are closed and no orders are open before setting dual mode * @see https://www.gate.io/docs/developers/apiv4/en/#enable-or-disable-dual-mode * @param {bool} hedged set to true to enable dual mode * @param {string|undefined} symbol if passed, dual mode is set for all markets with the same settle currency * @param {object} params extra parameters specific to the exchange API endpoint * @param {string} params.settle settle currency * @returns {object} response from the exchange */ func (this *gate) 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 market interface{} = Ternary(IsTrue((!IsEqual(symbol, nil))), this.Market(symbol), nil) requestqueryVariable := this.PrepareRequest(market, "swap", params); request := GetValue(requestqueryVariable,0); query := GetValue(requestqueryVariable,1) AddElementToObject(request, "dual_mode", hedged) retRes738015 := (<-this.PrivateFuturesPostSettleDualMode(this.Extend(request, query))) PanicOnError(retRes738015) ch <- retRes738015 return nil }() return ch } /** * @method * @name gate#fetchUnderlyingAssets * @description fetches the market ids of underlying assets for a specific contract market type * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-underlyings * @param {object} [params] exchange specific params * @param {string} [params.type] the contract market type, 'option', 'swap' or 'future', the default is 'option' * @returns {object[]} a list of [underlying assets]{@link https://docs.ccxt.com/#/?id=underlying-assets-structure} */ func (this *gate) FetchUnderlyingAssets(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 retRes73938 := (<-this.LoadMarkets()) PanicOnError(retRes73938) var marketType interface{} = nil marketTypeparamsVariable := this.HandleMarketTypeAndParams("fetchUnderlyingAssets", nil, params); marketType = GetValue(marketTypeparamsVariable,0); params = GetValue(marketTypeparamsVariable,1) if IsTrue(IsTrue((IsEqual(marketType, nil))) || IsTrue((IsEqual(marketType, "spot")))) { marketType = "option" } if IsTrue(!IsEqual(marketType, "option")) { panic(NotSupported(Add(this.Id, " fetchUnderlyingAssets() supports option markets only"))) } response:= (<-this.PublicOptionsGetUnderlyings(params)) PanicOnError(response) // // [ // { // "index_time": "1646915796", // "name": "BTC_USDT", // "index_price": "39142.73" // } // ] // var underlyings interface{} = []interface{}{} for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var underlying interface{} = GetValue(response, i) var name interface{} = this.SafeString(underlying, "name") if IsTrue(!IsEqual(name, nil)) { AppendToArray(&underlyings,name) } } ch <- underlyings return nil }() return ch } /** * @method * @name gate#fetchLiquidations * @description retrieves the public liquidations of a trading pair * @see https://www.gate.io/docs/developers/apiv4/en/#retrieve-liquidation-history * @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 exchange API endpoint * @param {int} [params.until] timestamp in ms of the latest liquidation * @returns {object} an array of [liquidation structures]{@link https://docs.ccxt.com/#/?id=liquidation-structure} */ func (this *gate) FetchLiquidations(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 retRes74368 := (<-this.LoadMarkets()) PanicOnError(retRes74368) var market interface{} = this.Market(symbol) if !IsTrue(GetValue(market, "swap")) { panic(NotSupported(Add(this.Id, " fetchLiquidations() supports swap markets only"))) } var request interface{} = map[string]interface{} { "settle": GetValue(market, "settleId"), "contract": GetValue(market, "id"), } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", since) } if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } requestparamsVariable := this.HandleUntilOption("to", request, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) response:= (<-this.PublicFuturesGetSettleLiqOrders(this.Extend(request, params))) PanicOnError(response) // // [ // { // "contract": "BTC_USDT", // "left": 0, // "size": -165, // "fill_price": "28070", // "order_price": "28225", // "time": 1696736132 // }, // ] // ch <- this.ParseLiquidations(response, market, since, limit) return nil }() return ch } /** * @method * @name gate#fetchMyLiquidations * @description retrieves the users liquidated positions * @see https://www.gate.io/docs/developers/apiv4/en/#list-liquidation-history * @see https://www.gate.io/docs/developers/apiv4/en/#list-liquidation-history-2 * @see https://www.gate.io/docs/developers/apiv4/en/#list-user-s-liquidation-history-of-specified-underlying * @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 exchange API endpoint * @returns {object} an array of [liquidation structures]{@link https://docs.ccxt.com/#/?id=liquidation-structure} */ func (this *gate) 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 if IsTrue(IsEqual(symbol, nil)) { panic(ArgumentsRequired(Add(this.Id, " fetchMyLiquidations() requires a symbol argument"))) } retRes74858 := (<-this.LoadMarkets()) PanicOnError(retRes74858) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "contract": GetValue(market, "id"), } var response interface{} = nil if IsTrue(IsTrue((GetValue(market, "swap"))) || IsTrue((GetValue(market, "future")))) { if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } AddElementToObject(request, "settle", GetValue(market, "settleId")) } else if IsTrue(GetValue(market, "option")) { var marketId interface{} = GetValue(market, "id") var optionParts interface{} = Split(marketId, "-") AddElementToObject(request, "underlying", this.SafeString(optionParts, 0)) } if IsTrue(GetValue(market, "swap")) { response = (<-this.PrivateFuturesGetSettleLiquidates(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "future")) { response = (<-this.PrivateDeliveryGetSettleLiquidates(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(GetValue(market, "option")) { response = (<-this.PrivateOptionsGetPositionClose(this.Extend(request, params))) PanicOnError(response) } else { panic(NotSupported(Add(Add(Add(this.Id, " fetchMyLiquidations() does not support "), GetValue(market, "type")), " orders"))) } // // swap and future // // [ // { // "time": 1548654951, // "contract": "BTC_USDT", // "size": 600, // "leverage": "25", // "margin": "0.006705256878", // "entry_price": "3536.123", // "liq_price": "3421.54", // "mark_price": "3420.27", // "order_id": 317393847, // "order_price": "3405", // "fill_price": "3424", // "left": 0 // } // ] // // option // // [ // { // "time": 1631764800, // "pnl": "-42914.291", // "settle_size": "-10001", // "side": "short", // "contract": "BTC_USDT-20210916-5000-C", // "text": "settled" // } // ] // ch <- this.ParseLiquidations(response, market, since, limit) return nil }() return ch } func (this *gate) ParseLiquidation(liquidation interface{}, optionalArgs ...interface{}) interface{} { // // fetchLiquidations // // { // "contract": "BTC_USDT", // "left": 0, // "size": -165, // "fill_price": "28070", // "order_price": "28225", // "time": 1696736132 // } // // swap and future: fetchMyLiquidations // // { // "time": 1548654951, // "contract": "BTC_USDT", // "size": 600, // "leverage": "25", // "margin": "0.006705256878", // "entry_price": "3536.123", // "liq_price": "3421.54", // "mark_price": "3420.27", // "order_id": 317393847, // "order_price": "3405", // "fill_price": "3424", // "left": 0 // } // // option: fetchMyLiquidations // // { // "time": 1631764800, // "pnl": "-42914.291", // "settle_size": "-10001", // "side": "short", // "contract": "BTC_USDT-20210916-5000-C", // "text": "settled" // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(liquidation, "contract") var timestamp interface{} = this.SafeTimestamp(liquidation, "time") var size interface{} = this.SafeString2(liquidation, "size", "settle_size") var left interface{} = this.SafeString(liquidation, "left", "0") var contractsString interface{} = Precise.StringAbs(Precise.StringSub(size, left)) var contractSizeString interface{} = this.SafeString(market, "contractSize") var priceString interface{} = this.SafeString2(liquidation, "liq_price", "fill_price") var baseValueString interface{} = Precise.StringMul(contractsString, contractSizeString) var quoteValueString interface{} = this.SafeString(liquidation, "pnl") if IsTrue(IsEqual(quoteValueString, nil)) { quoteValueString = Precise.StringMul(baseValueString, priceString) } return this.SafeLiquidation(map[string]interface{} { "info": liquidation, "symbol": this.SafeSymbol(marketId, market), "contracts": this.ParseNumber(contractsString), "contractSize": this.ParseNumber(contractSizeString), "price": this.ParseNumber(priceString), "baseValue": this.ParseNumber(baseValueString), "quoteValue": this.ParseNumber(Precise.StringAbs(quoteValueString)), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), }) } /** * @method * @name gate#fetchGreeks * @description fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract * @see https://www.gate.io/docs/developers/apiv4/en/#list-tickers-of-options-contracts * @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 *gate) 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 retRes76228 := (<-this.LoadMarkets()) PanicOnError(retRes76228) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "underlying": GetValue(GetValue(market, "info"), "underlying"), } response:= (<-this.PublicOptionsGetTickers(this.Extend(request, params))) PanicOnError(response) // // [ // { // "vega": "1.78992", // "leverage": "6.2096777055417", // "ask_iv": "0.6245", // "delta": "-0.69397", // "last_price": "0", // "theta": "-2.5723", // "bid1_price": "222.9", // "mark_iv": "0.5909", // "name": "ETH_USDT-20231201-2300-P", // "bid_iv": "0.5065", // "ask1_price": "243.6", // "mark_price": "236.57", // "position_size": 0, // "bid1_size": 368, // "ask1_size": -335, // "gamma": "0.00116" // }, // ] // var marketId interface{} = GetValue(market, "id") for i := 0; IsLessThan(i, GetArrayLength(response)); i++ { var entry interface{} = GetValue(response, i) var entryMarketId interface{} = this.SafeString(entry, "name") if IsTrue(IsEqual(entryMarketId, marketId)) { ch <- this.ParseGreeks(entry, market) return nil } } return nil }() return ch } func (this *gate) ParseGreeks(greeks interface{}, optionalArgs ...interface{}) interface{} { // // { // "vega": "1.78992", // "leverage": "6.2096777055417", // "ask_iv": "0.6245", // "delta": "-0.69397", // "last_price": "0", // "theta": "-2.5723", // "bid1_price": "222.9", // "mark_iv": "0.5909", // "name": "ETH_USDT-20231201-2300-P", // "bid_iv": "0.5065", // "ask1_price": "243.6", // "mark_price": "236.57", // "position_size": 0, // "bid1_size": 368, // "ask1_size": -335, // "gamma": "0.00116" // } // market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString(greeks, "name") 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": this.SafeNumber(greeks, "bid1_size"), "askSize": this.SafeNumber(greeks, "ask1_size"), "bidImpliedVolatility": this.SafeNumber(greeks, "bid_iv"), "askImpliedVolatility": this.SafeNumber(greeks, "ask_iv"), "markImpliedVolatility": this.SafeNumber(greeks, "mark_iv"), "bidPrice": this.SafeNumber(greeks, "bid1_price"), "askPrice": this.SafeNumber(greeks, "ask1_price"), "markPrice": this.SafeNumber(greeks, "mark_price"), "lastPrice": this.SafeNumber(greeks, "last_price"), "underlyingPrice": this.ParseNumber(GetValue(GetValue(market, "info"), "underlying_price")), "info": greeks, } } /** * @method * @name gate#closePosition * @description closes open positions for a market * @see https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order * @see https://www.gate.io/docs/developers/apiv4/en/#create-a-futures-order-2 * @see https://www.gate.io/docs/developers/apiv4/en/#create-an-options-order * @param {string} symbol Unified CCXT market symbol * @param {string} side 'buy' or 'sell' * @param {object} [params] extra parameters specific to the okx api endpoint * @returns {object[]} [A list of position structures]{@link https://docs.ccxt.com/#/?id=position-structure} */ func (this *gate) ClosePosition(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) side := GetArg(optionalArgs, 0, nil) _ = side params := GetArg(optionalArgs, 1, map[string]interface{} {}) _ = params var request interface{} = map[string]interface{} { "close": true, } params = this.Extend(request, params) if IsTrue(IsEqual(side, nil)) { side = "" // side is not used but needs to be present, otherwise crashes in php } retRes772715 := (<-this.CreateOrder(symbol, "market", side, 0, nil, params)) PanicOnError(retRes772715) ch <- retRes772715 return nil }() return ch } /** * @method * @name gate#fetchLeverage * @description fetch the set leverage for a market * @see https://www.gate.io/docs/developers/apiv4/en/#get-unified-account-information * @see https://www.gate.io/docs/developers/apiv4/en/#get-detail-of-lending-market * @see https://www.gate.io/docs/developers/apiv4/en/#query-one-single-margin-currency-pair-deprecated * @param {string} symbol unified market symbol * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.unified] default false, set to true for fetching the unified accounts leverage * @returns {object} a [leverage structure]{@link https://docs.ccxt.com/#/?id=leverage-structure} */ func (this *gate) FetchLeverage(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) params := GetArg(optionalArgs, 0, map[string]interface{} {}) _ = params retRes77438 := (<-this.LoadMarkets()) PanicOnError(retRes77438) var market interface{} = nil if IsTrue(!IsEqual(symbol, nil)) { // unified account does not require a symbol market = this.Market(symbol) } var request interface{} = map[string]interface{} {} var response interface{} = nil var isUnified interface{} = this.SafeBool(params, "unified") params = this.Omit(params, "unified") if IsTrue(GetValue(market, "spot")) { AddElementToObject(request, "currency_pair", GetValue(market, "id")) if IsTrue(isUnified) { response = (<-this.PublicMarginGetUniCurrencyPairsCurrencyPair(this.Extend(request, params))) PanicOnError(response) } else { response = (<-this.PublicMarginGetCurrencyPairsCurrencyPair(this.Extend(request, params))) PanicOnError(response) } } else if IsTrue(isUnified) { response = (<-this.PrivateUnifiedGetAccounts(this.Extend(request, params))) PanicOnError(response) } else { panic(NotSupported(Add(Add(Add(this.Id, " fetchLeverage() does not support "), GetValue(market, "type")), " markets"))) } ch <- this.ParseLeverage(response, market) return nil }() return ch } /** * @method * @name gate#fetchLeverages * @description fetch the set leverage for all leverage markets, only spot margin is supported on gate * @see https://www.gate.io/docs/developers/apiv4/en/#list-lending-markets * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-supported-currency-pairs-supported-in-margin-trading-deprecated * @param {string[]} symbols a list of unified market symbols * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {boolean} [params.unified] default false, set to true for fetching unified account leverages * @returns {object} a list of [leverage structures]{@link https://docs.ccxt.com/#/?id=leverage-structure} */ func (this *gate) 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 retRes78508 := (<-this.LoadMarkets()) PanicOnError(retRes78508) symbols = this.MarketSymbols(symbols) var response interface{} = nil var isUnified interface{} = this.SafeBool(params, "unified") params = this.Omit(params, "unified") var marketIdRequest interface{} = "id" if IsTrue(isUnified) { marketIdRequest = "currency_pair" response = (<-this.PublicMarginGetUniCurrencyPairs(params)) PanicOnError(response) } else { response = (<-this.PublicMarginGetCurrencyPairs(params)) PanicOnError(response) } ch <- this.ParseLeverages(response, symbols, marketIdRequest, "spot") return nil }() return ch } func (this *gate) ParseLeverage(leverage interface{}, optionalArgs ...interface{}) interface{} { market := GetArg(optionalArgs, 0, nil) _ = market var marketId interface{} = this.SafeString2(leverage, "currency_pair", "id") var leverageValue interface{} = this.SafeInteger(leverage, "leverage") return map[string]interface{} { "info": leverage, "symbol": this.SafeSymbol(marketId, market, "_", "spot"), "marginMode": nil, "longLeverage": leverageValue, "shortLeverage": leverageValue, } } /** * @method * @name gate#fetchOption * @description fetches option data that is commonly found in an option chain * @see https://www.gate.io/docs/developers/apiv4/en/#query-specified-contract-detail * @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 *gate) 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 retRes79118 := (<-this.LoadMarkets()) PanicOnError(retRes79118) var market interface{} = this.Market(symbol) var request interface{} = map[string]interface{} { "contract": GetValue(market, "id"), } response:= (<-this.PublicOptionsGetContractsContract(this.Extend(request, params))) PanicOnError(response) // // { // "is_active": true, // "mark_price_round": "0.01", // "settle_fee_rate": "0.00015", // "bid1_size": 30, // "taker_fee_rate": "0.0003", // "price_limit_fee_rate": "0.1", // "order_price_round": "0.1", // "tag": "month", // "ref_rebate_rate": "0", // "name": "ETH_USDT-20240628-4500-C", // "strike_price": "4500", // "ask1_price": "280.5", // "ref_discount_rate": "0", // "order_price_deviate": "0.2", // "ask1_size": -19, // "mark_price_down": "155.45", // "orderbook_id": 11724695, // "is_call": true, // "last_price": "188.7", // "mark_price": "274.26", // "underlying": "ETH_USDT", // "create_time": 1688024882, // "settle_limit_fee_rate": "0.1", // "orders_limit": 10, // "mark_price_up": "403.83", // "position_size": 80, // "order_size_max": 10000, // "position_limit": 100000, // "multiplier": "0.01", // "order_size_min": 1, // "trade_size": 229, // "underlying_price": "3326.6", // "maker_fee_rate": "0.0003", // "expiration_time": 1719561600, // "trade_id": 15, // "bid1_price": "269.3" // } // ch <- this.ParseOption(response, nil, market) return nil }() return ch } /** * @method * @name gate#fetchOptionChain * @description fetches data for an underlying asset that is commonly found in an option chain * @see https://www.gate.io/docs/developers/apiv4/en/#list-all-the-contracts-with-specified-underlying-and-expiration-time * @param {string} code base currency to fetch an option chain for * @param {object} [params] extra parameters specific to the exchange API endpoint * @param {string} [params.underlying] the underlying asset, can be obtained from fetchUnderlyingAssets () * @param {int} [params.expiration] unix timestamp of the expiration time * @returns {object} a list of [option chain structures]{@link https://docs.ccxt.com/#/?id=option-chain-structure} */ func (this *gate) FetchOptionChain(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 retRes79728 := (<-this.LoadMarkets()) PanicOnError(retRes79728) var currency interface{} = this.Currency(code) var request interface{} = map[string]interface{} { "underlying": Add(GetValue(currency, "code"), "_USDT"), } response:= (<-this.PublicOptionsGetContracts(this.Extend(request, params))) PanicOnError(response) // // [ // { // "is_active": true, // "mark_price_round": "0.1", // "settle_fee_rate": "0.00015", // "bid1_size": 434, // "taker_fee_rate": "0.0003", // "price_limit_fee_rate": "0.1", // "order_price_round": "1", // "tag": "day", // "ref_rebate_rate": "0", // "name": "BTC_USDT-20240324-63500-P", // "strike_price": "63500", // "ask1_price": "387", // "ref_discount_rate": "0", // "order_price_deviate": "0.15", // "ask1_size": -454, // "mark_price_down": "124.3", // "orderbook_id": 29600, // "is_call": false, // "last_price": "0", // "mark_price": "366.6", // "underlying": "BTC_USDT", // "create_time": 1711118829, // "settle_limit_fee_rate": "0.1", // "orders_limit": 10, // "mark_price_up": "630", // "position_size": 0, // "order_size_max": 10000, // "position_limit": 10000, // "multiplier": "0.01", // "order_size_min": 1, // "trade_size": 0, // "underlying_price": "64084.65", // "maker_fee_rate": "0.0003", // "expiration_time": 1711267200, // "trade_id": 0, // "bid1_price": "307" // }, // ] // ch <- this.ParseOptionChain(response, nil, "name") return nil }() return ch } func (this *gate) ParseOption(chain interface{}, optionalArgs ...interface{}) interface{} { // // { // "is_active": true, // "mark_price_round": "0.1", // "settle_fee_rate": "0.00015", // "bid1_size": 434, // "taker_fee_rate": "0.0003", // "price_limit_fee_rate": "0.1", // "order_price_round": "1", // "tag": "day", // "ref_rebate_rate": "0", // "name": "BTC_USDT-20240324-63500-P", // "strike_price": "63500", // "ask1_price": "387", // "ref_discount_rate": "0", // "order_price_deviate": "0.15", // "ask1_size": -454, // "mark_price_down": "124.3", // "orderbook_id": 29600, // "is_call": false, // "last_price": "0", // "mark_price": "366.6", // "underlying": "BTC_USDT", // "create_time": 1711118829, // "settle_limit_fee_rate": "0.1", // "orders_limit": 10, // "mark_price_up": "630", // "position_size": 0, // "order_size_max": 10000, // "position_limit": 10000, // "multiplier": "0.01", // "order_size_min": 1, // "trade_size": 0, // "underlying_price": "64084.65", // "maker_fee_rate": "0.0003", // "expiration_time": 1711267200, // "trade_id": 0, // "bid1_price": "307" // } // currency := GetArg(optionalArgs, 0, nil) _ = currency market := GetArg(optionalArgs, 1, nil) _ = market var marketId interface{} = this.SafeString(chain, "name") market = this.SafeMarket(marketId, market) var timestamp interface{} = this.SafeTimestamp(chain, "create_time") return map[string]interface{} { "info": chain, "currency": nil, "symbol": GetValue(market, "symbol"), "timestamp": timestamp, "datetime": this.Iso8601(timestamp), "impliedVolatility": nil, "openInterest": nil, "bidPrice": this.SafeNumber(chain, "bid1_price"), "askPrice": this.SafeNumber(chain, "ask1_price"), "midPrice": nil, "markPrice": this.SafeNumber(chain, "mark_price"), "lastPrice": this.SafeNumber(chain, "last_price"), "underlyingPrice": this.SafeNumber(chain, "underlying_price"), "change": nil, "percentage": nil, "baseVolume": nil, "quoteVolume": nil, } } /** * @method * @name gate#fetchPositionsHistory * @description fetches historical positions * @see https://www.gate.io/docs/developers/apiv4/#list-position-close-history * @see https://www.gate.io/docs/developers/apiv4/#list-position-close-history-2 * @param {string[]} symbols unified conract symbols, must all have the same settle currency and the same market type * @param {int} [since] the earliest time in ms to fetch positions for * @param {int} [limit] the maximum amount of records to fetch, default=1000 * @param {object} params extra parameters specific to the exchange api endpoint * @param {int} [params.until] the latest time in ms to fetch positions for * * EXCHANGE SPECIFIC PARAMETERS * @param {int} [params.offset] list offset, starting from 0 * @param {string} [params.side] long or short * @param {string} [params.pnl] query profit or loss * @returns {object[]} a list of [position structures]{@link https://docs.ccxt.com/#/?id=position-structure} */ func (this *gate) FetchPositionsHistory(optionalArgs ...interface{}) <- chan interface{} { ch := make(chan interface{}) go func() interface{} { defer close(ch) defer ReturnPanicError(ch) symbols := GetArg(optionalArgs, 0, nil) _ = symbols since := GetArg(optionalArgs, 1, nil) _ = since limit := GetArg(optionalArgs, 2, nil) _ = limit params := GetArg(optionalArgs, 3, map[string]interface{} {}) _ = params retRes81078 := (<-this.LoadMarkets()) PanicOnError(retRes81078) var market interface{} = nil if IsTrue(!IsEqual(symbols, nil)) { var symbolsLength interface{} = GetArrayLength(symbols) if IsTrue(IsEqual(symbolsLength, 1)) { market = this.Market(GetValue(symbols, 0)) } } var marketType interface{} = nil marketTypeparamsVariable := this.HandleMarketTypeAndParams("fetchPositionsHistory", market, params, "swap"); marketType = GetValue(marketTypeparamsVariable,0); params = GetValue(marketTypeparamsVariable,1) var until interface{} = this.SafeInteger(params, "until") params = this.Omit(params, "until") var request interface{} = map[string]interface{} {} requestparamsVariable := this.PrepareRequest(market, marketType, params); request = GetValue(requestparamsVariable,0); params = GetValue(requestparamsVariable,1) if IsTrue(!IsEqual(limit, nil)) { AddElementToObject(request, "limit", limit) } if IsTrue(!IsEqual(since, nil)) { AddElementToObject(request, "from", this.ParseToInt(Divide(since, 1000))) } if IsTrue(!IsEqual(until, nil)) { AddElementToObject(request, "to", this.ParseToInt(Divide(until, 1000))) } var response interface{} = nil if IsTrue(IsEqual(marketType, "swap")) { response = (<-this.PrivateFuturesGetSettlePositionClose(this.Extend(request, params))) PanicOnError(response) } else if IsTrue(IsEqual(marketType, "future")) { response = (<-this.PrivateDeliveryGetSettlePositionClose(this.Extend(request, params))) PanicOnError(response) } else { panic(NotSupported(Add(Add(this.Id, " fetchPositionsHistory() does not support markets of type "), marketType))) } // // [ // { // "contract": "SLERF_USDT", // "text": "web", // "long_price": "0.766306", // "pnl": "-23.41702352", // "pnl_pnl": "-22.7187", // "pnl_fee": "-0.06527125", // "pnl_fund": "-0.63305227", // "accum_size": "100", // "time": 1711279263, // "short_price": "0.539119", // "side": "long", // "max_size": "100", // "first_open_time": 1711037985 // }, // ... // ] // ch <- this.ParsePositions(response, symbols, params) return nil }() return ch } func (this *gate) HandleErrors(code interface{}, reason interface{}, url interface{}, method interface{}, headers interface{}, body interface{}, response interface{}, requestHeaders interface{}, requestBody interface{}) interface{} { if IsTrue(IsEqual(response, nil)) { return nil } // // {"label": "ORDER_NOT_FOUND", "message": "Order not found"} // {"label": "INVALID_PARAM_VALUE", "message": "invalid argument: status"} // {"label": "INVALID_PARAM_VALUE", "message": "invalid argument: Trigger.rule"} // {"label": "INVALID_PARAM_VALUE", "message": "invalid argument: trigger.expiration invalid range"} // {"label": "INVALID_ARGUMENT", "detail": "invalid size"} // {"user_id":10406147,"id":"id","succeeded":false,"message":"INVALID_PROTOCOL","label":"INVALID_PROTOCOL"} // var label interface{} = this.SafeString(response, "label") if IsTrue(!IsEqual(label, nil)) { var feedback interface{} = Add(Add(this.Id, " "), body) this.ThrowExactlyMatchedException(GetValue(this.Exceptions, "exact"), label, feedback) panic(ExchangeError(feedback)) } return nil } func (this *gate) Init(userConfig map[string]interface{}) { this.Exchange = Exchange{} this.Exchange.InitParent(userConfig, this.Describe().(map[string]interface{}), this) this.Exchange.DerivedExchange = this }