ccxt-go/kucoinfutures.go

4042 lines
179 KiB
Go
Raw Permalink Normal View History

2025-02-28 10:33:20 +08:00
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 kucoinfutures struct {
kucoin
}
func NewKucoinfuturesCore() kucoinfutures {
p := kucoinfutures{}
setDefaults(&p)
return p
}
func (this *kucoinfutures) Describe() interface{} {
return this.DeepExtend(this.kucoin.Describe(), map[string]interface{} {
"id": "kucoinfutures",
"name": "KuCoin Futures",
"countries": []interface{}{"SC"},
"rateLimit": 75,
"version": "v1",
"certified": true,
"pro": true,
"comment": "Platform 2.0",
"quoteJsonNumbers": false,
"has": map[string]interface{} {
"CORS": nil,
"spot": false,
"margin": false,
"swap": true,
"future": true,
"option": false,
"addMargin": true,
"cancelAllOrders": true,
"cancelOrder": true,
"cancelOrders": true,
"closeAllPositions": false,
"closePosition": true,
"closePositions": false,
"createDepositAddress": true,
"createOrder": true,
"createOrders": true,
"createOrderWithTakeProfitAndStopLoss": true,
"createReduceOnlyOrder": true,
"createStopLimitOrder": true,
"createStopLossOrder": true,
"createStopMarketOrder": true,
"createStopOrder": true,
"createTakeProfitOrder": true,
"createTriggerOrder": true,
"fetchAccounts": true,
"fetchBalance": true,
"fetchBidsAsks": true,
"fetchBorrowRateHistories": false,
"fetchBorrowRateHistory": false,
"fetchClosedOrders": true,
"fetchCrossBorrowRate": false,
"fetchCrossBorrowRates": false,
"fetchCurrencies": false,
"fetchDepositAddress": true,
"fetchDepositAddresses": false,
"fetchDepositAddressesByNetwork": false,
"fetchDeposits": true,
"fetchDepositWithdrawFee": false,
"fetchDepositWithdrawFees": false,
"fetchFundingHistory": true,
"fetchFundingInterval": true,
"fetchFundingIntervals": false,
"fetchFundingRate": true,
"fetchFundingRateHistory": true,
"fetchIndexOHLCV": false,
"fetchIsolatedBorrowRate": false,
"fetchIsolatedBorrowRates": false,
"fetchL3OrderBook": true,
"fetchLedger": true,
"fetchLeverage": true,
"fetchLeverageTiers": false,
"fetchMarginAdjustmentHistory": false,
"fetchMarginMode": true,
"fetchMarketLeverageTiers": true,
"fetchMarkets": true,
"fetchMarkOHLCV": false,
"fetchMarkPrice": true,
"fetchMyTrades": true,
"fetchOHLCV": true,
"fetchOpenOrders": true,
"fetchOrder": true,
"fetchOrderBook": true,
"fetchPosition": true,
"fetchPositionHistory": false,
"fetchPositionMode": false,
"fetchPositions": true,
"fetchPositionsHistory": true,
"fetchPremiumIndexOHLCV": false,
"fetchStatus": true,
"fetchTicker": true,
"fetchTickers": true,
"fetchTime": true,
"fetchTrades": true,
"fetchTradingFee": true,
"fetchTransactionFee": false,
"fetchWithdrawals": true,
"setLeverage": false,
"setMarginMode": true,
"transfer": true,
"withdraw": nil,
},
"urls": map[string]interface{} {
"logo": "https://user-images.githubusercontent.com/1294454/147508995-9e35030a-d046-43a1-a006-6fabd981b554.jpg",
"doc": []interface{}{"https://docs.kucoin.com/futures", "https://docs.kucoin.com"},
"www": "https://futures.kucoin.com/",
"referral": "https://futures.kucoin.com/?rcode=E5wkqe",
"api": map[string]interface{} {
"public": "https://openapi-v2.kucoin.com",
"private": "https://openapi-v2.kucoin.com",
"futuresPrivate": "https://api-futures.kucoin.com",
"futuresPublic": "https://api-futures.kucoin.com",
"webExchange": "https://futures.kucoin.com/_api/web-front",
},
},
"requiredCredentials": map[string]interface{} {
"apiKey": true,
"secret": true,
"password": true,
},
"api": map[string]interface{} {
"futuresPublic": map[string]interface{} {
"get": map[string]interface{} {
"contracts/active": 1,
"contracts/{symbol}": 1,
"contracts/risk-limit/{symbol}": 1,
"ticker": 1,
"allTickers": 1,
"level2/snapshot": 1.33,
"level2/depth{limit}": 1,
"level2/message/query": 1,
"level3/message/query": 1,
"level3/snapshot": 1,
"trade/history": 1,
"interest/query": 1,
"index/query": 1,
"mark-price/{symbol}/current": 1,
"premium/query": 1,
"funding-rate/{symbol}/current": 1,
"timestamp": 1,
"status": 1,
"kline/query": 1,
},
"post": map[string]interface{} {
"bullet-public": 1,
},
},
"futuresPrivate": map[string]interface{} {
"get": map[string]interface{} {
"account-overview": 1.33,
"transaction-history": 4.44,
"deposit-address": 1,
"deposit-list": 1,
"withdrawals/quotas": 1,
"withdrawal-list": 1,
"transfer-list": 1,
"orders": 1.33,
"stopOrders": 1,
"recentDoneOrders": 1,
"orders/{orderId}": 1,
"orders/byClientOid": 1,
"fills": 4.44,
"recentFills": 4.44,
"openOrderStatistics": 1,
"position": 1,
"positions": 4.44,
"funding-history": 4.44,
"sub/api-key": 1,
"trade-statistics": 1,
"trade-fees": 1,
"history-positions": 1,
"getMaxOpenSize": 1,
"getCrossUserLeverage": 1,
"position/getMarginMode": 1,
},
"post": map[string]interface{} {
"withdrawals": 1,
"transfer-out": 1,
"transfer-in": 1,
"orders": 1.33,
"st-orders": 1.33,
"orders/test": 1.33,
"position/margin/auto-deposit-status": 1,
"position/margin/deposit-margin": 1,
"position/risk-limit-level/change": 1,
"bullet-private": 1,
"sub/api-key": 1,
"sub/api-key/update": 1,
"changeCrossUserLeverage": 1,
"position/changeMarginMode": 1,
},
"delete": map[string]interface{} {
"withdrawals/{withdrawalId}": 1,
"cancel/transfer-out": 1,
"orders/{orderId}": 1,
"orders": 4.44,
"stopOrders": 1,
"sub/api-key": 1,
"orders/client-order/{clientOid}": 1,
"orders/multi-cancel": 20,
},
},
"webExchange": map[string]interface{} {
"get": map[string]interface{} {
"contract/{symbol}/funding-rates": 1,
},
},
},
"precisionMode": TICK_SIZE,
"exceptions": map[string]interface{} {
"exact": map[string]interface{} {
"400": BadRequest,
"401": AuthenticationError,
"403": NotSupported,
"404": NotSupported,
"405": NotSupported,
"415": BadRequest,
"429": RateLimitExceeded,
"500": ExchangeNotAvailable,
"503": ExchangeNotAvailable,
"100001": InvalidOrder,
"100004": BadRequest,
"101030": PermissionDenied,
"200004": InsufficientFunds,
"230003": InsufficientFunds,
"260100": InsufficientFunds,
"300003": InsufficientFunds,
"300012": InvalidOrder,
"400001": AuthenticationError,
"400002": InvalidNonce,
"400003": AuthenticationError,
"400004": AuthenticationError,
"400005": AuthenticationError,
"400006": AuthenticationError,
"400007": AuthenticationError,
"404000": NotSupported,
"400100": BadRequest,
"411100": AccountSuspended,
"500000": ExchangeNotAvailable,
"300009": InvalidOrder,
},
"broad": map[string]interface{} {
"Position does not exist": OrderNotFound,
},
},
"fees": map[string]interface{} {
"trading": map[string]interface{} {
"tierBased": true,
"percentage": true,
"taker": this.ParseNumber("0.0006"),
"maker": this.ParseNumber("0.0002"),
"tiers": map[string]interface{} {
"taker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.0006")}, []interface{}{this.ParseNumber("50"), this.ParseNumber("0.0006")}, []interface{}{this.ParseNumber("200"), this.ParseNumber("0.0006")}, []interface{}{this.ParseNumber("500"), this.ParseNumber("0.0005")}, []interface{}{this.ParseNumber("1000"), this.ParseNumber("0.0004")}, []interface{}{this.ParseNumber("2000"), this.ParseNumber("0.0004")}, []interface{}{this.ParseNumber("4000"), this.ParseNumber("0.00038")}, []interface{}{this.ParseNumber("8000"), this.ParseNumber("0.00035")}, []interface{}{this.ParseNumber("15000"), this.ParseNumber("0.00032")}, []interface{}{this.ParseNumber("25000"), this.ParseNumber("0.0003")}, []interface{}{this.ParseNumber("40000"), this.ParseNumber("0.0003")}, []interface{}{this.ParseNumber("60000"), this.ParseNumber("0.0003")}, []interface{}{this.ParseNumber("80000"), this.ParseNumber("0.0003")}},
"maker": []interface{}{[]interface{}{this.ParseNumber("0"), this.ParseNumber("0.02")}, []interface{}{this.ParseNumber("50"), this.ParseNumber("0.015")}, []interface{}{this.ParseNumber("200"), this.ParseNumber("0.01")}, []interface{}{this.ParseNumber("500"), this.ParseNumber("0.01")}, []interface{}{this.ParseNumber("1000"), this.ParseNumber("0.01")}, []interface{}{this.ParseNumber("2000"), this.ParseNumber("0")}, []interface{}{this.ParseNumber("4000"), this.ParseNumber("0")}, []interface{}{this.ParseNumber("8000"), this.ParseNumber("0")}, []interface{}{this.ParseNumber("15000"), this.ParseNumber("-0.003")}, []interface{}{this.ParseNumber("25000"), this.ParseNumber("-0.006")}, []interface{}{this.ParseNumber("40000"), this.ParseNumber("-0.009")}, []interface{}{this.ParseNumber("60000"), this.ParseNumber("-0.012")}, []interface{}{this.ParseNumber("80000"), this.ParseNumber("-0.015")}},
},
},
"funding": map[string]interface{} {
"tierBased": false,
"percentage": false,
"withdraw": map[string]interface{} {},
"deposit": map[string]interface{} {},
},
},
"commonCurrencies": map[string]interface{} {
"HOT": "HOTNOW",
"EDGE": "DADI",
"WAX": "WAXP",
"TRY": "Trias",
"VAI": "VAIOT",
"XBT": "BTC",
},
"timeframes": map[string]interface{} {
"1m": 1,
"3m": nil,
"5m": 5,
"15m": 15,
"30m": 30,
"1h": 60,
"2h": 120,
"4h": 240,
"6h": nil,
"8h": 480,
"12h": 720,
"1d": 1440,
"1w": 10080,
},
"options": map[string]interface{} {
"version": "v1",
"symbolSeparator": "-",
"defaultType": "swap",
"code": "USDT",
"marginModes": map[string]interface{} {},
"marginTypes": map[string]interface{} {},
"versions": map[string]interface{} {
"futuresPrivate": map[string]interface{} {
"GET": map[string]interface{} {
"getMaxOpenSize": "v2",
"getCrossUserLeverage": "v2",
"position/getMarginMode": "v2",
},
"POST": map[string]interface{} {
"transfer-out": "v2",
"changeCrossUserLeverage": "v2",
"position/changeMarginMode": "v2",
},
},
"futuresPublic": map[string]interface{} {
"GET": map[string]interface{} {
"level3/snapshot": "v2",
},
},
},
"networks": map[string]interface{} {
"OMNI": "omni",
"ERC20": "eth",
"TRC20": "trx",
},
},
"features": map[string]interface{} {
"spot": nil,
"forDerivs": map[string]interface{} {
"sandbox": false,
"createOrder": map[string]interface{} {
"marginMode": true,
"triggerPrice": true,
"triggerPriceType": map[string]interface{} {
"last": true,
"mark": true,
"index": true,
},
"triggerDirection": true,
"stopLossPrice": true,
"takeProfitPrice": true,
"attachedStopLossTakeProfit": map[string]interface{} {
"triggerPriceType": nil,
"price": true,
},
"timeInForce": map[string]interface{} {
"IOC": true,
"FOK": false,
"PO": true,
"GTD": false,
},
"hedged": false,
"trailing": false,
"leverage": true,
"marketBuyByCost": true,
"marketBuyRequiresPrice": false,
"selfTradePrevention": true,
"iceberg": true,
},
"createOrders": map[string]interface{} {
"max": 20,
},
"fetchMyTrades": map[string]interface{} {
"marginMode": true,
"limit": 1000,
"daysBack": nil,
"untilDays": 7,
"symbolRequired": false,
},
"fetchOrder": map[string]interface{} {
"marginMode": false,
"trigger": false,
"trailing": false,
"symbolRequired": false,
},
"fetchOpenOrders": map[string]interface{} {
"marginMode": false,
"limit": 1000,
"trigger": true,
"trailing": false,
"symbolRequired": false,
},
"fetchOrders": nil,
"fetchClosedOrders": map[string]interface{} {
"marginMode": false,
"limit": 1000,
"daysBack": nil,
"daysBackCanceled": nil,
"untilDays": nil,
"trigger": true,
"trailing": false,
"symbolRequired": false,
},
"fetchOHLCV": map[string]interface{} {
"limit": 500,
},
},
"swap": map[string]interface{} {
"linear": map[string]interface{} {
"extends": "forDerivs",
},
"inverse": map[string]interface{} {
"extends": "forDerivs",
},
},
"future": map[string]interface{} {
"linear": map[string]interface{} {
"extends": "forDerivs",
},
"inverse": map[string]interface{} {
"extends": "forDerivs",
},
},
},
})
}
/**
* @method
* @name kucoinfutures#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-service-status
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [status structure]{@link https://docs.ccxt.com/#/?id=exchange-status-structure}
*/
func (this *kucoinfutures) FetchStatus(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
response:= (<-this.FuturesPublicGetStatus(params))
PanicOnError(response)
//
// {
// "code":"200000",
// "data":{
// "status": "open", // open, close, cancelonly
// "msg": "upgrade match engine" // remark for operation when status not open
// }
// }
//
var data interface{} = this.SafeValue(response, "data", map[string]interface{} {})
var status interface{} = this.SafeString(data, "status")
ch <- map[string]interface{} {
"status": Ternary(IsTrue((IsEqual(status, "open"))), "ok", "maintenance"),
"updated": nil,
"eta": nil,
"url": nil,
"info": response,
}
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchMarkets
* @description retrieves data on all markets for kucoinfutures
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbols-list
* @param {object} [params] extra parameters specific to the exchange api endpoint
* @returns {object[]} an array of objects representing market data
*/
func (this *kucoinfutures) 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
response:= (<-this.FuturesPublicGetContractsActive(params))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "symbol": "ETHUSDTM",
// "rootSymbol": "USDT",
// "type": "FFWCSX",
// "firstOpenDate": 1591086000000,
// "expireDate": null,
// "settleDate": null,
// "baseCurrency": "ETH",
// "quoteCurrency": "USDT",
// "settleCurrency": "USDT",
// "maxOrderQty": 1000000,
// "maxPrice": 1000000.0000000000,
// "lotSize": 1,
// "tickSize": 0.05,
// "indexPriceTickSize": 0.01,
// "multiplier": 0.01,
// "initialMargin": 0.01,
// "maintainMargin": 0.005,
// "maxRiskLimit": 1000000,
// "minRiskLimit": 1000000,
// "riskStep": 500000,
// "makerFeeRate": 0.00020,
// "takerFeeRate": 0.00060,
// "takerFixFee": 0.0000000000,
// "makerFixFee": 0.0000000000,
// "settlementFee": null,
// "isDeleverage": true,
// "isQuanto": true,
// "isInverse": false,
// "markMethod": "FairPrice",
// "fairMethod": "FundingRate",
// "fundingBaseSymbol": ".ETHINT8H",
// "fundingQuoteSymbol": ".USDTINT8H",
// "fundingRateSymbol": ".ETHUSDTMFPI8H",
// "indexSymbol": ".KETHUSDT",
// "settlementSymbol": "",
// "status": "Open",
// "fundingFeeRate": 0.000535,
// "predictedFundingFeeRate": 0.002197,
// "openInterest": "8724443",
// "turnoverOf24h": 341156641.03354263,
// "volumeOf24h": 74833.54000000,
// "markPrice": 4534.07,
// "indexPrice":4531.92,
// "lastTradePrice": 4545.4500000000,
// "nextFundingRateTime": 25481884,
// "maxLeverage": 100,
// "sourceExchanges": [ "huobi", "Okex", "Binance", "Kucoin", "Poloniex", "Hitbtc" ],
// "premiumsSymbol1M": ".ETHUSDTMPI",
// "premiumsSymbol8H": ".ETHUSDTMPI8H",
// "fundingBaseSymbol1M": ".ETHINT",
// "fundingQuoteSymbol1M": ".USDTINT",
// "lowPrice": 4456.90,
// "highPrice": 4674.25,
// "priceChgPct": 0.0046,
// "priceChg": 21.15
// }
// }
//
var result interface{} = []interface{}{}
var data interface{} = this.SafeValue(response, "data", []interface{}{})
for i := 0; IsLessThan(i, GetArrayLength(data)); i++ {
var market interface{} = GetValue(data, i)
var id interface{} = this.SafeString(market, "symbol")
var expiry interface{} = this.SafeInteger(market, "expireDate")
var future interface{} = Ternary(IsTrue(expiry), true, false)
var swap interface{} = !IsTrue(future)
var baseId interface{} = this.SafeString(market, "baseCurrency")
var quoteId interface{} = this.SafeString(market, "quoteCurrency")
var settleId interface{} = this.SafeString(market, "settleCurrency")
var base interface{} = this.SafeCurrencyCode(baseId)
var quote interface{} = this.SafeCurrencyCode(quoteId)
var settle interface{} = this.SafeCurrencyCode(settleId)
var symbol interface{} = Add(Add(Add(Add(base, "/"), quote), ":"), settle)
var typeVar interface{} = "swap"
if IsTrue(future) {
symbol = Add(Add(symbol, "-"), this.Yymmdd(expiry, ""))
typeVar = "future"
}
var inverse interface{} = this.SafeValue(market, "isInverse")
var status interface{} = this.SafeString(market, "status")
var multiplier interface{} = this.SafeString(market, "multiplier")
var tickSize interface{} = this.SafeNumber(market, "tickSize")
var lotSize interface{} = this.SafeNumber(market, "lotSize")
var limitAmountMin interface{} = lotSize
if IsTrue(IsEqual(limitAmountMin, nil)) {
limitAmountMin = this.SafeNumber(market, "baseMinSize")
}
var limitAmountMax interface{} = this.SafeNumber(market, "maxOrderQty")
if IsTrue(IsEqual(limitAmountMax, nil)) {
limitAmountMax = this.SafeNumber(market, "baseMaxSize")
}
var limitPriceMax interface{} = this.SafeNumber(market, "maxPrice")
if IsTrue(IsEqual(limitPriceMax, nil)) {
var baseMinSizeString interface{} = this.SafeString(market, "baseMinSize")
var quoteMaxSizeString interface{} = this.SafeString(market, "quoteMaxSize")
limitPriceMax = this.ParseNumber(Precise.StringDiv(quoteMaxSizeString, baseMinSizeString))
}
AppendToArray(&result,map[string]interface{} {
"id": id,
"symbol": symbol,
"base": base,
"quote": quote,
"settle": settle,
"baseId": baseId,
"quoteId": quoteId,
"settleId": settleId,
"type": typeVar,
"spot": false,
"margin": false,
"swap": swap,
"future": future,
"option": false,
"active": (IsEqual(status, "Open")),
"contract": true,
"linear": !IsTrue(inverse),
"inverse": inverse,
"taker": this.SafeNumber(market, "takerFeeRate"),
"maker": this.SafeNumber(market, "makerFeeRate"),
"contractSize": this.ParseNumber(Precise.StringAbs(multiplier)),
"expiry": expiry,
"expiryDatetime": this.Iso8601(expiry),
"strike": nil,
"optionType": nil,
"precision": map[string]interface{} {
"amount": lotSize,
"price": tickSize,
},
"limits": map[string]interface{} {
"leverage": map[string]interface{} {
"min": this.ParseNumber("1"),
"max": this.SafeNumber(market, "maxLeverage"),
},
"amount": map[string]interface{} {
"min": limitAmountMin,
"max": limitAmountMax,
},
"price": map[string]interface{} {
"min": tickSize,
"max": limitPriceMax,
},
"cost": map[string]interface{} {
"min": this.SafeNumber(market, "quoteMinSize"),
"max": this.SafeNumber(market, "quoteMaxSize"),
},
},
"created": this.SafeInteger(market, "firstOpenDate"),
"info": market,
})
}
ch <- result
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-server-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 *kucoinfutures) 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.FuturesPublicGetTimestamp(params))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": 1637385119302,
// }
//
ch <- this.SafeInteger(response, "data")
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-klines
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {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
*/
func (this *kucoinfutures) 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
retRes6818 := (<-this.LoadMarkets())
PanicOnError(retRes6818)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOHLCV", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes68519 := (<-this.FetchPaginatedCallDeterministic("fetchOHLCV", symbol, since, limit, timeframe, params, 200))
PanicOnError(retRes68519)
ch <- retRes68519
return nil
}
var market interface{} = this.Market(symbol)
var marketId interface{} = GetValue(market, "id")
var parsedTimeframe interface{} = this.SafeInteger(this.Timeframes, timeframe)
var request interface{} = map[string]interface{} {
"symbol": marketId,
}
if IsTrue(!IsEqual(parsedTimeframe, nil)) {
AddElementToObject(request, "granularity", parsedTimeframe)
} else {
AddElementToObject(request, "granularity", timeframe)
}
var duration interface{} = Multiply(this.ParseTimeframe(timeframe), 1000)
var endAt interface{} = this.Milliseconds()
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "from", since)
if IsTrue(IsEqual(limit, nil)) {
limit = this.SafeInteger(this.Options, "fetchOHLCVLimit", 200)
}
endAt = this.Sum(since, Multiply(limit, duration))
} else if IsTrue(!IsEqual(limit, nil)) {
since = Subtract(endAt, Multiply(limit, duration))
AddElementToObject(request, "from", since)
}
AddElementToObject(request, "to", endAt)
response:= (<-this.FuturesPublicGetKlineQuery(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": [
// [1636459200000, 4779.3, 4792.1, 4768.7, 4770.3, 78051],
// [1636460100000, 4770.25, 4778.55, 4757.55, 4777.25, 80164],
// [1636461000000, 4777.25, 4791.45, 4774.5, 4791.3, 51555]
// ]
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseOHLCVs(data, market, timeframe, since, limit)
return nil
}()
return ch
}
func (this *kucoinfutures) ParseOHLCV(ohlcv interface{}, optionalArgs ...interface{}) interface{} {
//
// [
// "1545904980000", // Start time of the candle cycle
// "0.058", // opening price
// "0.049", // closing price
// "0.058", // highest price
// "0.049", // lowest price
// "0.018", // base volume
// "0.000945", // quote volume
// ]
//
market := GetArg(optionalArgs, 0, nil)
_ = market
return []interface{}{this.SafeInteger(ohlcv, 0), this.SafeNumber(ohlcv, 1), this.SafeNumber(ohlcv, 2), this.SafeNumber(ohlcv, 3), this.SafeNumber(ohlcv, 4), this.SafeNumber(ohlcv, 5)}
}
/**
* @method
* @name kucoinfutures#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://www.kucoin.com/docs/rest/funding/deposit/get-deposit-address
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [address structure]{@link https://docs.ccxt.com/#/?id=address-structure}
*/
func (this *kucoinfutures) 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
retRes7588 := (<-this.LoadMarkets())
PanicOnError(retRes7588)
var currency interface{} = this.Currency(code)
var currencyId interface{} = GetValue(currency, "id")
var request interface{} = map[string]interface{} {
"currency": currencyId,
}
response:= (<-this.FuturesPrivateGetDepositAddress(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "address": "0x78d3ad1c0aa1bf068e19c94a2d7b16c9c0fcd8b1",//Deposit address
// "memo": null//Address tag. If the returned value is null, it means that the requested token has no memo. If you are to transfer funds from another platform to KuCoin Futures and if the token to be //transferred has memo(tag), you need to fill in the memo to ensure the transferred funds will be sent //to the address you specified.
// }
// }
//
var data interface{} = this.SafeValue(response, "data", map[string]interface{} {})
var address interface{} = this.SafeString(data, "address")
if IsTrue(!IsEqual(currencyId, "NIM")) {
// contains spaces
this.CheckAddress(address)
}
ch <- map[string]interface{} {
"info": response,
"currency": currencyId,
"network": this.SafeString(data, "chain"),
"address": address,
"tag": this.SafeString(data, "memo"),
}
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-part-order-book-level-2
* @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 *kucoinfutures) 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
retRes8008 := (<-this.LoadMarkets())
PanicOnError(retRes8008)
var level interface{} = this.SafeNumber(params, "level")
if IsTrue(IsTrue(!IsEqual(level, 2)) && IsTrue(!IsEqual(level, nil))) {
panic(BadRequest(Add(this.Id, " fetchOrderBook() can only return level 2")))
}
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
if IsTrue(!IsEqual(limit, nil)) {
if IsTrue(IsTrue((IsEqual(limit, 20))) || IsTrue((IsEqual(limit, 100)))) {
AddElementToObject(request, "limit", limit)
} else {
panic(BadRequest(Add(this.Id, " fetchOrderBook() limit argument must be 20 or 100")))
}
} else {
AddElementToObject(request, "limit", 20)
}
response:= (<-this.FuturesPublicGetLevel2DepthLimit(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "symbol": "XBTUSDM", //Symbol
// "sequence": 100, //Ticker sequence number
// "asks": [
// ["5000.0", 1000], //Price, quantity
// ["6000.0", 1983] //Price, quantity
// ],
// "bids": [
// ["3200.0", 800], //Price, quantity
// ["3100.0", 100] //Price, quantity
// ],
// "ts": 1604643655040584408 // timestamp
// }
// }
//
var data interface{} = this.SafeValue(response, "data", map[string]interface{} {})
var timestamp interface{} = this.ParseToInt(Divide(this.SafeInteger(data, "ts"), 1000000))
var orderbook interface{} = this.ParseOrderBook(data, GetValue(market, "symbol"), timestamp, "bids", "asks", 0, 1)
AddElementToObject(orderbook, "nonce", this.SafeInteger(data, "sequence"))
ch <- orderbook
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#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.kucoin.com/docs/rest/futures-trading/market-data/get-ticker
* @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 *kucoinfutures) 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
retRes8548 := (<-this.LoadMarkets())
PanicOnError(retRes8548)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.FuturesPublicGetTicker(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "sequence": 1638444978558,
// "symbol": "ETHUSDTM",
// "side": "sell",
// "size": 4,
// "price": "4229.35",
// "bestBidSize": 2160,
// "bestBidPrice": "4229.0",
// "bestAskPrice": "4229.05",
// "tradeId": "61aaa8b777a0c43055fe4851",
// "ts": 1638574296209786785,
// "bestAskSize": 36,
// }
// }
//
ch <- this.ParseTicker(GetValue(response, "data"), market)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchMarkPrice
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-current-mark-price
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [ticker structure]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *kucoinfutures) FetchMarkPrice(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes8918 := (<-this.LoadMarkets())
PanicOnError(retRes8918)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.FuturesPublicGetMarkPriceSymbolCurrent(this.Extend(request, params)))
PanicOnError(response)
//
ch <- this.ParseTicker(GetValue(response, "data"), market)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-symbols-list
* @param {string[]} [symbols] unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.method] the method to use, futuresPublicGetAllTickers or futuresPublicGetContractsActive
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *kucoinfutures) 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
retRes9128 := (<-this.LoadMarkets())
PanicOnError(retRes9128)
symbols = this.MarketSymbols(symbols)
var method interface{} = nil
methodparamsVariable := this.HandleOptionAndParams(params, "fetchTickers", "method", "futuresPublicGetContractsActive");
method = GetValue(methodparamsVariable,0);
params = GetValue(methodparamsVariable,1)
var response interface{} = nil
if IsTrue(IsEqual(method, "futuresPublicGetAllTickers")) {
response = (<-this.FuturesPublicGetAllTickers(params))
PanicOnError(response)
} else {
response = (<-this.FuturesPublicGetContractsActive(params))
PanicOnError(response)
}
//
// {
// "code": "200000",
// "data": {
// "symbol": "ETHUSDTM",
// "rootSymbol": "USDT",
// "type": "FFWCSX",
// "firstOpenDate": 1591086000000,
// "expireDate": null,
// "settleDate": null,
// "baseCurrency": "ETH",
// "quoteCurrency": "USDT",
// "settleCurrency": "USDT",
// "maxOrderQty": 1000000,
// "maxPrice": 1000000.0000000000,
// "lotSize": 1,
// "tickSize": 0.05,
// "indexPriceTickSize": 0.01,
// "multiplier": 0.01,
// "initialMargin": 0.01,
// "maintainMargin": 0.005,
// "maxRiskLimit": 1000000,
// "minRiskLimit": 1000000,
// "riskStep": 500000,
// "makerFeeRate": 0.00020,
// "takerFeeRate": 0.00060,
// "takerFixFee": 0.0000000000,
// "makerFixFee": 0.0000000000,
// "settlementFee": null,
// "isDeleverage": true,
// "isQuanto": true,
// "isInverse": false,
// "markMethod": "FairPrice",
// "fairMethod": "FundingRate",
// "fundingBaseSymbol": ".ETHINT8H",
// "fundingQuoteSymbol": ".USDTINT8H",
// "fundingRateSymbol": ".ETHUSDTMFPI8H",
// "indexSymbol": ".KETHUSDT",
// "settlementSymbol": "",
// "status": "Open",
// "fundingFeeRate": 0.000535,
// "predictedFundingFeeRate": 0.002197,
// "openInterest": "8724443",
// "turnoverOf24h": 341156641.03354263,
// "volumeOf24h": 74833.54000000,
// "markPrice": 4534.07,
// "indexPrice":4531.92,
// "lastTradePrice": 4545.4500000000,
// "nextFundingRateTime": 25481884,
// "maxLeverage": 100,
// "sourceExchanges": [ "huobi", "Okex", "Binance", "Kucoin", "Poloniex", "Hitbtc" ],
// "premiumsSymbol1M": ".ETHUSDTMPI",
// "premiumsSymbol8H": ".ETHUSDTMPI8H",
// "fundingBaseSymbol1M": ".ETHINT",
// "fundingQuoteSymbol1M": ".USDTINT",
// "lowPrice": 4456.90,
// "highPrice": 4674.25,
// "priceChgPct": 0.0046,
// "priceChg": 21.15
// }
// }
//
var data interface{} = this.SafeList(response, "data")
var tickers interface{} = this.ParseTickers(data, symbols)
ch <- this.FilterByArrayTickers(tickers, "symbol", symbols)
return nil
}()
return ch
}
func (this *kucoinfutures) ParseTicker(ticker interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "symbol": "LTCUSDTM",
// "granularity": 1000,
// "timePoint": 1727967339000,
// "value": 62.37, mark price
// "indexPrice": 62.37
// }
//
// {
// "code": "200000",
// "data": {
// "sequence": 1629930362547,
// "symbol": "ETHUSDTM",
// "side": "buy",
// "size": 130,
// "price": "4724.7",
// "bestBidSize": 5,
// "bestBidPrice": "4724.6",
// "bestAskPrice": "4724.65",
// "tradeId": "618d2a5a77a0c4431d2335f4",
// "ts": 1636641371963227600,
// "bestAskSize": 1789
// }
// }
//
// from fetchTickers
//
// {
// symbol: "XBTUSDTM",
// rootSymbol: "USDT",
// type: "FFWCSX",
// firstOpenDate: 1585555200000,
// expireDate: null,
// settleDate: null,
// baseCurrency: "XBT",
// quoteCurrency: "USDT",
// settleCurrency: "USDT",
// maxOrderQty: 1000000,
// maxPrice: 1000000,
// lotSize: 1,
// tickSize: 0.1,
// indexPriceTickSize: 0.01,
// multiplier: 0.001,
// initialMargin: 0.008,
// maintainMargin: 0.004,
// maxRiskLimit: 100000,
// minRiskLimit: 100000,
// riskStep: 50000,
// makerFeeRate: 0.0002,
// takerFeeRate: 0.0006,
// takerFixFee: 0,
// makerFixFee: 0,
// settlementFee: null,
// isDeleverage: true,
// isQuanto: true,
// isInverse: false,
// markMethod: "FairPrice",
// fairMethod: "FundingRate",
// fundingBaseSymbol: ".XBTINT8H",
// fundingQuoteSymbol: ".USDTINT8H",
// fundingRateSymbol: ".XBTUSDTMFPI8H",
// indexSymbol: ".KXBTUSDT",
// settlementSymbol: "",
// status: "Open",
// fundingFeeRate: 0.000297,
// predictedFundingFeeRate: 0.000327,
// fundingRateGranularity: 28800000,
// openInterest: "8033200",
// turnoverOf24h: 659795309.2524643,
// volumeOf24h: 9998.54,
// markPrice: 67193.51,
// indexPrice: 67184.81,
// lastTradePrice: 67191.8,
// nextFundingRateTime: 20022985,
// maxLeverage: 125,
// premiumsSymbol1M: ".XBTUSDTMPI",
// premiumsSymbol8H: ".XBTUSDTMPI8H",
// fundingBaseSymbol1M: ".XBTINT",
// fundingQuoteSymbol1M: ".USDTINT",
// lowPrice: 64041.6,
// highPrice: 67737.3,
// priceChgPct: 0.0447,
// priceChg: 2878.7
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(ticker, "symbol")
market = this.SafeMarket(marketId, market, "-")
var last interface{} = this.SafeString2(ticker, "price", "lastTradePrice")
var timestamp interface{} = this.SafeIntegerProduct(ticker, "ts", 0.000001)
return this.SafeTicker(map[string]interface{} {
"symbol": GetValue(market, "symbol"),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"high": this.SafeString(ticker, "highPrice"),
"low": this.SafeString(ticker, "lowPrice"),
"bid": this.SafeString(ticker, "bestBidPrice"),
"bidVolume": this.SafeString(ticker, "bestBidSize"),
"ask": this.SafeString(ticker, "bestAskPrice"),
"askVolume": this.SafeString(ticker, "bestAskSize"),
"vwap": nil,
"open": nil,
"close": last,
"last": last,
"previousClose": nil,
"change": this.SafeString(ticker, "priceChg"),
"percentage": this.SafeString(ticker, "priceChgPct"),
"average": nil,
"baseVolume": this.SafeString(ticker, "volumeOf24h"),
"quoteVolume": this.SafeString(ticker, "turnoverOf24h"),
"markPrice": this.SafeString2(ticker, "markPrice", "value"),
"indexPrice": this.SafeString(ticker, "indexPrice"),
"info": ticker,
}, market)
}
/**
* @method
* @name kucoinfutures#fetchBidsAsks
* @description fetches the bid and ask price and volume for multiple markets
* @param {string[]} [symbols] unified symbols of the markets to fetch the bids and asks for, all markets are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *kucoinfutures) FetchBidsAsks(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbols := GetArg(optionalArgs, 0, nil)
_ = symbols
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
var request interface{} = map[string]interface{} {
"method": "futuresPublicGetAllTickers",
}
retRes111815 := (<-this.FetchTickers(symbols, this.Extend(request, params)))
PanicOnError(retRes111815)
ch <- retRes111815
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchFundingHistory
* @description fetch the history of funding payments paid and received on this account
* @see https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-funding-history
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch funding history for
* @param {int} [limit] the maximum number of funding history structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding history structure]{@link https://docs.ccxt.com/#/?id=funding-history-structure}
*/
func (this *kucoinfutures) 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
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchFundingHistory() requires a symbol argument")))
}
retRes11368 := (<-this.LoadMarkets())
PanicOnError(retRes11368)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startAt", since)
}
if IsTrue(!IsEqual(limit, nil)) {
// * Since is ignored if limit is defined
AddElementToObject(request, "maxCount", limit)
}
response:= (<-this.FuturesPrivateGetFundingHistory(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "dataList": [
// {
// "id": 239471298749817,
// "symbol": "ETHUSDTM",
// "timePoint": 1638532800000,
// "fundingRate": 0.000100,
// "markPrice": 4612.8300000000,
// "positionQty": 12,
// "positionCost": 553.5396000000,
// "funding": -0.0553539600,
// "settleCurrency": "USDT"
// },
// ...
// ],
// "hasMore": true
// }
// }
//
var data interface{} = this.SafeValue(response, "data")
var dataList interface{} = this.SafeValue(data, "dataList", []interface{}{})
var fees interface{} = []interface{}{}
for i := 0; IsLessThan(i, GetArrayLength(dataList)); i++ {
var listItem interface{} = GetValue(dataList, i)
var timestamp interface{} = this.SafeInteger(listItem, "timePoint")
AppendToArray(&fees,map[string]interface{} {
"info": listItem,
"symbol": symbol,
"code": this.SafeCurrencyCode(this.SafeString(listItem, "settleCurrency")),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"id": this.SafeNumber(listItem, "id"),
"amount": this.SafeNumber(listItem, "funding"),
"fundingRate": this.SafeNumber(listItem, "fundingRate"),
"markPrice": this.SafeNumber(listItem, "markPrice"),
"positionQty": this.SafeNumber(listItem, "positionQty"),
"positionCost": this.SafeNumber(listItem, "positionCost"),
})
}
ch <- fees
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchPosition
* @see https://docs.kucoin.com/futures/#get-position-details
* @description fetch data on an open 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 *kucoinfutures) 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
retRes12048 := (<-this.LoadMarkets())
PanicOnError(retRes12048)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.FuturesPrivateGetPosition(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "id": "6505ee6eaff4070001f651c4",
// "symbol": "XBTUSDTM",
// "autoDeposit": false,
// "maintMarginReq": 0,
// "riskLimit": 200,
// "realLeverage": 0.0,
// "crossMode": false,
// "delevPercentage": 0.0,
// "currentTimestamp": 1694887534594,
// "currentQty": 0,
// "currentCost": 0.0,
// "currentComm": 0.0,
// "unrealisedCost": 0.0,
// "realisedGrossCost": 0.0,
// "realisedCost": 0.0,
// "isOpen": false,
// "markPrice": 26611.71,
// "markValue": 0.0,
// "posCost": 0.0,
// "posCross": 0,
// "posInit": 0.0,
// "posComm": 0.0,
// "posLoss": 0.0,
// "posMargin": 0.0,
// "posMaint": 0.0,
// "maintMargin": 0.0,
// "realisedGrossPnl": 0.0,
// "realisedPnl": 0.0,
// "unrealisedPnl": 0.0,
// "unrealisedPnlPcnt": 0,
// "unrealisedRoePcnt": 0,
// "avgEntryPrice": 0.0,
// "liquidationPrice": 0.0,
// "bankruptPrice": 0.0,
// "settleCurrency": "USDT",
// "maintainMargin": 0,
// "riskLimitLevel": 1
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
ch <- this.ParsePosition(data, market)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchPositions
* @description fetch all open positions
* @see https://docs.kucoin.com/futures/#get-position-list
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *kucoinfutures) 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
retRes12688 := (<-this.LoadMarkets())
PanicOnError(retRes12688)
response:= (<-this.FuturesPrivateGetPositions(params))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": [
// {
// "id": "615ba79f83a3410001cde321",
// "symbol": "ETHUSDTM",
// "autoDeposit": false,
// "maintMarginReq": 0.005,
// "riskLimit": 1000000,
// "realLeverage": 18.61,
// "crossMode": false,
// "delevPercentage": 0.86,
// "openingTimestamp": 1638563515618,
// "currentTimestamp": 1638576872774,
// "currentQty": 2,
// "currentCost": 83.64200000,
// "currentComm": 0.05018520,
// "unrealisedCost": 83.64200000,
// "realisedGrossCost": 0.00000000,
// "realisedCost": 0.05018520,
// "isOpen": true,
// "markPrice": 4225.01,
// "markValue": 84.50020000,
// "posCost": 83.64200000,
// "posCross": 0.0000000000,
// "posInit": 3.63660870,
// "posComm": 0.05236717,
// "posLoss": 0.00000000,
// "posMargin": 3.68897586,
// "posMaint": 0.50637594,
// "maintMargin": 4.54717586,
// "realisedGrossPnl": 0.00000000,
// "realisedPnl": -0.05018520,
// "unrealisedPnl": 0.85820000,
// "unrealisedPnlPcnt": 0.0103,
// "unrealisedRoePcnt": 0.2360,
// "avgEntryPrice": 4182.10,
// "liquidationPrice": 4023.00,
// "bankruptPrice": 4000.25,
// "settleCurrency": "USDT",
// "isInverse": false
// }
// ]
// }
//
var data interface{} = this.SafeList(response, "data")
ch <- this.ParsePositions(data, symbols)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchPositionsHistory
* @description fetches historical positions
* @see https://www.kucoin.com/docs/rest/futures-trading/positions/get-positions-history
* @param {string[]} [symbols] list of unified market symbols
* @param {int} [since] the earliest time in ms to fetch position history for
* @param {int} [limit] the maximum number of entries to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] closing end time
* @param {int} [params.pageId] page id
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *kucoinfutures) 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
retRes13348 := (<-this.LoadMarkets())
PanicOnError(retRes13348)
if IsTrue(IsEqual(limit, nil)) {
limit = 200
}
var request interface{} = map[string]interface{} {
"limit": limit,
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "from", since)
}
var until interface{} = this.SafeInteger(params, "until")
if IsTrue(!IsEqual(until, nil)) {
params = this.Omit(params, "until")
AddElementToObject(request, "to", until)
}
response:= (<-this.FuturesPrivateGetHistoryPositions(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "success": true,
// "code": "200",
// "msg": "success",
// "retry": false,
// "data": {
// "currentPage": 1,
// "pageSize": 10,
// "totalNum": 25,
// "totalPage": 3,
// "items": [
// {
// "closeId": "300000000000000030",
// "positionId": "300000000000000009",
// "uid": 99996908309485,
// "userId": "6527d4fc8c7f3d0001f40f5f",
// "symbol": "XBTUSDM",
// "settleCurrency": "XBT",
// "leverage": "0.0",
// "type": "LIQUID_LONG",
// "side": null,
// "closeSize": null,
// "pnl": "-1.0000003793999999",
// "realisedGrossCost": "0.9993849748999999",
// "withdrawPnl": "0.0",
// "roe": null,
// "tradeFee": "0.0006154045",
// "fundingFee": "0.0",
// "openTime": 1713785751181,
// "closeTime": 1713785752784,
// "openPrice": null,
// "closePrice": null
// }
// ]
// }
// }
//
var data interface{} = this.SafeDict(response, "data")
var items interface{} = this.SafeList(data, "items", []interface{}{})
ch <- this.ParsePositions(items, symbols)
return nil
}()
return ch
}
func (this *kucoinfutures) ParsePosition(position interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "code": "200000",
// "data": [
// {
// "id": "615ba79f83a3410001cde321", // Position ID
// "symbol": "ETHUSDTM", // Symbol
// "autoDeposit": false, // Auto deposit margin or not
// "maintMarginReq": 0.005, // Maintenance margin requirement
// "riskLimit": 1000000, // Risk limit
// "realLeverage": 25.92, // Leverage of the order
// "crossMode": false, // Cross mode or not
// "delevPercentage": 0.76, // ADL ranking percentile
// "openingTimestamp": 1638578546031, // Open time
// "currentTimestamp": 1638578563580, // Current timestamp
// "currentQty": 2, // Current postion quantity
// "currentCost": 83.787, // Current postion value
// "currentComm": 0.0167574, // Current commission
// "unrealisedCost": 83.787, // Unrealised value
// "realisedGrossCost": 0.0, // Accumulated realised gross profit value
// "realisedCost": 0.0167574, // Current realised position value
// "isOpen": true, // Opened position or not
// "markPrice": 4183.38, // Mark price
// "markValue": 83.6676, // Mark value
// "posCost": 83.787, // Position value
// "posCross": 0.0, // added margin
// "posInit": 3.35148, // Leverage margin
// "posComm": 0.05228309, // Bankruptcy cost
// "posLoss": 0.0, // Funding fees paid out
// "posMargin": 3.40376309, // Position margin
// "posMaint": 0.50707892, // Maintenance margin
// "maintMargin": 3.28436309, // Position margin
// "realisedGrossPnl": 0.0, // Accumulated realised gross profit value
// "realisedPnl": -0.0167574, // Realised profit and loss
// "unrealisedPnl": -0.1194, // Unrealised profit and loss
// "unrealisedPnlPcnt": -0.0014, // Profit-loss ratio of the position
// "unrealisedRoePcnt": -0.0356, // Rate of return on investment
// "avgEntryPrice": 4189.35, // Average entry price
// "liquidationPrice": 4044.55, // Liquidation price
// "bankruptPrice": 4021.75, // Bankruptcy price
// "settleCurrency": "USDT", // Currency used to clear and settle the trades
// "isInverse": false
// }
// ]
// }
// position history
// {
// "closeId": "300000000000000030",
// "positionId": "300000000000000009",
// "uid": 99996908309485,
// "userId": "6527d4fc8c7f3d0001f40f5f",
// "symbol": "XBTUSDM",
// "settleCurrency": "XBT",
// "leverage": "0.0",
// "type": "LIQUID_LONG",
// "side": null,
// "closeSize": null,
// "pnl": "-1.0000003793999999",
// "realisedGrossCost": "0.9993849748999999",
// "withdrawPnl": "0.0",
// "roe": null,
// "tradeFee": "0.0006154045",
// "fundingFee": "0.0",
// "openTime": 1713785751181,
// "closeTime": 1713785752784,
// "openPrice": null,
// "closePrice": null
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var symbol interface{} = this.SafeString(position, "symbol")
market = this.SafeMarket(symbol, market)
var timestamp interface{} = this.SafeInteger(position, "currentTimestamp")
var size interface{} = this.SafeString(position, "currentQty")
var side interface{} = nil
var typeVar interface{} = this.SafeStringLower(position, "type")
if IsTrue(!IsEqual(size, nil)) {
if IsTrue(Precise.StringGt(size, "0")) {
side = "long"
} else if IsTrue(Precise.StringLt(size, "0")) {
side = "short"
}
} else if IsTrue(!IsEqual(typeVar, nil)) {
if IsTrue(IsGreaterThan(GetIndexOf(typeVar, "long"), OpNeg(1))) {
side = "long"
} else {
side = "short"
}
}
var notional interface{} = Precise.StringAbs(this.SafeString(position, "posCost"))
var initialMargin interface{} = this.SafeString(position, "posInit")
var initialMarginPercentage interface{} = Precise.StringDiv(initialMargin, notional)
// const marginRatio = Precise.stringDiv (maintenanceRate, collateral);
var unrealisedPnl interface{} = this.SafeString(position, "unrealisedPnl")
var crossMode interface{} = this.SafeValue(position, "crossMode")
// currently crossMode is always set to false and only isolated positions are supported
var marginMode interface{} = nil
if IsTrue(!IsEqual(crossMode, nil)) {
marginMode = Ternary(IsTrue(crossMode), "cross", "isolated")
}
return this.SafePosition(map[string]interface{} {
"info": position,
"id": this.SafeString2(position, "id", "positionId"),
"symbol": this.SafeString(market, "symbol"),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"lastUpdateTimestamp": this.SafeInteger(position, "closeTime"),
"initialMargin": this.ParseNumber(initialMargin),
"initialMarginPercentage": this.ParseNumber(initialMarginPercentage),
"maintenanceMargin": this.SafeNumber(position, "posMaint"),
"maintenanceMarginPercentage": this.SafeNumber(position, "maintMarginReq"),
"entryPrice": this.SafeNumber2(position, "avgEntryPrice", "openPrice"),
"notional": this.ParseNumber(notional),
"leverage": this.SafeNumber2(position, "realLeverage", "leverage"),
"unrealizedPnl": this.ParseNumber(unrealisedPnl),
"contracts": this.ParseNumber(Precise.StringAbs(size)),
"contractSize": this.SafeValue(market, "contractSize"),
"realizedPnl": this.SafeNumber2(position, "realisedPnl", "pnl"),
"marginRatio": nil,
"liquidationPrice": this.SafeNumber(position, "liquidationPrice"),
"markPrice": this.SafeNumber(position, "markPrice"),
"lastPrice": nil,
"collateral": this.SafeNumber(position, "maintMargin"),
"marginMode": marginMode,
"side": side,
"percentage": nil,
"stopLossPrice": nil,
"takeProfitPrice": nil,
})
}
/**
* @method
* @name kucoinfutures#createOrder
* @description Create an order on the exchange
* @see https://www.kucoin.com/docs/rest/futures-trading/orders/place-order
* @see https://www.kucoin.com/docs/rest/futures-trading/orders/place-take-profit-and-stop-loss-order#http-request
* @param {string} symbol Unified CCXT market symbol
* @param {string} type 'limit' or 'market'
* @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 {object} [params.takeProfit] *takeProfit object in params* containing the triggerPrice at which the attached take profit order will be triggered and the triggerPriceType
* @param {object} [params.stopLoss] *stopLoss object in params* containing the triggerPrice at which the attached stop loss order will be triggered and the triggerPriceType
* @param {float} [params.triggerPrice] The price a trigger order is triggered at
* @param {float} [params.stopLossPrice] price to trigger stop-loss orders
* @param {float} [params.takeProfitPrice] price to trigger take-profit orders
* @param {bool} [params.reduceOnly] A mark to reduce the position size only. Set to false by default. Need to set the position size when reduceOnly is true.
* @param {string} [params.timeInForce] GTC, GTT, IOC, or FOK, default is GTC, limit orders only
* @param {string} [params.postOnly] Post only flag, invalid when timeInForce is IOC or FOK
* @param {float} [params.cost] the cost of the order in units of USDT
* ----------------- Exchange Specific Parameters -----------------
* @param {float} [params.leverage] Leverage size of the order (mandatory param in request, default is 1)
* @param {string} [params.clientOid] client order id, defaults to uuid if not passed
* @param {string} [params.remark] remark for the order, length cannot exceed 100 utf8 characters
* @param {string} [params.stop] 'up' or 'down', the direction the triggerPrice is triggered from, requires triggerPrice. down: Triggers when the price reaches or goes below the triggerPrice. up: Triggers when the price reaches or goes above the triggerPrice.
* @param {string} [params.triggerPriceType] "last", "mark", "index" - defaults to "mark"
* @param {string} [params.stopPriceType] exchange-specific alternative for triggerPriceType: TP, IP or MP
* @param {bool} [params.closeOrder] set to true to close position
* @param {bool} [params.test] set to true to use the test order endpoint (does not submit order, use to validate params)
* @param {bool} [params.forceHold] A mark to forcely hold the funds for an order, even though it's an order to reduce the position size. This helps the order stay on the order book and not get canceled when the position size changes. Set to false by default.
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *kucoinfutures) 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
retRes15588 := (<-this.LoadMarkets())
PanicOnError(retRes15588)
var market interface{} = this.Market(symbol)
var testOrder interface{} = this.SafeBool(params, "test", false)
params = this.Omit(params, "test")
var isTpAndSlOrder interface{} = IsTrue((!IsEqual(this.SafeValue(params, "stopLoss"), nil))) || IsTrue((!IsEqual(this.SafeValue(params, "takeProfit"), nil)))
var orderRequest interface{} = this.CreateContractOrderRequest(symbol, typeVar, side, amount, price, params)
var response interface{} = nil
if IsTrue(testOrder) {
response = (<-this.FuturesPrivatePostOrdersTest(orderRequest))
PanicOnError(response)
} else {
if IsTrue(isTpAndSlOrder) {
response = (<-this.FuturesPrivatePostStOrders(orderRequest))
PanicOnError(response)
} else {
response = (<-this.FuturesPrivatePostOrders(orderRequest))
PanicOnError(response)
}
}
//
// {
// "code": "200000",
// "data": {
// "orderId": "619717484f1d010001510cde",
// },
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
ch <- this.ParseOrder(data, market)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#createOrders
* @description create a list of trade orders
* @see https://www.kucoin.com/docs/rest/futures-trading/orders/place-multiple-orders
* @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *kucoinfutures) 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
retRes15968 := (<-this.LoadMarkets())
PanicOnError(retRes15968)
var ordersRequests interface{} = []interface{}{}
for i := 0; IsLessThan(i, GetArrayLength(orders)); i++ {
var rawOrder interface{} = GetValue(orders, i)
var symbol interface{} = this.SafeString(rawOrder, "symbol")
var market interface{} = this.Market(symbol)
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 orderRequest interface{} = this.CreateContractOrderRequest(GetValue(market, "id"), typeVar, side, amount, price, orderParams)
AppendToArray(&ordersRequests,orderRequest)
}
response:= (<-this.FuturesPrivatePostOrdersMulti(ordersRequests))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": [
// {
// "orderId": "135241412609331200",
// "clientOid": "3d8fcc13-0b13-447f-ad30-4b3441e05213",
// "symbol": "LTCUSDTM",
// "code": "200000",
// "msg": "success"
// },
// {
// "orderId": "135241412747743234",
// "clientOid": "b878c7ee-ae3e-4d63-a20b-038acbb7306f",
// "symbol": "LTCUSDTM",
// "code": "200000",
// "msg": "success"
// }
// ]
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseOrders(data)
return nil
}()
return ch
}
func (this *kucoinfutures) CreateContractOrderRequest(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)
// required param, cannot be used twice
var clientOrderId interface{} = this.SafeString2(params, "clientOid", "clientOrderId", this.Uuid())
params = this.Omit(params, []interface{}{"clientOid", "clientOrderId"})
var request interface{} = map[string]interface{} {
"clientOid": clientOrderId,
"side": side,
"symbol": GetValue(market, "id"),
"type": typeVar,
"leverage": 1,
}
var cost interface{} = this.SafeString(params, "cost")
params = this.Omit(params, "cost")
if IsTrue(!IsEqual(cost, nil)) {
AddElementToObject(request, "valueQty", this.CostToPrecision(symbol, cost))
} else {
if IsTrue(IsLessThan(amount, 1)) {
panic(InvalidOrder(Add(this.Id, " createOrder() minimum contract order amount is 1")))
}
AddElementToObject(request, "size", ParseInt(this.AmountToPrecision(symbol, amount)))
}
triggerPricestopLossPricetakeProfitPriceVariable := this.HandleTriggerPrices(params);
triggerPrice := GetValue(triggerPricestopLossPricetakeProfitPriceVariable,0);
stopLossPrice := GetValue(triggerPricestopLossPricetakeProfitPriceVariable,1);
takeProfitPrice := GetValue(triggerPricestopLossPricetakeProfitPriceVariable,2)
var stopLoss interface{} = this.SafeDict(params, "stopLoss")
var takeProfit interface{} = this.SafeDict(params, "takeProfit")
// const isTpAndSl = stopLossPrice && takeProfitPrice;
var triggerPriceTypes interface{} = map[string]interface{} {
"mark": "MP",
"last": "TP",
"index": "IP",
}
var triggerPriceType interface{} = this.SafeString(params, "triggerPriceType", "mark")
var triggerPriceTypeValue interface{} = this.SafeString(triggerPriceTypes, triggerPriceType, triggerPriceType)
params = this.Omit(params, []interface{}{"stopLossPrice", "takeProfitPrice", "triggerPrice", "stopPrice", "takeProfit", "stopLoss"})
if IsTrue(triggerPrice) {
AddElementToObject(request, "stop", Ternary(IsTrue((IsEqual(side, "buy"))), "up", "down"))
AddElementToObject(request, "stopPrice", this.PriceToPrecision(symbol, triggerPrice))
AddElementToObject(request, "stopPriceType", triggerPriceTypeValue)
} else if IsTrue(IsTrue(!IsEqual(stopLoss, nil)) || IsTrue(!IsEqual(takeProfit, nil))) {
var priceType interface{} = triggerPriceTypeValue
if IsTrue(!IsEqual(stopLoss, nil)) {
var slPrice interface{} = this.SafeString2(stopLoss, "triggerPrice", "stopPrice")
AddElementToObject(request, "triggerStopDownPrice", this.PriceToPrecision(symbol, slPrice))
priceType = this.SafeString(stopLoss, "triggerPriceType", "mark")
priceType = this.SafeString(triggerPriceTypes, priceType, priceType)
}
if IsTrue(!IsEqual(takeProfit, nil)) {
var tpPrice interface{} = this.SafeString2(takeProfit, "triggerPrice", "takeProfitPrice")
AddElementToObject(request, "triggerStopUpPrice", this.PriceToPrecision(symbol, tpPrice))
priceType = this.SafeString(takeProfit, "triggerPriceType", "mark")
priceType = this.SafeString(triggerPriceTypes, priceType, priceType)
}
AddElementToObject(request, "stopPriceType", priceType)
} else if IsTrue(IsTrue(stopLossPrice) || IsTrue(takeProfitPrice)) {
if IsTrue(stopLossPrice) {
AddElementToObject(request, "stop", Ternary(IsTrue((IsEqual(side, "buy"))), "up", "down"))
AddElementToObject(request, "stopPrice", this.PriceToPrecision(symbol, stopLossPrice))
} else {
AddElementToObject(request, "stop", Ternary(IsTrue((IsEqual(side, "buy"))), "down", "up"))
AddElementToObject(request, "stopPrice", this.PriceToPrecision(symbol, takeProfitPrice))
}
AddElementToObject(request, "reduceOnly", true)
AddElementToObject(request, "stopPriceType", triggerPriceTypeValue)
}
var uppercaseType interface{} = ToUpper(typeVar)
var timeInForce interface{} = this.SafeStringUpper(params, "timeInForce")
if IsTrue(IsEqual(uppercaseType, "LIMIT")) {
if IsTrue(IsEqual(price, nil)) {
panic(ArgumentsRequired(Add(this.Id, " createOrder() requires a price argument for limit orders")))
} else {
AddElementToObject(request, "price", this.PriceToPrecision(symbol, price))
}
if IsTrue(!IsEqual(timeInForce, nil)) {
AddElementToObject(request, "timeInForce", timeInForce)
}
}
var postOnly interface{} = nil
postOnlyparamsVariable := this.HandlePostOnly(IsEqual(typeVar, "market"), false, params);
postOnly = GetValue(postOnlyparamsVariable,0);
params = GetValue(postOnlyparamsVariable,1)
if IsTrue(postOnly) {
AddElementToObject(request, "postOnly", true)
}
var hidden interface{} = this.SafeValue(params, "hidden")
if IsTrue(IsTrue(postOnly) && IsTrue((!IsEqual(hidden, nil)))) {
panic(BadRequest(Add(this.Id, " createOrder() does not support the postOnly parameter together with a hidden parameter")))
}
var iceberg interface{} = this.SafeValue(params, "iceberg")
if IsTrue(iceberg) {
var visibleSize interface{} = this.SafeValue(params, "visibleSize")
if IsTrue(IsEqual(visibleSize, nil)) {
panic(ArgumentsRequired(Add(this.Id, " createOrder() requires a visibleSize parameter for iceberg orders")))
}
}
params = this.Omit(params, []interface{}{"timeInForce", "stopPrice", "triggerPrice", "stopLossPrice", "takeProfitPrice"}) // Time in force only valid for limit orders, exchange error when gtc for market orders
return this.Extend(request, params)
}
/**
* @method
* @name kucoinfutures#cancelOrder
* @description cancels an open order
* @see https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-futures-order-by-orderid
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.clientOrderId] cancel order by client order id
* @returns {object} An [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *kucoinfutures) 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
retRes17448 := (<-this.LoadMarkets())
PanicOnError(retRes17448)
var clientOrderId interface{} = this.SafeString2(params, "clientOid", "clientOrderId")
params = this.Omit(params, []interface{}{"clientOrderId"})
var request interface{} = map[string]interface{} {}
var response interface{} = nil
if IsTrue(!IsEqual(clientOrderId, nil)) {
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " cancelOrder() requires a symbol argument when cancelling by clientOrderId")))
}
var market interface{} = this.Market(symbol)
AddElementToObject(request, "symbol", GetValue(market, "id"))
AddElementToObject(request, "clientOid", clientOrderId)
response = (<-this.FuturesPrivateDeleteOrdersClientOrderClientOid(this.Extend(request, params)))
PanicOnError(response)
} else {
AddElementToObject(request, "orderId", id)
response = (<-this.FuturesPrivateDeleteOrdersOrderId(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// "code": "200000",
// "data": {
// "cancelledOrderIds": [
// "619714b8b6353000014c505a",
// ],
// },
// }
//
ch <- this.SafeValue(response, "data")
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#cancelOrders
* @description cancel multiple orders
* @see https://www.kucoin.com/docs/rest/futures-trading/orders/batch-cancel-orders
* @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 {string[]} [params.clientOrderIds] client order ids
* @returns {object} an list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *kucoinfutures) 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
retRes17868 := (<-this.LoadMarkets())
PanicOnError(retRes17868)
var market interface{} = nil
if IsTrue(!IsEqual(symbol, nil)) {
market = this.Market(symbol)
}
var ordersRequests interface{} = []interface{}{}
var clientOrderIds interface{} = this.SafeList2(params, "clientOrderIds", "clientOids", []interface{}{})
params = this.Omit(params, []interface{}{"clientOrderIds", "clientOids"})
var useClientorderId interface{} = false
for i := 0; IsLessThan(i, GetArrayLength(clientOrderIds)); i++ {
useClientorderId = true
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " cancelOrders() requires a symbol argument when cancelling by clientOrderIds")))
}
AppendToArray(&ordersRequests,map[string]interface{} {
"symbol": GetValue(market, "id"),
"clientOid": this.SafeString(clientOrderIds, i),
})
}
for i := 0; IsLessThan(i, GetArrayLength(ids)); i++ {
AppendToArray(&ordersRequests,GetValue(ids, i))
}
var requestKey interface{} = Ternary(IsTrue(useClientorderId), "clientOidsList", "orderIdsList")
var request interface{} = map[string]interface{} {}
AddElementToObject(request, requestKey, ordersRequests)
response:= (<-this.FuturesPrivateDeleteOrdersMultiCancel(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data":
// [
// {
// "orderId": "80465574458560512",
// "clientOid": null,
// "code": "200",
// "msg": "success"
// },
// {
// "orderId": "80465575289094144",
// "clientOid": null,
// "code": "200",
// "msg": "success"
// }
// ]
// }
//
var orders interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseOrders(orders, market)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#cancelAllOrders
* @description cancel all open orders
* @see https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-multiple-futures-limit-orders
* @see https://www.kucoin.com/docs/rest/futures-trading/orders/cancel-multiple-futures-stop-orders
* @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 {object} [params.trigger] When true, all the trigger orders will be cancelled
* @returns Response from the exchange
*/
func (this *kucoinfutures) 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
retRes18488 := (<-this.LoadMarkets())
PanicOnError(retRes18488)
var request interface{} = map[string]interface{} {}
if IsTrue(!IsEqual(symbol, nil)) {
AddElementToObject(request, "symbol", this.MarketId(symbol))
}
var trigger interface{} = this.SafeValue2(params, "stop", "trigger")
params = this.Omit(params, []interface{}{"stop", "trigger"})
var response interface{} = nil
if IsTrue(trigger) {
response = (<-this.FuturesPrivateDeleteStopOrders(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.FuturesPrivateDeleteOrders(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// "code": "200000",
// "data": {
// "cancelledOrderIds": [
// "619714b8b6353000014c505a",
// ],
// },
// }
//
ch <- this.SafeValue(response, "data")
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#addMargin
* @description add margin
* @see https://www.kucoin.com/docs/rest/futures-trading/positions/add-margin-manually
* @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 *kucoinfutures) 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
retRes18858 := (<-this.LoadMarkets())
PanicOnError(retRes18858)
var market interface{} = this.Market(symbol)
var uuid interface{} = this.Uuid()
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"margin": this.AmountToPrecision(symbol, amount),
"bizNo": uuid,
}
response:= (<-this.FuturesPrivatePostPositionMarginDepositMargin(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "id": "62311d26064e8f00013f2c6d",
// "symbol": "XRPUSDTM",
// "autoDeposit": false,
// "maintMarginReq": 0.01,
// "riskLimit": 200000,
// "realLeverage": 0.88,
// "crossMode": false,
// "delevPercentage": 0.4,
// "openingTimestamp": 1647385894798,
// "currentTimestamp": 1647414510672,
// "currentQty": -1,
// "currentCost": -7.658,
// "currentComm": 0.0053561,
// "unrealisedCost": -7.658,
// "realisedGrossCost": 0,
// "realisedCost": 0.0053561,
// "isOpen": true,
// "markPrice": 0.7635,
// "markValue": -7.635,
// "posCost": -7.658,
// "posCross": 1.00016084,
// "posInit": 7.658,
// "posComm": 0.00979006,
// "posLoss": 0,
// "posMargin": 8.6679509,
// "posMaint": 0.08637006,
// "maintMargin": 8.6909509,
// "realisedGrossPnl": 0,
// "realisedPnl": -0.0038335,
// "unrealisedPnl": 0.023,
// "unrealisedPnlPcnt": 0.003,
// "unrealisedRoePcnt": 0.003,
// "avgEntryPrice": 0.7658,
// "liquidationPrice": 1.6239,
// "bankruptPrice": 1.6317,
// "settleCurrency": "USDT"
// }
// }
//
//
// {
// "code":"200000",
// "msg":"Position does not exist"
// }
//
var data interface{} = this.SafeValue(response, "data")
ch <- this.Extend(this.ParseMarginModification(data, market), map[string]interface{} {
"amount": this.AmountToPrecision(symbol, amount),
"direction": "in",
})
return nil
}()
return ch
}
func (this *kucoinfutures) ParseMarginModification(info interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "id": "62311d26064e8f00013f2c6d",
// "symbol": "XRPUSDTM",
// "autoDeposit": false,
// "maintMarginReq": 0.01,
// "riskLimit": 200000,
// "realLeverage": 0.88,
// "crossMode": false,
// "delevPercentage": 0.4,
// "openingTimestamp": 1647385894798,
// "currentTimestamp": 1647414510672,
// "currentQty": -1,
// "currentCost": -7.658,
// "currentComm": 0.0053561,
// "unrealisedCost": -7.658,
// "realisedGrossCost": 0,
// "realisedCost": 0.0053561,
// "isOpen": true,
// "markPrice": 0.7635,
// "markValue": -7.635,
// "posCost": -7.658,
// "posCross": 1.00016084,
// "posInit": 7.658,
// "posComm": 0.00979006,
// "posLoss": 0,
// "posMargin": 8.6679509,
// "posMaint": 0.08637006,
// "maintMargin": 8.6909509,
// "realisedGrossPnl": 0,
// "realisedPnl": -0.0038335,
// "unrealisedPnl": 0.023,
// "unrealisedPnlPcnt": 0.003,
// "unrealisedRoePcnt": 0.003,
// "avgEntryPrice": 0.7658,
// "liquidationPrice": 1.6239,
// "bankruptPrice": 1.6317,
// "settleCurrency": "USDT"
// }
//
// {
// "code":"200000",
// "msg":"Position does not exist"
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var id interface{} = this.SafeString(info, "id")
market = this.SafeMarket(id, market)
var currencyId interface{} = this.SafeString(info, "settleCurrency")
var crossMode interface{} = this.SafeValue(info, "crossMode")
var mode interface{} = Ternary(IsTrue(crossMode), "cross", "isolated")
var marketId interface{} = this.SafeString(market, "symbol")
var timestamp interface{} = this.SafeInteger(info, "currentTimestamp")
return map[string]interface{} {
"info": info,
"symbol": this.SafeSymbol(marketId, market),
"type": nil,
"marginMode": mode,
"amount": nil,
"total": nil,
"code": this.SafeCurrencyCode(currencyId),
"status": nil,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
}
}
/**
* @method
* @name kucoinfutures#fetchOrdersByStatus
* @description fetches a list of orders placed on the exchange
* @see https://docs.kucoin.com/futures/#get-order-list
* @see https://docs.kucoin.com/futures/#get-untriggered-stop-order-list
* @param {string} status 'active' or 'closed', only 'active' is valid for stop orders
* @param {string} symbol unified symbol for the market to retrieve orders from
* @param {int} [since] timestamp in ms of the earliest order to retrieve
* @param {int} [limit] The maximum number of orders to retrieve
* @param {object} [params] exchange specific parameters
* @param {bool} [params.trigger] set to true to retrieve untriggered stop orders
* @param {int} [params.until] End time in ms
* @param {string} [params.side] buy or sell
* @param {string} [params.type] limit or market
* @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 An [array of order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *kucoinfutures) 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
retRes20368 := (<-this.LoadMarkets())
PanicOnError(retRes20368)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOrdersByStatus", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes204019 := (<-this.FetchPaginatedCallDynamic("fetchOrdersByStatus", symbol, since, limit, params))
PanicOnError(retRes204019)
ch <- retRes204019
return nil
}
var trigger interface{} = this.SafeBool2(params, "stop", "trigger")
var until interface{} = this.SafeInteger(params, "until")
params = this.Omit(params, []interface{}{"stop", "until", "trigger"})
if IsTrue(IsEqual(status, "closed")) {
status = "done"
} else if IsTrue(IsEqual(status, "open")) {
status = "active"
}
var request interface{} = map[string]interface{} {}
if !IsTrue(trigger) {
AddElementToObject(request, "status", status)
} else if IsTrue(!IsEqual(status, "active")) {
panic(BadRequest(Add(this.Id, " fetchOrdersByStatus() can only fetch untriggered stop orders")))
}
var market interface{} = nil
if IsTrue(!IsEqual(symbol, nil)) {
market = this.Market(symbol)
AddElementToObject(request, "symbol", GetValue(market, "id"))
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startAt", since)
}
if IsTrue(!IsEqual(until, nil)) {
AddElementToObject(request, "endAt", until)
}
var response interface{} = nil
if IsTrue(trigger) {
response = (<-this.FuturesPrivateGetStopOrders(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.FuturesPrivateGetOrders(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// "code": "200000",
// "data": {
// "currentPage": 1,
// "pageSize": 50,
// "totalNum": 4,
// "totalPage": 1,
// "items": [
// {
// "id": "64507d02921f1c0001ff6892",
// "symbol": "XBTUSDTM",
// "type": "market",
// "side": "buy",
// "price": null,
// "size": 1,
// "value": "27.992",
// "dealValue": "27.992",
// "dealSize": 1,
// "stp": "",
// "stop": "",
// "stopPriceType": "",
// "stopTriggered": false,
// "stopPrice": null,
// "timeInForce": "GTC",
// "postOnly": false,
// "hidden": false,
// "iceberg": false,
// "leverage": "17",
// "forceHold": false,
// "closeOrder": false,
// "visibleSize": null,
// "clientOid": null,
// "remark": null,
// "tags": null,
// "isActive": false,
// "cancelExist": false,
// "createdAt": 1682996482000,
// "updatedAt": 1682996483062,
// "endAt": 1682996483062,
// "orderTime": 1682996482953900677,
// "settleCurrency": "USDT",
// "status": "done",
// "filledValue": "27.992",
// "filledSize": 1,
// "reduceOnly": false
// }
// ]
// }
// }
//
var responseData interface{} = this.SafeValue(response, "data", map[string]interface{} {})
var orders interface{} = this.SafeList(responseData, "items", []interface{}{})
ch <- this.ParseOrders(orders, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://docs.kucoin.com/futures/#get-order-list
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] end time in ms
* @param {string} [params.side] buy or sell
* @param {string} [params.type] limit, or market
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *kucoinfutures) 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
retRes21458 := (<-this.LoadMarkets())
PanicOnError(retRes21458)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchClosedOrders", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes214919 := (<-this.FetchPaginatedCallDynamic("fetchClosedOrders", symbol, since, limit, params))
PanicOnError(retRes214919)
ch <- retRes214919
return nil
}
retRes215115 := (<-this.FetchOrdersByStatus("done", symbol, since, limit, params))
PanicOnError(retRes215115)
ch <- retRes215115
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchOpenOrders
* @description fetches information on multiple open orders made by the user
* @see https://docs.kucoin.com/futures/#get-order-list
* @see https://docs.kucoin.com/futures/#get-untriggered-stop-order-list
* @param {string} symbol unified market symbol of the market orders were made in
* @param {int} [since] the earliest time in ms to fetch orders for
* @param {int} [limit] the maximum number of order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] end time in ms
* @param {string} [params.side] buy or sell
* @param {string} [params.type] limit, or market
* @param {boolean} [params.trigger] set to true to retrieve untriggered stop orders
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *kucoinfutures) 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
retRes21728 := (<-this.LoadMarkets())
PanicOnError(retRes21728)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOpenOrders", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes217619 := (<-this.FetchPaginatedCallDynamic("fetchOpenOrders", symbol, since, limit, params))
PanicOnError(retRes217619)
ch <- retRes217619
return nil
}
retRes217815 := (<-this.FetchOrdersByStatus("open", symbol, since, limit, params))
PanicOnError(retRes217815)
ch <- retRes217815
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.kucoin.com/futures/#get-details-of-a-single-order
* @param {string} id order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *kucoinfutures) 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
retRes21928 := (<-this.LoadMarkets())
PanicOnError(retRes21928)
var request interface{} = map[string]interface{} {}
var response interface{} = nil
if IsTrue(IsEqual(id, nil)) {
var clientOrderId interface{} = this.SafeString2(params, "clientOid", "clientOrderId")
if IsTrue(IsEqual(clientOrderId, nil)) {
panic(InvalidOrder(Add(this.Id, " fetchOrder() requires parameter id or params.clientOid")))
}
AddElementToObject(request, "clientOid", clientOrderId)
params = this.Omit(params, []interface{}{"clientOid", "clientOrderId"})
response = (<-this.FuturesPrivateGetOrdersByClientOid(this.Extend(request, params)))
PanicOnError(response)
} else {
AddElementToObject(request, "orderId", id)
response = (<-this.FuturesPrivateGetOrdersOrderId(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// "code": "200000",
// "data": {
// "id": "64507d02921f1c0001ff6892",
// "symbol": "XBTUSDTM",
// "type": "market",
// "side": "buy",
// "price": null,
// "size": 1,
// "value": "27.992",
// "dealValue": "27.992",
// "dealSize": 1,
// "stp": "",
// "stop": "",
// "stopPriceType": "",
// "stopTriggered": false,
// "stopPrice": null,
// "timeInForce": "GTC",
// "postOnly": false,
// "hidden": false,
// "iceberg": false,
// "leverage": "17",
// "forceHold": false,
// "closeOrder": false,
// "visibleSize": null,
// "clientOid": null,
// "remark": null,
// "tags": null,
// "isActive": false,
// "cancelExist": false,
// "createdAt": 1682996482000,
// "updatedAt": 1682996483000,
// "endAt": 1682996483000,
// "orderTime": 1682996482953900677,
// "settleCurrency": "USDT",
// "status": "done",
// "filledSize": 1,
// "filledValue": "27.992",
// "reduceOnly": false
// }
// }
//
var market interface{} = Ternary(IsTrue((!IsEqual(symbol, nil))), this.Market(symbol), nil)
var responseData interface{} = this.SafeDict(response, "data")
ch <- this.ParseOrder(responseData, market)
return nil
}()
return ch
}
func (this *kucoinfutures) ParseOrder(order interface{}, optionalArgs ...interface{}) interface{} {
//
// fetchOrder, fetchOrdersByStatus
//
// {
// "id": "64507d02921f1c0001ff6892",
// "symbol": "XBTUSDTM",
// "type": "market",
// "side": "buy",
// "price": null,
// "size": 1,
// "value": "27.992",
// "dealValue": "27.992",
// "dealSize": 1,
// "stp": "",
// "stop": "",
// "stopPriceType": "",
// "stopTriggered": false,
// "stopPrice": null,
// "timeInForce": "GTC",
// "postOnly": false,
// "hidden": false,
// "iceberg": false,
// "leverage": "17",
// "forceHold": false,
// "closeOrder": false,
// "visibleSize": null,
// "clientOid": null,
// "remark": null,
// "tags": null,
// "isActive": false,
// "cancelExist": false,
// "createdAt": 1682996482000,
// "updatedAt": 1682996483062,
// "endAt": 1682996483062,
// "orderTime": 1682996482953900677,
// "settleCurrency": "USDT",
// "status": "done",
// "filledValue": "27.992",
// "filledSize": 1,
// "reduceOnly": false
// }
//
// createOrder
//
// {
// "orderId": "619717484f1d010001510cde"
// }
//
// createOrders
//
// {
// "orderId": "80465574458560512",
// "clientOid": "5c52e11203aa677f33e491",
// "symbol": "ETHUSDTM",
// "code": "200000",
// "msg": "success"
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(order, "symbol")
market = this.SafeMarket(marketId, market)
var symbol interface{} = GetValue(market, "symbol")
var orderId interface{} = this.SafeString2(order, "id", "orderId")
var typeVar interface{} = this.SafeString(order, "type")
var timestamp interface{} = this.SafeInteger(order, "createdAt")
var datetime interface{} = this.Iso8601(timestamp)
var price interface{} = this.SafeString(order, "price")
// price is zero for market order
// omitZero is called in safeOrder2
var side interface{} = this.SafeString(order, "side")
var feeCurrencyId interface{} = this.SafeString(order, "feeCurrency")
var feeCurrency interface{} = this.SafeCurrencyCode(feeCurrencyId)
var feeCost interface{} = this.SafeNumber(order, "fee")
var amount interface{} = this.SafeString(order, "size")
var filled interface{} = this.SafeString(order, "filledSize")
var cost interface{} = this.SafeString(order, "filledValue")
var average interface{} = this.SafeString(order, "avgDealPrice")
if IsTrue(IsTrue((IsEqual(average, nil))) && IsTrue(Precise.StringGt(filled, "0"))) {
var contractSize interface{} = this.SafeString(market, "contractSize")
if IsTrue(GetValue(market, "linear")) {
average = Precise.StringDiv(cost, Precise.StringMul(contractSize, filled))
} else {
average = Precise.StringDiv(Precise.StringMul(contractSize, filled), cost)
}
}
// precision reported by their api is 8 d.p.
// const average = Precise.stringDiv (cost, Precise.stringMul (filled, market['contractSize']));
// bool
var isActive interface{} = this.SafeValue(order, "isActive")
var cancelExist interface{} = this.SafeBool(order, "cancelExist", false)
var status interface{} = nil
if IsTrue(!IsEqual(isActive, nil)) {
status = Ternary(IsTrue(isActive), "open", "closed")
}
status = Ternary(IsTrue(cancelExist), "canceled", status)
var fee interface{} = nil
if IsTrue(!IsEqual(feeCost, nil)) {
fee = map[string]interface{} {
"currency": feeCurrency,
"cost": feeCost,
}
}
var clientOrderId interface{} = this.SafeString(order, "clientOid")
var timeInForce interface{} = this.SafeString(order, "timeInForce")
var postOnly interface{} = this.SafeValue(order, "postOnly")
var reduceOnly interface{} = this.SafeValue(order, "reduceOnly")
var lastUpdateTimestamp interface{} = this.SafeInteger(order, "updatedAt")
return this.SafeOrder(map[string]interface{} {
"id": orderId,
"clientOrderId": clientOrderId,
"symbol": symbol,
"type": typeVar,
"timeInForce": timeInForce,
"postOnly": postOnly,
"reduceOnly": reduceOnly,
"side": side,
"amount": amount,
"price": price,
"triggerPrice": this.SafeNumber(order, "stopPrice"),
"cost": cost,
"filled": filled,
"remaining": nil,
"timestamp": timestamp,
"datetime": datetime,
"fee": fee,
"status": status,
"info": order,
"lastTradeTimestamp": nil,
"lastUpdateTimestamp": lastUpdateTimestamp,
"average": average,
"trades": nil,
}, market)
}
/**
* @method
* @name kucoinfutures#fetchFundingRate
* @description fetch the current funding rate
* @see https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-current-funding-rate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/#/?id=funding-rate-structure}
*/
func (this *kucoinfutures) 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
retRes23998 := (<-this.LoadMarkets())
PanicOnError(retRes23998)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.FuturesPublicGetFundingRateSymbolCurrent(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "symbol": ".ETHUSDTMFPI8H",
// "granularity": 28800000,
// "timePoint": 1637380800000,
// "value": 0.0001,
// "predictedValue": 0.0001,
// },
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
// the website displayes the previous funding rate as "funding rate"
ch <- this.ParseFundingRate(data, market)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchFundingInterval
* @description fetch the current funding rate interval
* @see https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-current-funding-rate
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/#/?id=funding-rate-structure}
*/
func (this *kucoinfutures) FetchFundingInterval(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
retRes243215 := (<-this.FetchFundingRate(symbol, params))
PanicOnError(retRes243215)
ch <- retRes243215
return nil
}()
return ch
}
func (this *kucoinfutures) ParseFundingRate(data interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "symbol": ".ETHUSDTMFPI8H",
// "granularity": 28800000,
// "timePoint": 1637380800000,
// "value": 0.0001,
// "predictedValue": 0.0001,
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var fundingTimestamp interface{} = this.SafeInteger(data, "timePoint")
var marketId interface{} = this.SafeString(data, "symbol")
return map[string]interface{} {
"info": data,
"symbol": this.SafeSymbol(marketId, market, nil, "contract"),
"markPrice": nil,
"indexPrice": nil,
"interestRate": nil,
"estimatedSettlePrice": nil,
"timestamp": nil,
"datetime": nil,
"fundingRate": this.SafeNumber(data, "value"),
"fundingTimestamp": fundingTimestamp,
"fundingDatetime": this.Iso8601(fundingTimestamp),
"nextFundingRate": this.SafeNumber(data, "predictedValue"),
"nextFundingTimestamp": nil,
"nextFundingDatetime": nil,
"previousFundingRate": nil,
"previousFundingTimestamp": nil,
"previousFundingDatetime": nil,
"interval": this.ParseFundingInterval(this.SafeString(data, "granularity")),
}
}
func (this *kucoinfutures) 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 *kucoinfutures) ParseBalance(response interface{}) interface{} {
var result interface{} = map[string]interface{} {
"info": response,
"timestamp": nil,
"datetime": nil,
}
var data interface{} = this.SafeValue(response, "data")
var currencyId interface{} = this.SafeString(data, "currency")
var code interface{} = this.SafeCurrencyCode(currencyId)
var account interface{} = this.Account()
AddElementToObject(account, "free", this.SafeString(data, "availableBalance"))
AddElementToObject(account, "total", this.SafeString(data, "accountEquity"))
AddElementToObject(result, code, account)
return this.SafeBalance(result)
}
/**
* @method
* @name kucoinfutures#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://www.kucoin.com/docs/rest/funding/funding-overview/get-account-detail-futures
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/#/?id=balance-structure}
*/
func (this *kucoinfutures) 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
retRes25058 := (<-this.LoadMarkets())
PanicOnError(retRes25058)
// only fetches one balance at a time
var defaultCode interface{} = this.SafeString(this.Options, "code")
var fetchBalanceOptions interface{} = this.SafeValue(this.Options, "fetchBalance", map[string]interface{} {})
defaultCode = this.SafeString(fetchBalanceOptions, "code", defaultCode)
var code interface{} = this.SafeString(params, "code", defaultCode)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
}
response:= (<-this.FuturesPrivateGetAccountOverview(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "accountEquity": 0.00005,
// "unrealisedPNL": 0,
// "marginBalance": 0.00005,
// "positionMargin": 0,
// "orderMargin": 0,
// "frozenFunds": 0,
// "availableBalance": 0.00005,
// "currency": "XBT"
// }
// }
//
ch <- this.ParseBalance(response)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#transfer
* @description transfer currency internally between wallets on the same account
* @see https://www.kucoin.com/docs/rest/funding/transfer/transfer-to-main-or-trade-account
* @see https://www.kucoin.com/docs/rest/funding/transfer/transfer-to-futures-account
* @param {string} code unified currency code
* @param {float} amount amount to transfer
* @param {string} fromAccount account to transfer from
* @param {string} toAccount account to transfer to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transfer structure]{@link https://docs.ccxt.com/#/?id=transfer-structure}
*/
func (this *kucoinfutures) 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
retRes25488 := (<-this.LoadMarkets())
PanicOnError(retRes25488)
var currency interface{} = this.Currency(code)
var amountToPrecision interface{} = this.CurrencyToPrecision(code, amount)
var request interface{} = map[string]interface{} {
"currency": this.SafeString(currency, "id"),
"amount": amountToPrecision,
}
var toAccountString interface{} = this.ParseTransferType(toAccount)
var response interface{} = nil
if IsTrue(IsTrue(IsEqual(toAccountString, "TRADE")) || IsTrue(IsEqual(toAccountString, "MAIN"))) {
AddElementToObject(request, "recAccountType", toAccountString)
response = (<-this.FuturesPrivatePostTransferOut(this.Extend(request, params)))
PanicOnError(response)
} else if IsTrue(IsTrue(IsTrue(IsEqual(toAccount, "future")) || IsTrue(IsEqual(toAccount, "swap"))) || IsTrue(IsEqual(toAccount, "contract"))) {
AddElementToObject(request, "payAccountType", this.ParseTransferType(fromAccount))
response = (<-this.FuturesPrivatePostTransferIn(this.Extend(request, params)))
PanicOnError(response)
} else {
panic(BadRequest(Add(this.Id, " transfer() only supports transfers between future/swap, spot and funding accounts")))
}
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
ch <- this.Extend(this.ParseTransfer(data, currency), map[string]interface{} {
"amount": this.ParseNumber(amountToPrecision),
"fromAccount": fromAccount,
"toAccount": toAccount,
})
return nil
}()
return ch
}
func (this *kucoinfutures) ParseTransfer(transfer interface{}, optionalArgs ...interface{}) interface{} {
//
// transfer to spot or funding account
//
// {
// "applyId": "5bffb63303aa675e8bbe18f9" // Transfer-out request ID
// }
//
// transfer to future account
//
// {
// "applyId": "6738754373ceee00011ec3f8",
// "bizNo": "6738754373ceee00011ec3f7",
// "payAccountType": "CONTRACT",
// "payTag": "DEFAULT",
// "remark": "",
// "recAccountType": "MAIN",
// "recTag": "DEFAULT",
// "recRemark": "",
// "recSystem": "KUCOIN",
// "status": "PROCESSING",
// "currency": "USDT",
// "amount": "5",
// "fee": "0",
// "sn": 1519769124846692,
// "reason": "",
// "createdAt": 1731753283000,
// "updatedAt": 1731753283000
// }
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
var timestamp interface{} = this.SafeInteger(transfer, "updatedAt")
return map[string]interface{} {
"id": this.SafeString(transfer, "applyId"),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"currency": this.SafeCurrencyCode(nil, currency),
"amount": this.SafeNumber(transfer, "amount"),
"fromAccount": nil,
"toAccount": nil,
"status": this.SafeString(transfer, "status"),
"info": transfer,
}
}
func (this *kucoinfutures) ParseTransferStatus(status interface{}) interface{} {
var statuses interface{} = map[string]interface{} {
"PROCESSING": "pending",
}
return this.SafeString(statuses, status, status)
}
func (this *kucoinfutures) ParseTransferType(transferType interface{}) interface{} {
var transferTypes interface{} = map[string]interface{} {
"spot": "TRADE",
"funding": "MAIN",
}
return this.SafeStringUpper(transferTypes, transferType, transferType)
}
/**
* @method
* @name kucoinfutures#fetchMyTrades
* @see https://docs.kucoin.com/futures/#get-fills
* @description fetch all trades made by the user
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @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 {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure}
*/
func (this *kucoinfutures) 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
retRes26798 := (<-this.LoadMarkets())
PanicOnError(retRes26798)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchMyTrades", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes268319 := (<-this.FetchPaginatedCallDynamic("fetchMyTrades", symbol, since, limit, params))
PanicOnError(retRes268319)
ch <- retRes268319
return nil
}
var request interface{} = map[string]interface{} {}
var market interface{} = nil
if IsTrue(!IsEqual(symbol, nil)) {
market = this.Market(symbol)
AddElementToObject(request, "symbol", GetValue(market, "id"))
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startAt", since)
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "pageSize", mathMin(1000, limit))
}
requestparamsVariable := this.HandleUntilOption("endAt", request, params);
request = GetValue(requestparamsVariable,0);
params = GetValue(requestparamsVariable,1)
response:= (<-this.FuturesPrivateGetFills(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "currentPage": 1,
// "pageSize": 1,
// "totalNum": 251915,
// "totalPage": 251915,
// "items": [
// {
// "symbol": "XBTUSDM", // Ticker symbol of the contract
// "tradeId": "5ce24c1f0c19fc3c58edc47c", // Trade ID
// "orderId": "5ce24c16b210233c36ee321d", // Order ID
// "side": "sell", // Transaction side
// "liquidity": "taker", // Liquidity- taker or maker
// "price": "8302", // Filled price
// "size": 10, // Filled amount
// "value": "0.001204529", // Order value
// "feeRate": "0.0005", // Floating fees
// "fixFee": "0.00000006", // Fixed fees
// "feeCurrency": "XBT", // Charging currency
// "stop": "", // A mark to the stop order type
// "fee": "0.0000012022", // Transaction fee
// "orderType": "limit", // Order type
// "tradeType": "trade", // Trade type (trade, liquidation, ADL or settlement)
// "createdAt": 1558334496000, // Time the order created
// "settleCurrency": "XBT", // settlement currency
// "tradeTime": 1558334496000000000 // trade time in nanosecond
// }
// ]
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var trades interface{} = this.SafeList(data, "items", []interface{}{})
ch <- this.ParseTrades(trades, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://www.kucoin.com/docs/rest/futures-trading/market-data/get-transaction-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
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades}
*/
func (this *kucoinfutures) 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
retRes27568 := (<-this.LoadMarkets())
PanicOnError(retRes27568)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.FuturesPublicGetTradeHistory(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": [
// {
// "sequence": 32114961,
// "side": "buy",
// "size": 39,
// "price": "4001.6500000000",
// "takerOrderId": "61c20742f172110001e0ebe4",
// "makerOrderId": "61c2073fcfc88100010fcb5d",
// "tradeId": "61c2074277a0c473e69029b8",
// "ts": 1640105794099993896 // filled time
// }
// ]
// }
//
var trades interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseTrades(trades, market, since, limit)
return nil
}()
return ch
}
func (this *kucoinfutures) ParseTrade(trade interface{}, optionalArgs ...interface{}) interface{} {
//
// fetchTrades (public)
//
// {
// "sequence": 32114961,
// "side": "buy",
// "size": 39,
// "price": "4001.6500000000",
// "takerOrderId": "61c20742f172110001e0ebe4",
// "makerOrderId": "61c2073fcfc88100010fcb5d",
// "tradeId": "61c2074277a0c473e69029b8",
// "ts": 1640105794099993896 // filled time
// }
//
// fetchMyTrades (private) v2
//
// {
// "symbol":"BTC-USDT",
// "tradeId":"5c35c02709e4f67d5266954e",
// "orderId":"5c35c02703aa673ceec2a168",
// "counterOrderId":"5c1ab46003aa676e487fa8e3",
// "side":"buy",
// "liquidity":"taker",
// "forceTaker":true,
// "price":"0.083",
// "size":"0.8424304",
// "funds":"0.0699217232",
// "fee":"0",
// "feeRate":"0",
// "feeCurrency":"USDT",
// "stop":"",
// "type":"limit",
// "createdAt":1547026472000
// }
//
// fetchMyTrades (private) v1
//
// {
// "symbol":"DOGEUSDTM",
// "tradeId":"620ec41a96bab27b5f4ced56",
// "orderId":"620ec41a0d1d8a0001560bd0",
// "side":"sell",
// "liquidity":"taker",
// "forceTaker":true,
// "price":"0.13969",
// "size":1,
// "value":"13.969",
// "feeRate":"0.0006",
// "fixFee":"0",
// "feeCurrency":"USDT",
// "stop":"",
// "tradeTime":1645134874858018058,
// "fee":"0.0083814",
// "settleCurrency":"USDT",
// "orderType":"market",
// "tradeType":"trade",
// "createdAt":1645134874858
// }
//
// watchTrades
//
// {
// "makerUserId": "62286a4d720edf0001e81961",
// "symbol": "ADAUSDTM",
// "sequence": 41320766,
// "side": "sell",
// "size": 2,
// "price": 0.35904,
// "takerOrderId": "636dd9da9857ba00010cfa44",
// "makerOrderId": "636dd9c8df149d0001e62bc8",
// "takerUserId": "6180be22b6ab210001fa3371",
// "tradeId": "636dd9da0000d400d477eca7",
// "ts": 1668143578987357700
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(trade, "symbol")
market = this.SafeMarket(marketId, market, "-")
var id interface{} = this.SafeString2(trade, "tradeId", "id")
var orderId interface{} = this.SafeString(trade, "orderId")
var takerOrMaker interface{} = this.SafeString(trade, "liquidity")
var timestamp interface{} = this.SafeInteger(trade, "ts")
if IsTrue(!IsEqual(timestamp, nil)) {
timestamp = this.ParseToInt(Divide(timestamp, 1000000))
} else {
timestamp = this.SafeInteger(trade, "createdAt")
// if it's a historical v1 trade, the exchange returns timestamp in seconds
if IsTrue(IsTrue((InOp(trade, "dealValue"))) && IsTrue((!IsEqual(timestamp, nil)))) {
timestamp = Multiply(timestamp, 1000)
}
}
var priceString interface{} = this.SafeString2(trade, "price", "dealPrice")
var amountString interface{} = this.SafeString2(trade, "size", "amount")
var side interface{} = this.SafeString(trade, "side")
var fee interface{} = nil
var feeCostString interface{} = this.SafeString(trade, "fee")
if IsTrue(!IsEqual(feeCostString, nil)) {
var feeCurrencyId interface{} = this.SafeString(trade, "feeCurrency")
var feeCurrency interface{} = this.SafeCurrencyCode(feeCurrencyId)
if IsTrue(IsEqual(feeCurrency, nil)) {
feeCurrency = Ternary(IsTrue((IsEqual(side, "sell"))), GetValue(market, "quote"), GetValue(market, "base"))
}
fee = map[string]interface{} {
"cost": feeCostString,
"currency": feeCurrency,
"rate": this.SafeString(trade, "feeRate"),
}
}
var typeVar interface{} = this.SafeString2(trade, "type", "orderType")
if IsTrue(IsEqual(typeVar, "match")) {
typeVar = nil
}
var costString interface{} = this.SafeString2(trade, "funds", "value")
if IsTrue(IsEqual(costString, nil)) {
var contractSize interface{} = this.SafeString(market, "contractSize")
var contractCost interface{} = Precise.StringMul(priceString, amountString)
costString = Precise.StringMul(contractCost, contractSize)
}
return this.SafeTrade(map[string]interface{} {
"info": trade,
"id": id,
"order": orderId,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"symbol": GetValue(market, "symbol"),
"type": typeVar,
"takerOrMaker": takerOrMaker,
"side": side,
"price": priceString,
"amount": amountString,
"cost": costString,
"fee": fee,
}, market)
}
/**
* @method
* @name kucoinfutures#fetchDeposits
* @description fetch all deposits made to an account
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch deposits for
* @param {int} [limit] the maximum number of deposits structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
func (this *kucoinfutures) 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
retRes29298 := (<-this.LoadMarkets())
PanicOnError(retRes29298)
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"))
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "pageSize", limit)
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startAt", since)
}
response:= (<-this.FuturesPrivateGetDepositList(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "currentPage": 1,
// "pageSize": 5,
// "totalNum": 2,
// "totalPage": 1,
// "items": [
// {
// "address": "0x5f047b29041bcfdbf0e4478cdfa753a336ba6989",
// "memo": "5c247c8a03aa677cea2a251d",
// "amount": 1,
// "fee": 0.0001,
// "currency": "KCS",
// "isInner": false,
// "walletTxId": "5bbb57386d99522d9f954c5a@test004",
// "status": "SUCCESS",
// "createdAt": 1544178843000,
// "updatedAt": 1544178891000
// "remark":"foobar"
// },
// ...
// ]
// }
// }
//
var responseData interface{} = GetValue(GetValue(response, "data"), "items")
ch <- this.ParseTransactions(responseData, currency, since, limit, map[string]interface{} {
"type": "deposit",
})
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @param {string} code unified currency code
* @param {int} [since] the earliest time in ms to fetch withdrawals for
* @param {int} [limit] the maximum number of withdrawals structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transaction structures]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
func (this *kucoinfutures) 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
retRes29858 := (<-this.LoadMarkets())
PanicOnError(retRes29858)
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"))
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "pageSize", limit)
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "startAt", since)
}
response:= (<-this.FuturesPrivateGetWithdrawalList(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "currentPage": 1,
// "pageSize": 5,
// "totalNum": 2,
// "totalPage": 1,
// "items": [
// {
// "id": "5c2dc64e03aa675aa263f1ac",
// "address": "0x5bedb060b8eb8d823e2414d82acce78d38be7fe9",
// "memo": "",
// "currency": "ETH",
// "amount": 1.0000000,
// "fee": 0.0100000,
// "walletTxId": "3e2414d82acce78d38be7fe9",
// "isInner": false,
// "status": "FAILURE",
// "createdAt": 1546503758000,
// "updatedAt": 1546504603000
// },
// ...
// ]
// }
// }
//
var responseData interface{} = GetValue(GetValue(response, "data"), "items")
ch <- this.ParseTransactions(responseData, currency, since, limit, map[string]interface{} {
"type": "withdrawal",
})
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchMarketLeverageTiers
* @description retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes for a single market
* @see https://www.kucoin.com/docs/rest/futures-trading/risk-limit/get-futures-risk-limit-level
* @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 *kucoinfutures) 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
retRes30408 := (<-this.LoadMarkets())
PanicOnError(retRes30408)
var market interface{} = this.Market(symbol)
if !IsTrue(GetValue(market, "contract")) {
panic(BadRequest(Add(this.Id, " fetchMarketLeverageTiers() supports contract markets only")))
}
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.FuturesPublicGetContractsRiskLimitSymbol(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": [
// {
// "symbol": "ETHUSDTM",
// "level": 1,
// "maxRiskLimit": 300000,
// "minRiskLimit": 0,
// "maxLeverage": 100,
// "initialMargin": 0.0100000000,
// "maintainMargin": 0.0050000000
// },
// ...
// ]
// }
//
var data interface{} = this.SafeValue(response, "data")
ch <- this.ParseMarketLeverageTiers(data, market)
return nil
}()
return ch
}
func (this *kucoinfutures) ParseMarketLeverageTiers(info interface{}, optionalArgs ...interface{}) interface{} {
/**
* @ignore
* @method
* @name kucoinfutures#parseMarketLeverageTiers
* @param {object} info Exchange market response for 1 market
* @param {object} market CCXT market
*/
//
// {
// "symbol": "ETHUSDTM",
// "level": 1,
// "maxRiskLimit": 300000,
// "minRiskLimit": 0,
// "maxLeverage": 100,
// "initialMargin": 0.0100000000,
// "maintainMargin": 0.0050000000
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var tiers interface{} = []interface{}{}
for i := 0; IsLessThan(i, GetArrayLength(info)); i++ {
var tier interface{} = GetValue(info, i)
var marketId interface{} = this.SafeString(tier, "symbol")
AppendToArray(&tiers,map[string]interface{} {
"tier": this.SafeNumber(tier, "level"),
"symbol": this.SafeSymbol(marketId, market, nil, "contract"),
"currency": GetValue(market, "base"),
"minNotional": this.SafeNumber(tier, "minRiskLimit"),
"maxNotional": this.SafeNumber(tier, "maxRiskLimit"),
"maintenanceMarginRate": this.SafeNumber(tier, "maintainMargin"),
"maxLeverage": this.SafeNumber(tier, "maxLeverage"),
"info": tier,
})
}
return tiers
}
/**
* @method
* @name kucoinfutures#fetchFundingRateHistory
* @see https://www.kucoin.com/docs/rest/futures-trading/funding-fees/get-public-funding-history#request-url
* @description fetches historical funding rate prices
* @param {string} symbol unified symbol of the market to fetch the funding rate history for
* @param {int} [since] not used by kucuoinfutures
* @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] end time in ms
* @returns {object[]} a list of [funding rate structures]{@link https://docs.ccxt.com/#/?id=funding-rate-history-structure}
*/
func (this *kucoinfutures) 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")))
}
retRes31238 := (<-this.LoadMarkets())
PanicOnError(retRes31238)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"from": 0,
"to": this.Milliseconds(),
}
var until interface{} = this.SafeInteger(params, "until")
params = this.Omit(params, []interface{}{"until"})
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "from", since)
if IsTrue(IsEqual(until, nil)) {
AddElementToObject(request, "to", Add(since, Multiply(Multiply(Multiply(Multiply(1000, 8), 60), 60), 100)))
}
}
if IsTrue(!IsEqual(until, nil)) {
AddElementToObject(request, "to", until)
if IsTrue(IsEqual(since, nil)) {
AddElementToObject(request, "to", Subtract(until, Multiply(Multiply(Multiply(Multiply(1000, 8), 60), 60), 100)))
}
}
response:= (<-this.FuturesPublicGetContractFundingRates(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": [
// {
// "symbol": "IDUSDTM",
// "fundingRate": 2.26E-4,
// "timepoint": 1702296000000
// }
// ]
// }
//
var data interface{} = this.SafeValue(response, "data")
ch <- this.ParseFundingRateHistories(data, market, since, limit)
return nil
}()
return ch
}
func (this *kucoinfutures) ParseFundingRateHistory(info interface{}, optionalArgs ...interface{}) interface{} {
market := GetArg(optionalArgs, 0, nil)
_ = market
var timestamp interface{} = this.SafeInteger(info, "timepoint")
var marketId interface{} = this.SafeString(info, "symbol")
return map[string]interface{} {
"info": info,
"symbol": this.SafeSymbol(marketId, market),
"fundingRate": this.SafeNumber(info, "fundingRate"),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
}
}
/**
* @method
* @name kucoinfutures#closePosition
* @description closes open positions for a market
* @see https://www.kucoin.com/docs/rest/futures-trading/orders/place-order
* @param {string} symbol Unified CCXT market symbol
* @param {string} side not used by kucoinfutures closePositions
* @param {object} [params] extra parameters specific to the okx api endpoint
* @param {string} [params.clientOrderId] client order id of the order
* @returns {object[]} [A list of position structures]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *kucoinfutures) 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
retRes31858 := (<-this.LoadMarkets())
PanicOnError(retRes31858)
var market interface{} = this.Market(symbol)
var clientOrderId interface{} = this.SafeString(params, "clientOrderId")
var testOrder interface{} = this.SafeBool(params, "test", false)
params = this.Omit(params, []interface{}{"test", "clientOrderId"})
if IsTrue(IsEqual(clientOrderId, nil)) {
clientOrderId = this.NumberToString(this.Nonce())
}
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"closeOrder": true,
"clientOid": clientOrderId,
"type": "market",
}
var response interface{} = nil
if IsTrue(testOrder) {
response = (<-this.FuturesPrivatePostOrdersTest(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.FuturesPrivatePostOrders(this.Extend(request, params)))
PanicOnError(response)
}
ch <- this.ParseOrder(response, market)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchTradingFee
* @description fetch the trading fees for a market
* @see https://www.kucoin.com/docs/rest/funding/trade-fee/trading-pair-actual-fee-futures
* @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 *kucoinfutures) 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
retRes32188 := (<-this.LoadMarkets())
PanicOnError(retRes32188)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbols": GetValue(market, "id"),
}
response:= (<-this.PrivateGetTradeFees(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "symbol": "XBTUSDTM",
// "takerFeeRate": "0.0006",
// "makerFeeRate": "0.0002"
// }
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
var first interface{} = this.SafeDict(data, 0)
var marketId interface{} = this.SafeString(first, "symbol")
ch <- map[string]interface{} {
"info": response,
"symbol": this.SafeSymbol(marketId, market),
"maker": this.SafeNumber(first, "makerFeeRate"),
"taker": this.SafeNumber(first, "takerFeeRate"),
"percentage": true,
"tierBased": true,
}
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchMarginMode
* @description fetches the margin mode of a trading pair
* @see https://www.kucoin.com/docs/rest/futures-trading/positions/get-margin-mode
* @param {string} symbol unified symbol of the market to fetch the margin mode for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [margin mode structure]{@link https://docs.ccxt.com/#/?id=margin-mode-structure}
*/
func (this *kucoinfutures) FetchMarginMode(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes32578 := (<-this.LoadMarkets())
PanicOnError(retRes32578)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.FuturesPrivateGetPositionGetMarginMode(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "symbol": "XBTUSDTM",
// "marginMode": "ISOLATED"
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
ch <- this.ParseMarginMode(data, market)
return nil
}()
return ch
}
func (this *kucoinfutures) ParseMarginMode(marginMode interface{}, optionalArgs ...interface{}) interface{} {
market := GetArg(optionalArgs, 0, nil)
_ = market
var marginType interface{} = this.SafeString(marginMode, "marginMode")
marginType = Ternary(IsTrue((IsEqual(marginType, "ISOLATED"))), "isolated", "cross")
return map[string]interface{} {
"info": marginMode,
"symbol": GetValue(market, "symbol"),
"marginMode": marginType,
}
}
/**
* @method
* @name kucoinfutures#setMarginMode
* @description set margin mode to 'cross' or 'isolated'
* @see https://www.kucoin.com/docs/rest/futures-trading/positions/modify-margin-mode
* @param {string} marginMode 'cross' or 'isolated'
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
func (this *kucoinfutures) SetMarginMode(marginMode interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " setMarginMode() requires a symbol argument")))
}
this.CheckRequiredArgument("setMarginMode", marginMode, "marginMode", []interface{}{"cross", "isolated"})
retRes33018 := (<-this.LoadMarkets())
PanicOnError(retRes33018)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"marginMode": ToUpper(marginMode),
}
response:= (<-this.FuturesPrivatePostPositionChangeMarginMode(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "symbol": "XBTUSDTM",
// "marginMode": "ISOLATED"
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
ch <- this.ParseMarginMode(data, market)
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#fetchLeverage
* @description fetch the set leverage for a market
* @see https://www.kucoin.com/docs/rest/futures-trading/positions/get-cross-margin-leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [leverage structure]{@link https://docs.ccxt.com/#/?id=leverage-structure}
*/
func (this *kucoinfutures) 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
var marginMode interface{} = nil
marginModeparamsVariable := this.HandleMarginModeAndParams(symbol, params);
marginMode = GetValue(marginModeparamsVariable,0);
params = GetValue(marginModeparamsVariable,1)
if IsTrue(!IsEqual(marginMode, "cross")) {
panic(NotSupported(Add(this.Id, " fetchLeverage() currently supports only params[\"marginMode\"] = \"cross\"")))
}
retRes33368 := (<-this.LoadMarkets())
PanicOnError(retRes33368)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.FuturesPrivateGetGetCrossUserLeverage(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": {
// "symbol": "XBTUSDTM",
// "leverage": "3"
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
var parsed interface{} = this.ParseLeverage(data, market)
ch <- this.Extend(parsed, map[string]interface{} {
"marginMode": marginMode,
})
return nil
}()
return ch
}
/**
* @method
* @name kucoinfutures#setLeverage
* @description set the level of leverage for a market
* @see https://www.kucoin.com/docs/rest/futures-trading/positions/modify-cross-margin-leverage
* @param {float} leverage the rate of leverage
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} response from the exchange
*/
func (this *kucoinfutures) 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
var marginMode interface{} = nil
marginModeparamsVariable := this.HandleMarginModeAndParams(symbol, params);
marginMode = GetValue(marginModeparamsVariable,0);
params = GetValue(marginModeparamsVariable,1)
if IsTrue(!IsEqual(marginMode, "cross")) {
panic(NotSupported(Add(this.Id, " setLeverage() currently supports only params[\"marginMode\"] = \"cross\"")))
}
retRes33748 := (<-this.LoadMarkets())
PanicOnError(retRes33748)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"leverage": ToString(leverage),
}
response:= (<-this.FuturesPrivatePostChangeCrossUserLeverage(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "code": "200000",
// "data": true
// }
//
ch <- this.ParseLeverage(response, market)
return nil
}()
return ch
}
func (this *kucoinfutures) ParseLeverage(leverage interface{}, optionalArgs ...interface{}) interface{} {
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(leverage, "symbol")
market = this.SafeMarket(marketId, market)
var leverageNum interface{} = this.SafeInteger(leverage, "leverage")
return map[string]interface{} {
"info": leverage,
"symbol": GetValue(market, "symbol"),
"marginMode": nil,
"longLeverage": leverageNum,
"shortLeverage": leverageNum,
}
}
func (this *kucoinfutures) Init(userConfig map[string]interface{}) {
this.kucoin.Init(this.DeepExtend(this.Describe(), userConfig))
this.Itf = this
this.Exchange.DerivedExchange = this
}