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

2616 lines
106 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 defx struct {
Exchange
}
func NewDefxCore() defx {
p := defx{}
setDefaults(&p)
return p
}
func (this *defx) Describe() interface{} {
return this.DeepExtend(this.Exchange.Describe(), map[string]interface{} {
"id": "defx",
"name": "Defx X",
"rateLimit": 100,
"version": "v1",
"certified": false,
"pro": false,
"hostname": "defx.com",
"dex": true,
"has": map[string]interface{} {
"CORS": nil,
"spot": false,
"margin": false,
"swap": true,
"future": false,
"option": false,
"addMargin": true,
"cancelAllOrders": true,
"cancelAllOrdersAfter": false,
"cancelOrder": true,
"cancelWithdraw": false,
"closeAllPositions": true,
"closePosition": true,
"createConvertTrade": false,
"createDepositAddress": false,
"createMarketBuyOrderWithCost": false,
"createMarketOrder": false,
"createMarketOrderWithCost": false,
"createMarketSellOrderWithCost": false,
"createOrder": true,
"createOrderWithTakeProfitAndStopLoss": true,
"createReduceOnlyOrder": true,
"createStopLimitOrder": false,
"createStopLossOrder": false,
"createStopMarketOrder": false,
"createStopOrder": false,
"createTakeProfitOrder": true,
"createTrailingAmountOrder": false,
"createTrailingPercentOrder": false,
"createTriggerOrder": true,
"fetchAccounts": false,
"fetchBalance": true,
"fetchCanceledOrders": true,
"fetchClosedOrder": false,
"fetchClosedOrders": true,
"fetchConvertCurrencies": false,
"fetchConvertQuote": false,
"fetchConvertTrade": false,
"fetchConvertTradeHistory": false,
"fetchCurrencies": false,
"fetchDepositAddress": false,
"fetchDepositAddresses": false,
"fetchDepositAddressesByNetwork": false,
"fetchDeposits": false,
"fetchDepositsWithdrawals": false,
"fetchFundingHistory": false,
"fetchFundingInterval": false,
"fetchFundingIntervals": false,
"fetchFundingRate": true,
"fetchFundingRateHistory": false,
"fetchFundingRates": false,
"fetchIndexOHLCV": false,
"fetchLedger": true,
"fetchLeverage": false,
"fetchMarginAdjustmentHistory": false,
"fetchMarginMode": false,
"fetchMarkets": true,
"fetchMarkOHLCV": false,
"fetchMarkPrice": false,
"fetchMarkPrices": false,
"fetchMyTrades": true,
"fetchOHLCV": true,
"fetchOpenInterestHistory": false,
"fetchOpenOrder": false,
"fetchOpenOrders": true,
"fetchOrder": true,
"fetchOrderBook": true,
"fetchOrders": true,
"fetchOrderTrades": false,
"fetchPosition": true,
"fetchPositionHistory": false,
"fetchPositionMode": false,
"fetchPositions": true,
"fetchPositionsHistory": false,
"fetchPremiumIndexOHLCV": false,
"fetchStatus": true,
"fetchTicker": true,
"fetchTickers": true,
"fetchTime": true,
"fetchTrades": true,
"fetchTradingFee": false,
"fetchTradingFees": false,
"fetchTransactions": false,
"fetchTransfers": false,
"fetchWithdrawals": false,
"reduceMargin": false,
"sandbox": true,
"setLeverage": true,
"setMargin": false,
"setPositionMode": false,
"transfer": false,
"withdraw": true,
},
"timeframes": map[string]interface{} {
"1m": "1m",
"3m": "3m",
"5m": "5m",
"15m": "15m",
"30m": "30m",
"1h": "1h",
"2h": "2h",
"4h": "4h",
"12h": "12h",
"1d": "1d",
"1w": "1w",
"1M": "1M",
},
"urls": map[string]interface{} {
"logo": "https://github.com/user-attachments/assets/4e92bace-d7a9-45ea-92be-122168dc87e4",
"api": map[string]interface{} {
"public": "https://api.{hostname}",
"private": "https://api.{hostname}",
},
"test": map[string]interface{} {
"public": "https://api.testnet.{hostname}",
"private": "https://api.testnet.{hostname}",
},
"www": "https://defx.com/home",
"doc": []interface{}{"https://docs.defx.com/docs", "https://api-docs.defx.com/"},
"fees": []interface{}{""},
"referral": map[string]interface{} {
"url": "https://app.defx.com/join/6I2CZ7",
},
},
"api": map[string]interface{} {
"v1": map[string]interface{} {
"public": map[string]interface{} {
"get": map[string]interface{} {
"healthcheck/ping": 1,
"symbols/{symbol}/ohlc": 1,
"symbols/{symbol}/trades": 1,
"symbols/{symbol}/prices": 1,
"symbols/{symbol}/ticker/24hr": 1,
"symbols/{symbol}/depth/{level}/{slab}": 1,
"ticker/24HrAgg": 1,
"c/markets": 1,
"c/markets/metadata": 1,
"analytics/market/stats/newUsers": 1,
"analytics/market/stats/tvl": 1,
"analytics/market/stats/volumeByInstrument": 1,
"analytics/market/stats/liquidation": 1,
"analytics/market/stats/totalVolume": 1,
"analytics/market/stats/openInterest": 1,
"analytics/market/stats/totalTrades": 1,
"analytics/market/stats/basis": 1,
"analytics/market/stats/insuranceFund": 1,
"analytics/market/stats/longAndShortRatio": 1,
"analytics/market/stats/fundingRate": 1,
"analytics/market/overview": 1,
"explorer/search": 1,
"explorer/transactions": 1,
"explorer/blocks": 1,
},
},
"private": map[string]interface{} {
"get": map[string]interface{} {
"api/order/{orderId}": 1,
"api/orders": 1,
"api/orders/oco/{parentOrderId}": 1,
"api/trades": 1,
"api/position/active": 1,
"api/users/metadata/leverage": 1,
"api/users/metadata/feeMultiplier": 1,
"api/users/metadata/slippage": 1,
"api/users/referral": 1,
"api/users/apikeys": 1,
"connection-signature-message/evm": 1,
"api/users/profile/wallets": 1,
"api/notifications": 1,
"api/wallet/balance": 1,
"api/wallet/transactions": 1,
"api/analytics/user/overview": 1,
"api/analytics/user/pnl": 1,
"api/analytics/points/overview": 1,
"api/analytics/points/history": 1,
},
"post": map[string]interface{} {
"api/order": 1,
"api/position/oco": 1,
"api/users/socket/listenKeys": 1,
"api/users/metadata/leverage": 1,
"api/users/metadata/feeMultiplier": 1,
"api/users/metadata/slippage": 1,
"api/users/referral/recordReferralSignup": 1,
"api/users/apikeys": 1,
"api/users/profile/wallets": 1,
"api/transfers/withdrawal": 1,
"api/transfers/bridge/withdrawal": 1,
},
"put": map[string]interface{} {
"api/position/updatePositionMargin": 1,
"api/users/socket/listenKeys/{listenKey}": 1,
"api/users/apikeys/{accessKey}/status": 1,
"api/users/referral": 1,
},
"patch": map[string]interface{} {
"api/users/apikeys/{accessKey}": 1,
},
"delete": map[string]interface{} {
"api/orders/allOpen": 1,
"api/order/{orderId}": 1,
"api/position/{positionId}": 1,
"api/position/all": 1,
"api/users/socket/listenKeys/{listenKey}": 1,
"api/users/apikeys/{accessKey}": 1,
},
},
},
},
"fees": map[string]interface{} {
"trading": map[string]interface{} {
"tierBased": true,
"percentage": true,
"maker": this.ParseNumber("0.0002"),
"taker": this.ParseNumber("0.0005"),
},
},
"options": map[string]interface{} {
"sandboxMode": false,
},
"features": map[string]interface{} {
"spot": nil,
"forDerivatives": map[string]interface{} {
"sandbox": true,
"createOrder": map[string]interface{} {
"marginMode": false,
"triggerPrice": true,
"triggerPriceType": map[string]interface{} {
"last": true,
"mark": true,
"index": false,
},
"triggerDirection": false,
"stopLossPrice": false,
"takeProfitPrice": false,
"attachedStopLossTakeProfit": nil,
"timeInForce": map[string]interface{} {
"IOC": true,
"FOK": true,
"PO": true,
"GTD": false,
},
"hedged": false,
"selfTradePrevention": false,
"trailing": false,
"iceberg": false,
"leverage": false,
"marketBuyByCost": false,
"marketBuyRequiresPrice": false,
},
"createOrders": nil,
"fetchMyTrades": map[string]interface{} {
"marginMode": false,
"limit": 1000,
"daysBack": nil,
"untilDays": nil,
"symbolRequired": false,
},
"fetchOrder": map[string]interface{} {
"marginMode": false,
"trigger": false,
"trailing": false,
"symbolRequired": false,
},
"fetchOpenOrders": map[string]interface{} {
"marginMode": true,
"limit": 100,
"trigger": false,
"trailing": false,
"symbolRequired": false,
},
"fetchOrders": map[string]interface{} {
"marginMode": false,
"limit": 500,
"daysBack": 100000,
"untilDays": 100000,
"trigger": false,
"trailing": false,
"symbolRequired": false,
},
"fetchClosedOrders": map[string]interface{} {
"marginMode": false,
"limit": 500,
"daysBack": 100000,
"daysBackCanceled": 1,
"untilDays": 100000,
"trigger": false,
"trailing": false,
"symbolRequired": false,
},
"fetchOHLCV": map[string]interface{} {
"limit": 1000,
},
},
"swap": map[string]interface{} {
"linear": map[string]interface{} {
"extends": "forDerivatives",
},
"inverse": nil,
},
"future": map[string]interface{} {
"linear": nil,
"inverse": nil,
},
},
"commonCurrencies": map[string]interface{} {},
"exceptions": map[string]interface{} {
"exact": map[string]interface{} {
"404": BadRequest,
"missing_auth_signature": AuthenticationError,
"order_rejected": InvalidOrder,
"invalid_order_id": InvalidOrder,
"filter_lotsize_maxqty": InvalidOrder,
"filter_notional_min": InvalidOrder,
"failed_index_price_up_multiplier_filter": InvalidOrder,
"no_open_orders": InvalidOrder,
"active_position_not_found": InvalidOrder,
"position_inactive": InvalidOrder,
"invalid_position_id": InvalidOrder,
"Internal server error": ExchangeError,
},
"broad": map[string]interface{} {
"Bad Request": BadRequest,
},
},
"precisionMode": TICK_SIZE,
})
}
/**
* @method
* @name defx#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://api-docs.defx.com/#4b03bb3b-a0fa-4dfb-b96c-237bde0ce9e6
* @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 *defx) 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.V1PublicGetHealthcheckPing(params))
PanicOnError(response)
//
// {
// "success": true,
// "t": 1709705048323,
// "v": "0.0.7",
// "msg": "A programmers wife tells him, “While youre at the grocery store, buy some eggs.” He never comes back."
// }
//
var status interface{} = nil
var success interface{} = this.SafeBool(response, "success")
if IsTrue(success) {
status = "ok"
} else {
status = "error"
}
ch <- map[string]interface{} {
"status": status,
"updated": nil,
"eta": nil,
"url": nil,
"info": response,
}
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://api-docs.defx.com/#4b03bb3b-a0fa-4dfb-b96c-237bde0ce9e6
* @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 *defx) 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.V1PublicGetHealthcheckPing(params))
PanicOnError(response)
//
// {
// "success": true,
// "t": 1709705048323,
// "v": "0.0.7",
// "msg": "A programmers wife tells him, “While youre at the grocery store, buy some eggs.” He never comes back."
// }
//
ch <- this.SafeInteger(response, "t")
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchMarkets
* @description retrieves data on all markets for defx
* @see https://api-docs.defx.com/#73cce0c8-f842-4891-9145-01bb6d61324d
* @see https://api-docs.defx.com/#24fd4e5b-840e-451e-99e0-7fea47c7f371
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
func (this *defx) FetchMarkets(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
var request interface{} = map[string]interface{} {
"type": "perps",
}
var promises interface{} = []interface{}{this.V1PublicGetCMarkets(this.Extend(request, params)), this.V1PublicGetCMarketsMetadata(this.Extend(request, params))}
responses:= (<-promiseAll(promises))
PanicOnError(responses)
//
// {
// "data": [
// {
// "market": "DOGE_USDC",
// "candleWindows": [
// "1m",
// "3m",
// "5m",
// "15m",
// "30m",
// "1h",
// "2h",
// "4h",
// "12h",
// "1d",
// "1w",
// "1M"
// ],
// "depthSlabs": [
// "0.00001",
// "0.00005",
// "0.0001",
// "0.001",
// "0.01"
// ],
// "filters": [
// {
// "filterType": "LOT_SIZE",
// "minQty": "1.00000",
// "maxQty": "1500000.00000",
// "stepSize": "1.00000"
// },
// {
// "filterType": "MARKET_LOT_SIZE",
// "minQty": "1.00000",
// "maxQty": "750000.00000",
// "stepSize": "1.00000"
// },
// {
// "filterType": "PRICE_FILTER",
// "minPrice": "0.00244000",
// "maxPrice": "30.00000000",
// "tickSize": "0.00001"
// },
// {
// "filterType": "NOTIONAL",
// "minNotional": "100.00000000"
// },
// {
// "filterType": "PERCENT_PRICE_BY_SIDE",
// "bidMultiplierUp": "1.5",
// "bidMultiplierDown": "0.5",
// "askMultiplierUp": "1.5",
// "askMultiplierDown": "0.5"
// },
// {
// "filterType": "INDEX_PRICE_FILTER",
// "multiplierUp": "1.3",
// "multiplierDown": "0.7"
// }
// ],
// "cappedLeverage": "25",
// "maintenanceMarginTiers": [
// {
// "tier": "1",
// "minMaintenanceMargin": "0",
// "maxMaintenanceMargin": "2500",
// "leverage": "25"
// },
// {
// "tier": "2",
// "minMaintenanceMargin": "2500",
// "maxMaintenanceMargin": "12500",
// "leverage": "20"
// },
// {
// "tier": "3",
// "minMaintenanceMargin": "12500",
// "maxMaintenanceMargin": "25000",
// "leverage": "15"
// },
// {
// "tier": "4",
// "minMaintenanceMargin": "25000",
// "maxMaintenanceMargin": "50000",
// "leverage": "10"
// },
// {
// "tier": "5",
// "minMaintenanceMargin": "50000",
// "maxMaintenanceMargin": "75000",
// "leverage": "8"
// },
// {
// "tier": "6",
// "minMaintenanceMargin": "75000",
// "maxMaintenanceMargin": "125000",
// "leverage": "7"
// },
// {
// "tier": "7",
// "minMaintenanceMargin": "125000",
// "maxMaintenanceMargin": "187500",
// "leverage": "5"
// },
// {
// "tier": "8",
// "minMaintenanceMargin": "187500",
// "maxMaintenanceMargin": "250000",
// "leverage": "3"
// },
// {
// "tier": "9",
// "minMaintenanceMargin": "250000",
// "maxMaintenanceMargin": "375000",
// "leverage": "2"
// },
// {
// "tier": "10",
// "minMaintenanceMargin": "375000",
// "maxMaintenanceMargin": "500000",
// "leverage": "1"
// }
// ],
// "fees": {
// "maker": "0.08",
// "taker": "0.1"
// }
// },
// ]
// }
//
var activeMarkets interface{} = this.SafeList(GetValue(responses, 0), "data")
var activeMarketsByType interface{} = this.IndexBy(activeMarkets, "market")
var marketMetadatas interface{} = this.SafeList(GetValue(responses, 1), "data")
for i := 0; IsLessThan(i, GetArrayLength(marketMetadatas)); i++ {
var marketId interface{} = GetValue(GetValue(marketMetadatas, i), "market")
var status interface{} = nil
if IsTrue(InOp(activeMarketsByType, marketId)) {
status = GetValue(GetValue(activeMarketsByType, marketId), "status")
}
AddElementToObject(GetValue(marketMetadatas, i), "status", status)
}
ch <- this.ParseMarkets(marketMetadatas)
return nil
}()
return ch
}
func (this *defx) ParseMarket(market interface{}) interface{} {
var marketId interface{} = this.SafeString(market, "market")
var parts interface{} = Split(marketId, "_")
var baseId interface{} = this.SafeString(parts, 0)
var quoteId interface{} = this.SafeString(parts, 1)
var base interface{} = this.SafeCurrencyCode(baseId)
var quote interface{} = this.SafeCurrencyCode(quoteId)
var symbol interface{} = Add(Add(Add(Add(base, "/"), quote), ":"), quote)
var filters interface{} = this.SafeList(market, "filters", []interface{}{})
var fees interface{} = this.SafeDict(market, "fees", map[string]interface{} {})
var filtersByType interface{} = this.IndexBy(filters, "filterType")
var priceFilter interface{} = this.SafeDict(filtersByType, "PRICE_FILTER", map[string]interface{} {})
var lotFilter interface{} = this.SafeDict(filtersByType, "LOT_SIZE", map[string]interface{} {})
var marketLotFilter interface{} = this.SafeDict(filtersByType, "MARKET_LOT_SIZE", map[string]interface{} {})
var notionalFilter interface{} = this.SafeDict(filtersByType, "NOTIONAL", map[string]interface{} {})
return map[string]interface{} {
"id": marketId,
"symbol": symbol,
"base": base,
"quote": quote,
"settle": quote,
"baseId": baseId,
"quoteId": quoteId,
"settleId": quoteId,
"type": "swap",
"spot": false,
"margin": false,
"swap": true,
"future": false,
"option": false,
"active": IsEqual(this.SafeString(market, "status", ""), "active"),
"contract": true,
"linear": true,
"inverse": nil,
"taker": this.SafeNumber(fees, "taker"),
"maker": this.SafeNumber(fees, "maker"),
"contractSize": this.ParseNumber("1"),
"expiry": nil,
"expiryDatetime": nil,
"strike": nil,
"optionType": nil,
"precision": map[string]interface{} {
"amount": this.SafeNumber(lotFilter, "stepSize"),
"price": this.SafeNumber(priceFilter, "tickSize"),
},
"limits": map[string]interface{} {
"leverage": map[string]interface{} {
"min": nil,
"max": this.SafeNumber(market, "cappedLeverage"),
},
"amount": map[string]interface{} {
"min": this.SafeNumber(lotFilter, "minQty"),
"max": this.SafeNumber(lotFilter, "maxQty"),
},
"price": map[string]interface{} {
"min": this.SafeNumber(priceFilter, "minPrice"),
"max": this.SafeNumber(priceFilter, "maxPrice"),
},
"cost": map[string]interface{} {
"min": this.SafeNumber(notionalFilter, "minNotional"),
"max": nil,
},
"market": map[string]interface{} {
"min": this.SafeNumber(marketLotFilter, "minQty"),
"max": this.SafeNumber(marketLotFilter, "maxQty"),
},
},
"created": nil,
"info": market,
}
}
/**
* @method
* @name defx#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://api-docs.defx.com/#fe6f81d0-2f3a-4eee-976f-c8fc8f4c5d56
* @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 *defx) 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
retRes6668 := (<-this.LoadMarkets())
PanicOnError(retRes6668)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.V1PublicGetSymbolsSymbolTicker24hr(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "symbol": "BTC_USDC",
// "priceChange": "0",
// "priceChangePercent": "0",
// "weightedAvgPrice": "0",
// "lastPrice": "2.00",
// "lastQty": "10.000",
// "bestBidPrice": "1646.00",
// "bestBidQty": "10.000",
// "bestAskPrice": "1646.00",
// "bestAskQty": "10.000",
// "openPrice": "0.00",
// "highPrice": "0.00",
// "lowPrice": "0.00",
// "volume": "0.000",
// "quoteVolume": "0.00",
// "openTime": 1700142658697,
// "closeTime": 1700142658697,
// "openInterestBase": "1.000",
// "openInterestQuote": "0.43112300"
// }
//
ch <- this.ParseTicker(response, market)
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://api-docs.defx.com/#8c61cfbd-40d9-410e-b014-f5b36eba51d1
* @param {string[]|undefined} symbols unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *defx) 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
retRes7088 := (<-this.LoadMarkets())
PanicOnError(retRes7088)
var market interface{} = nil
if IsTrue(!IsEqual(symbols, nil)) {
symbols = this.MarketSymbols(symbols)
var firstSymbol interface{} = this.SafeString(symbols, 0)
if IsTrue(!IsEqual(firstSymbol, nil)) {
market = this.Market(firstSymbol)
}
}
var typeVar interface{} = nil
typeVarparamsVariable := this.HandleMarketTypeAndParams("fetchTickers", market, params);
typeVar = GetValue(typeVarparamsVariable,0);
params = GetValue(typeVarparamsVariable,1)
if IsTrue(IsEqual(typeVar, "spot")) {
panic(NotSupported(Add(Add(Add(this.Id, " fetchTickers() is not supported for "), typeVar), " markets")))
}
response:= (<-this.V1PublicGetTicker24HrAgg(params))
PanicOnError(response)
//
// {
// "ETH_USDC": {
// "priceChange": "0",
// "priceChangePercent": "0",
// "openPrice": "1646.15",
// "highPrice": "1646.15",
// "lowPrice": "1646.15",
// "lastPrice": "1646.15",
// "quoteVolume": "13.17",
// "volume": "0.008",
// "markPrice": "1645.15"
// }
// }
//
ch <- this.ParseTickers(response, symbols)
return nil
}()
return ch
}
func (this *defx) ParseTicker(ticker interface{}, optionalArgs ...interface{}) interface{} {
//
// fetchTicker
//
// {
// "symbol": "BTC_USDC",
// "priceChange": "0",
// "priceChangePercent": "0",
// "weightedAvgPrice": "0",
// "lastPrice": "2.00",
// "lastQty": "10.000",
// "bestBidPrice": "1646.00",
// "bestBidQty": "10.000",
// "bestAskPrice": "1646.00",
// "bestAskQty": "10.000",
// "openPrice": "0.00",
// "highPrice": "0.00",
// "lowPrice": "0.00",
// "volume": "0.000",
// "quoteVolume": "0.00",
// "openTime": 1700142658697,
// "closeTime": 1700142658697,
// "openInterestBase": "1.000",
// "openInterestQuote": "0.43112300"
// }
//
// fetchTickers
//
// "ETH_USDC": {
// "priceChange": "0",
// "priceChangePercent": "0",
// "openPrice": "1646.15",
// "highPrice": "1646.15",
// "lowPrice": "1646.15",
// "lastPrice": "1646.15",
// "quoteVolume": "13.17",
// "volume": "0.008",
// "markPrice": "1645.15"
// }
//
// fetchMarkPrice
//
// {
// "markPrice": "100.00",
// "indexPrice": "100.00",
// "ltp": "101.34",
// "movingFundingRate": "0.08",
// "payoutFundingRate": "-0.03",
// "nextFundingPayout": 1711555532146
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(ticker, "symbol")
if IsTrue(!IsEqual(marketId, nil)) {
market = this.Market(marketId)
}
var symbol interface{} = GetValue(market, "symbol")
var open interface{} = this.SafeString(ticker, "openPrice")
var high interface{} = this.SafeString(ticker, "highPrice")
var low interface{} = this.SafeString(ticker, "lowPrice")
var close interface{} = this.SafeString(ticker, "lastPrice")
var quoteVolume interface{} = this.SafeString(ticker, "quoteVolume")
var baseVolume interface{} = this.SafeString(ticker, "volume")
var percentage interface{} = this.SafeString(ticker, "priceChangePercent")
var change interface{} = this.SafeString(ticker, "priceChange")
var ts interface{} = this.SafeInteger(ticker, "closeTime")
if IsTrue(IsEqual(ts, 0)) {
ts = nil
}
var datetime interface{} = this.Iso8601(ts)
var bid interface{} = this.SafeString(ticker, "bestBidPrice")
var bidVolume interface{} = this.SafeString(ticker, "bestBidQty")
var ask interface{} = this.SafeString(ticker, "bestAskPrice")
var askVolume interface{} = this.SafeString(ticker, "bestAskQty")
return this.SafeTicker(map[string]interface{} {
"symbol": symbol,
"timestamp": ts,
"datetime": datetime,
"high": high,
"low": low,
"bid": bid,
"bidVolume": bidVolume,
"ask": ask,
"askVolume": askVolume,
"vwap": nil,
"open": open,
"close": close,
"last": nil,
"previousClose": nil,
"change": change,
"percentage": percentage,
"average": nil,
"baseVolume": baseVolume,
"quoteVolume": quoteVolume,
"markPrice": this.SafeString(ticker, "markPrice"),
"indexPrice": this.SafeString(ticker, "indexPrice"),
"info": ticker,
}, market)
}
/**
* @method
* @name defx#fetchOHLCV
* @see https://api-docs.defx.com/#54b71951-1472-4670-b5af-4c2dc41e73d0
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @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] max=1000, max=100 when since is defined and is less than (now - (999 * (timeframe in ms)))
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
func (this *defx) 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
retRes8548 := (<-this.LoadMarkets())
PanicOnError(retRes8548)
var market interface{} = this.Market(symbol)
var maxLimit interface{} = 1000
if IsTrue(IsEqual(limit, nil)) {
limit = maxLimit
}
limit = mathMin(maxLimit, limit)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"interval": this.SafeString(this.Timeframes, timeframe, timeframe),
"limit": limit,
}
var until interface{} = this.SafeInteger2(params, "until", "till")
params = this.Omit(params, []interface{}{"until", "till"})
AddElementToObject(request, "endTime", Ternary(IsTrue((IsEqual(until, nil))), this.Milliseconds(), until))
if IsTrue(IsEqual(since, nil)) {
AddElementToObject(request, "startTime", 0)
} else {
AddElementToObject(request, "startTime", since)
if IsTrue(IsEqual(until, nil)) {
var timeframeInSeconds interface{} = this.ParseTimeframe(timeframe)
var timeframeInMilliseconds interface{} = Multiply(timeframeInSeconds, 1000)
var totalTimeframeInMilliseconds interface{} = Multiply(limit, timeframeInMilliseconds)
AddElementToObject(request, "endTime", this.Sum(since, totalTimeframeInMilliseconds))
}
}
response:= (<-this.V1PublicGetSymbolsSymbolOhlc(this.Extend(request, params)))
PanicOnError(response)
//
// [
// {
// "symbol": "BTC_USDC",
// "open": "0.00",
// "high": "0.00",
// "low": "0.00",
// "close": "0.00",
// "volume": "0.000",
// "quoteAssetVolume": "0.00",
// "takerBuyAssetVolume": "0.000",
// "takerBuyQuoteAssetVolume": "0.00",
// "numberOfTrades": 0,
// "start": 1702453663894,
// "end": 1702453663894,
// "isClosed": true
// }
// ]
//
ch <- this.ParseOHLCVs(response, market, timeframe, since, limit)
return nil
}()
return ch
}
func (this *defx) ParseOHLCV(ohlcv interface{}, optionalArgs ...interface{}) interface{} {
// example response in fetchOHLCV
market := GetArg(optionalArgs, 0, nil)
_ = market
return []interface{}{this.SafeInteger(ohlcv, "start"), this.SafeNumber(ohlcv, "open"), this.SafeNumber(ohlcv, "high"), this.SafeNumber(ohlcv, "low"), this.SafeNumber(ohlcv, "close"), this.SafeNumber(ohlcv, "volume")}
}
/**
* @method
* @name defx#fetchTrades
* @description get the list of most recent trades for a particular symbol
* @see https://api-docs.defx.com/#5865452f-ea32-4f13-bfbc-03af5f5574fd
* @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 *defx) 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
retRes9278 := (<-this.LoadMarkets())
PanicOnError(retRes9278)
var market interface{} = this.Market(symbol)
var maxLimit interface{} = 50
if IsTrue(IsEqual(limit, nil)) {
limit = maxLimit
}
limit = mathMin(maxLimit, limit)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"limit": limit,
}
response:= (<-this.V1PublicGetSymbolsSymbolTrades(this.Extend(request, params)))
PanicOnError(response)
//
// [
// {
// "buyerMaker": "false",
// "price": "2.0000",
// "qty": "10.0000",
// "symbol": "BTC_USDC",
// "timestamp": "1702453663894"
// }
// ]
//
ch <- this.ParseTrades(response, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchMyTrades
* @description fetch all trades made by the user
* @see https://api-docs.defx.com/#06b5b33c-2fc6-48de-896c-fc316f5871a7
* @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 *defx) 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
retRes9658 := (<-this.LoadMarkets())
PanicOnError(retRes9658)
var request interface{} = map[string]interface{} {}
if IsTrue(!IsEqual(symbol, nil)) {
var market interface{} = this.Market(symbol)
AddElementToObject(request, "symbols", GetValue(market, "id"))
}
if IsTrue(!IsEqual(limit, nil)) {
var maxLimit interface{} = 100
limit = mathMin(maxLimit, limit)
AddElementToObject(request, "pageSize", limit)
}
response:= (<-this.V1PrivateGetApiTrades(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "data": [
// {
// "id": "0192f665-c05b-7ba0-a080-8b6c99083489",
// "orderId": "757730811259651728",
// "time": "2024-11-04T08:58:36.474Z",
// "symbol": "SOL_USDC",
// "side": "SELL",
// "price": "160.43600000",
// "qty": "1.00",
// "fee": "0.08823980",
// "role": "TAKER",
// "pnl": "0.00000000"
// }
// ]
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseTrades(data, nil, since, limit)
return nil
}()
return ch
}
func (this *defx) ParseTrade(trade interface{}, optionalArgs ...interface{}) interface{} {
//
// fetchTrades
// {
// "buyerMaker": "false",
// "price": "2.0000",
// "qty": "10.0000",
// "symbol": "BTC_USDC",
// "timestamp": "1702453663894"
// }
//
// fetchMyTrades
// {
// "id": "0192f665-c05b-7ba0-a080-8b6c99083489",
// "orderId": "757730811259651728",
// "time": "2024-11-04T08:58:36.474Z",
// "symbol": "SOL_USDC",
// "side": "SELL",
// "price": "160.43600000",
// "qty": "1.00",
// "fee": "0.08823980",
// "role": "TAKER",
// "pnl": "0.00000000"
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var time interface{} = this.SafeString(trade, "time")
var timestamp interface{} = this.SafeInteger(trade, "timestamp", this.Parse8601(time))
var marketId interface{} = this.SafeString(trade, "symbol")
market = this.SafeMarket(marketId, market)
var symbol interface{} = GetValue(market, "symbol")
var price interface{} = this.SafeString(trade, "price")
var amount interface{} = this.SafeString(trade, "qty")
var id interface{} = this.SafeString(trade, "id")
var oid interface{} = this.SafeString(trade, "orderId")
var takerOrMaker interface{} = this.SafeStringLower(trade, "role")
var buyerMaker interface{} = this.SafeBool(trade, "buyerMaker")
var side interface{} = this.SafeStringLower(trade, "side")
if IsTrue(!IsEqual(buyerMaker, nil)) {
if IsTrue(buyerMaker) {
side = "sell"
} else {
side = "buy"
}
}
return this.SafeTrade(map[string]interface{} {
"id": id,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"symbol": symbol,
"side": side,
"price": price,
"amount": amount,
"cost": nil,
"order": oid,
"takerOrMaker": takerOrMaker,
"type": nil,
"fee": map[string]interface{} {
"cost": this.SafeString(trade, "fee"),
"currency": "USDC",
},
"info": trade,
}, market)
}
/**
* @method
* @name defx#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://api-docs.defx.com/#6c1a2971-8325-4e7d-9962-e0bfcaacf9c4
* @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
* @param {string} [params.slab] slab from market.info.depthSlabs
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/#/?id=order-book-structure} indexed by market symbols
*/
func (this *defx) 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
retRes10758 := (<-this.LoadMarkets())
PanicOnError(retRes10758)
var market interface{} = this.Market(symbol)
if IsTrue(IsEqual(limit, nil)) {
limit = 10 // limit must be one of [5, 10, 20]
}
var marketInfo interface{} = this.SafeDict(market, "info", map[string]interface{} {})
var slab interface{} = this.SafeList(marketInfo, "depthSlabs", []interface{}{})
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"level": limit,
"slab": this.SafeString(slab, 0),
}
response:= (<-this.V1PublicGetSymbolsSymbolDepthLevelSlab(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "symbol": "ETH_USDC",
// "level": "5",
// "slab": "1",
// "lastTradeTimestamp": "1708313446812",
// "timestamp": "1708313446812",
// "bids": [
// {
// "price": "1646.16",
// "qty": "0.001"
// }
// ],
// "asks": [
// {
// "price": "1646.16",
// "qty": "0.001"
// }
// ]
// }
//
var timestamp interface{} = this.SafeInteger(response, "timestamp")
ch <- this.ParseOrderBook(response, symbol, timestamp, "bids", "asks", "price", "qty")
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchMarkPrice
* @description fetches mark price for the market
* @see https://api-docs.defx.com/#12168192-4e7b-4458-a001-e8b80961f0b7
* @param {string} symbol unified symbol of the market to fetch the ticker for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.subType] "linear" or "inverse"
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *defx) 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
retRes11248 := (<-this.LoadMarkets())
PanicOnError(retRes11248)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.V1PublicGetSymbolsSymbolPrices(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "markPrice": "100.00",
// "indexPrice": "100.00",
// "ltp": "101.34",
// "movingFundingRate": "0.08",
// "payoutFundingRate": "-0.03",
// "nextFundingPayout": 1711555532146
// }
//
ch <- this.ParseTicker(response, market)
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchFundingRate
* @description fetch the current funding rate
* @see https://api-docs.defx.com/#12168192-4e7b-4458-a001-e8b80961f0b7
* @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 *defx) 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
retRes11538 := (<-this.LoadMarkets())
PanicOnError(retRes11538)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.V1PublicGetSymbolsSymbolPrices(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "markPrice": "100.00",
// "indexPrice": "100.00",
// "ltp": "101.34",
// "movingFundingRate": "0.08",
// "payoutFundingRate": "-0.03",
// "nextFundingPayout": 1711555532146
// }
//
ch <- this.ParseFundingRate(response, market)
return nil
}()
return ch
}
func (this *defx) ParseFundingRate(contract interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "markPrice": "100.00",
// "indexPrice": "100.00",
// "ltp": "101.34",
// "movingFundingRate": "0.08",
// "payoutFundingRate": "-0.03",
// "nextFundingPayout": 1711555532146
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var markPrice interface{} = this.SafeNumber(contract, "markPrice")
var indexPrice interface{} = this.SafeNumber(contract, "indexPrice")
var fundingRate interface{} = this.SafeNumber(contract, "payoutFundingRate")
var fundingTime interface{} = this.SafeInteger(contract, "nextFundingPayout")
return map[string]interface{} {
"info": contract,
"symbol": GetValue(market, "symbol"),
"markPrice": markPrice,
"indexPrice": indexPrice,
"interestRate": nil,
"estimatedSettlePrice": nil,
"timestamp": nil,
"datetime": nil,
"fundingRate": fundingRate,
"fundingTimestamp": fundingTime,
"fundingDatetime": this.Iso8601(fundingTime),
"nextFundingRate": nil,
"nextFundingTimestamp": nil,
"nextFundingDatetime": nil,
"previousFundingRate": nil,
"previousFundingTimestamp": nil,
"previousFundingDatetime": nil,
"interval": nil,
}
}
/**
* @method
* @name defx#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://api-docs.defx.com/#26414338-14f7-40a1-b246-f8ea8571493f
* @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 *defx) 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
retRes12188 := (<-this.LoadMarkets())
PanicOnError(retRes12188)
response:= (<-this.V1PrivateGetApiWalletBalance(params))
PanicOnError(response)
//
// {
// "assets": [
// {
// "asset": "USDC",
// "balance": "0.000"
// }
// ]
// }
//
var data interface{} = this.SafeList(response, "assets")
ch <- this.ParseBalance(data)
return nil
}()
return ch
}
func (this *defx) ParseBalance(balances interface{}) interface{} {
var result interface{} = map[string]interface{} {
"info": balances,
}
for i := 0; IsLessThan(i, GetArrayLength(balances)); i++ {
var balance interface{} = GetValue(balances, i)
var code interface{} = this.SafeCurrencyCode(this.SafeString(balance, "asset"))
var account interface{} = this.Account()
AddElementToObject(account, "total", this.SafeString(balance, "balance"))
AddElementToObject(result, code, account)
}
return this.SafeBalance(result)
}
/**
* @method
* @name defx#createOrder
* @description create a trade order
* @see https://api-docs.defx.com/#ba222d88-8856-4d3c-87a9-7cec07bb2622
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much of currency you want to trade in units of base currency
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {float} [params.triggerPrice] The price a trigger order is triggered at
* @param {string} [params.reduceOnly] for swap and future reduceOnly is a string 'true' or 'false' that cant be sent with close position set to true or in hedge mode. For spot margin and option reduceOnly is a boolean.
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *defx) 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
retRes12648 := (<-this.LoadMarkets())
PanicOnError(retRes12648)
var market interface{} = this.Market(symbol)
var reduceOnly interface{} = this.SafeBool2(params, "reduceOnly", "reduce_only")
params = this.Omit(params, []interface{}{"reduceOnly", "reduce_only"})
var orderType interface{} = ToUpper(typeVar)
var orderSide interface{} = ToUpper(side)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
"side": orderSide,
"type": orderType,
}
var takeProfitPrice interface{} = this.SafeString(params, "takeProfitPrice")
var triggerPrice interface{} = this.SafeString2(params, "stopPrice", "triggerPrice")
var isMarket interface{} = IsEqual(orderType, "MARKET")
var isLimit interface{} = IsEqual(orderType, "LIMIT")
var timeInForce interface{} = this.SafeStringUpper(params, "timeInForce")
if IsTrue(!IsEqual(timeInForce, nil)) {
// GTC, IOC, FOK, AON
AddElementToObject(request, "timeInForce", timeInForce)
} else {
if IsTrue(isLimit) {
AddElementToObject(request, "timeInForce", "GTC")
}
}
if IsTrue(reduceOnly) {
AddElementToObject(request, "reduceOnly", reduceOnly)
}
var clientOrderId interface{} = this.SafeString(params, "clientOrderId")
if IsTrue(!IsEqual(clientOrderId, nil)) {
AddElementToObject(request, "newClientOrderId", clientOrderId)
}
if IsTrue(IsTrue(!IsEqual(triggerPrice, nil)) || IsTrue(!IsEqual(takeProfitPrice, nil))) {
AddElementToObject(request, "workingType", "MARK_PRICE")
if IsTrue(!IsEqual(takeProfitPrice, nil)) {
AddElementToObject(request, "stopPrice", this.PriceToPrecision(symbol, takeProfitPrice))
if IsTrue(isMarket) {
AddElementToObject(request, "type", "TAKE_PROFIT_MARKET")
} else {
AddElementToObject(request, "type", "TAKE_PROFIT_LIMIT")
}
} else {
AddElementToObject(request, "stopPrice", this.PriceToPrecision(symbol, triggerPrice))
if IsTrue(isMarket) {
AddElementToObject(request, "type", "STOP_MARKET")
} else {
AddElementToObject(request, "type", "STOP_LIMIT")
}
}
}
if IsTrue(IsTrue(isLimit) && IsTrue(!IsEqual(price, nil))) {
AddElementToObject(request, "price", this.PriceToPrecision(symbol, price))
}
AddElementToObject(request, "quantity", this.AmountToPrecision(symbol, amount))
params = this.Omit(params, []interface{}{"clOrdID", "clientOrderId", "client_order_id", "postOnly", "timeInForce", "stopPrice", "triggerPrice", "takeProfitPrice"})
response:= (<-this.V1PrivatePostApiOrder(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "success": true,
// "data": {
// "orderId": "",
// "clientOrderId": "",
// "cumulativeQty": "",
// "cumulativeQuote": "",
// "executedQty": "",
// "avgPrice": "",
// "origQty": "",
// "price": "",
// "reduceOnly": true,
// "side": "",
// "status": "",
// "symbol": "",
// "timeInForce": "",
// "type": "",
// "workingType": ""
// }
// }
//
var data interface{} = this.SafeDict(response, "data")
ch <- this.ParseOrder(data, market)
return nil
}()
return ch
}
func (this *defx) ParseOrderStatus(status interface{}) interface{} {
if IsTrue(!IsEqual(status, nil)) {
var statuses interface{} = map[string]interface{} {
"NEW": "open",
"OPEN": "open",
"CANCELLED": "canceled",
"REJECTED": "rejected",
"FILLED": "closed",
}
return this.SafeString(statuses, status, status)
}
return status
}
func (this *defx) ParseOrder(order interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "orderId": "746472647227344528",
// "createdAt": "2024-10-25T16:49:31.077Z",
// "updatedAt": "2024-10-25T16:49:31.378Z",
// "clientOrderId": "0192c495-49c3-71ee-b3d3-7442a2090807",
// "reduceOnly": false,
// "side": "SELL",
// "status": "FILLED",
// "symbol": "SOL_USDC",
// "timeInForce": "GTC",
// "type": "MARKET",
// "origQty": "0.80",
// "executedQty": "0.80",
// "cumulativeQuote": "137.87440000",
// "avgPrice": "172.34300000",
// "totalPnL": "0.00000000",
// "totalFee": "0.07583092",
// "workingType": null,
// "postOnly": false,
// "linkedOrderParentType": null,
// "isTriggered": false,
// "slippagePercentage": "5"
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var orderId interface{} = this.SafeString(order, "orderId")
var clientOrderId interface{} = this.SafeString(order, "clientOrderId")
var marketId interface{} = this.SafeString(order, "symbol")
market = this.SafeMarket(marketId, market)
var symbol interface{} = GetValue(market, "symbol")
var price interface{} = this.SafeString(order, "price")
var amount interface{} = this.SafeString(order, "origQty")
var orderType interface{} = this.SafeStringLower(order, "type")
var status interface{} = this.SafeString(order, "status")
var side interface{} = this.SafeStringLower(order, "side")
var filled interface{} = this.OmitZero(this.SafeString(order, "executedQty"))
var average interface{} = this.OmitZero(this.SafeString(order, "avgPrice"))
var timeInForce interface{} = this.SafeStringLower(order, "timeInForce")
var takeProfitPrice interface{} = nil
var triggerPrice interface{} = nil
if IsTrue(!IsEqual(orderType, nil)) {
if IsTrue(IsGreaterThanOrEqual(GetIndexOf(orderType, "take_profit"), 0)) {
takeProfitPrice = this.SafeString(order, "stopPrice")
} else {
triggerPrice = this.SafeString(order, "stopPrice")
}
}
var timestamp interface{} = this.Parse8601(this.SafeString(order, "createdAt"))
var lastTradeTimestamp interface{} = this.Parse8601(this.SafeString(order, "updatedAt"))
return this.SafeOrder(map[string]interface{} {
"id": orderId,
"clientOrderId": clientOrderId,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"lastTradeTimestamp": lastTradeTimestamp,
"lastUpdateTimestamp": lastTradeTimestamp,
"status": this.ParseOrderStatus(status),
"symbol": symbol,
"type": orderType,
"timeInForce": timeInForce,
"postOnly": this.SafeBool(order, "postOnly"),
"reduceOnly": this.SafeBool(order, "reduceOnly"),
"side": side,
"price": price,
"triggerPrice": triggerPrice,
"takeProfitPrice": takeProfitPrice,
"stopLossPrice": nil,
"average": average,
"amount": amount,
"filled": filled,
"remaining": nil,
"cost": nil,
"trades": nil,
"fee": map[string]interface{} {
"cost": this.SafeString(order, "totalFee"),
"currency": "USDC",
},
"info": order,
}, market)
}
/**
* @method
* @name defx#cancelOrder
* @see https://api-docs.defx.com/#09186f23-f8d1-4993-acf4-9974d8a6ddb0
* @description cancels an open 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 *defx) 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
retRes14528 := (<-this.LoadMarkets())
PanicOnError(retRes14528)
var request interface{} = map[string]interface{} {
"orderId": id,
"idType": "orderId",
}
var clientOrderId interface{} = this.SafeStringN(params, []interface{}{"clOrdID", "clientOrderId", "client_order_id"})
var isByClientOrder interface{} = !IsEqual(clientOrderId, nil)
if IsTrue(isByClientOrder) {
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " cancelOrder() requires a symbol argument")))
}
var market interface{} = this.Market(symbol)
AddElementToObject(request, "orderId", clientOrderId)
AddElementToObject(request, "idType", "clientOrderId")
AddElementToObject(request, "symbol", GetValue(market, "id"))
}
params = this.Omit(params, []interface{}{"clOrdID", "clientOrderId", "client_order_id"})
response:= (<-this.V1PrivateDeleteApiOrderOrderId(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "success": true
// }
//
var extendParams interface{} = map[string]interface{} {
"symbol": symbol,
}
if IsTrue(isByClientOrder) {
AddElementToObject(extendParams, "clientOrderId", clientOrderId)
} else {
AddElementToObject(extendParams, "id", id)
}
ch <- this.Extend(this.ParseOrder(response), extendParams)
return nil
}()
return ch
}
/**
* @method
* @name defx#cancelAllOrders
* @description cancel all open orders
* @see https://api-docs.defx.com/#db5531da-3692-4a53-841f-6ad6495f823a
* @param {string} symbol unified market symbol, only orders in the market of this symbol are cancelled when symbol is not undefined
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *defx) 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
retRes14948 := (<-this.LoadMarkets())
PanicOnError(retRes14948)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbols": []interface{}{GetValue(market, "id")},
}
response:= (<-this.V1PrivateDeleteApiOrdersAllOpen(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "data": {
// "msg": "The operation of cancel all open order is done."
// }
// }
//
ch <- response
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchPosition
* @description fetch data on a single open contract trade position
* @see https://api-docs.defx.com/#d89dbb86-9aba-4f59-ac5d-a97ff25ea80e
* @param {string} symbol unified market symbol of the market the position is held in, default is undefined
* @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 *defx) 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
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchPosition() requires a symbol argument")))
}
retRes15238 := (<-this.LoadMarkets())
PanicOnError(retRes15238)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"symbol": GetValue(market, "id"),
}
response:= (<-this.V1PrivateGetApiPositionActive(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "data": [
// {
// "positionId": "0192c495-4a68-70ee-9081-9d368bd16dfc",
// "symbol": "SOL_USDC",
// "positionSide": "SHORT",
// "entryPrice": "172.34300000",
// "quantity": "0.80",
// "marginAmount": "20.11561173",
// "marginAsset": "USDC",
// "pnl": "0.00000000"
// }
// ]
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
var first interface{} = this.SafeDict(data, 0, map[string]interface{} {})
ch <- this.ParsePosition(first, market)
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchPositions
* @description fetch all open positions
* @see https://api-docs.defx.com/#d89dbb86-9aba-4f59-ac5d-a97ff25ea80e
* @param {string[]} [symbols] list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *defx) 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
retRes15608 := (<-this.LoadMarkets())
PanicOnError(retRes15608)
response:= (<-this.V1PrivateGetApiPositionActive(params))
PanicOnError(response)
//
// {
// "data": [
// {
// "positionId": "0192c495-4a68-70ee-9081-9d368bd16dfc",
// "symbol": "SOL_USDC",
// "positionSide": "SHORT",
// "entryPrice": "172.34300000",
// "quantity": "0.80",
// "marginAmount": "20.11561173",
// "marginAsset": "USDC",
// "pnl": "0.00000000"
// }
// ]
// }
//
var positions interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParsePositions(positions, symbols)
return nil
}()
return ch
}
func (this *defx) ParsePosition(position interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "positionId": "0192c495-4a68-70ee-9081-9d368bd16dfc",
// "symbol": "SOL_USDC",
// "positionSide": "SHORT",
// "entryPrice": "172.34300000",
// "quantity": "0.80",
// "marginAmount": "20.11561173",
// "marginAsset": "USDC",
// "pnl": "0.00000000"
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(position, "symbol")
market = this.SafeMarket(marketId, market)
var size interface{} = Precise.StringAbs(this.SafeString(position, "quantity"))
var side interface{} = this.SafeStringLower(position, "positionSide")
var unrealisedPnl interface{} = this.OmitZero(this.SafeString(position, "pnl"))
var entryPrice interface{} = this.OmitZero(this.SafeString(position, "entryPrice"))
var initialMargin interface{} = this.SafeString(position, "marginAmount")
return this.SafePosition(map[string]interface{} {
"info": position,
"id": this.SafeString(position, "positionId"),
"symbol": GetValue(market, "symbol"),
"timestamp": nil,
"datetime": nil,
"lastUpdateTimestamp": nil,
"initialMargin": this.ParseNumber(initialMargin),
"initialMarginPercentage": nil,
"maintenanceMargin": nil,
"maintenanceMarginPercentage": nil,
"entryPrice": this.ParseNumber(entryPrice),
"notional": nil,
"leverage": nil,
"unrealizedPnl": this.ParseNumber(unrealisedPnl),
"realizedPnl": nil,
"contracts": this.ParseNumber(size),
"contractSize": this.SafeNumber(market, "contractSize"),
"marginRatio": nil,
"liquidationPrice": nil,
"markPrice": nil,
"lastPrice": nil,
"collateral": nil,
"marginMode": nil,
"side": side,
"percentage": nil,
"stopLossPrice": nil,
"takeProfitPrice": nil,
"hedged": nil,
})
}
/**
* @method
* @name defx#fetchOrder
* @description fetches information on an order made by the user
* @see https://api-docs.defx.com/#44f82dd5-26b3-4e1f-b4aa-88ceddd65237
* @param {string} id the order id
* @param {string} symbol unified symbol of the market the order was made in
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} An [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *defx) 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
retRes16458 := (<-this.LoadMarkets())
PanicOnError(retRes16458)
var request interface{} = map[string]interface{} {
"orderId": id,
"idType": "orderId",
}
var clientOrderId interface{} = this.SafeStringN(params, []interface{}{"clOrdID", "clientOrderId", "client_order_id"})
params = this.Omit(params, []interface{}{"clOrdID", "clientOrderId", "client_order_id"})
if IsTrue(!IsEqual(clientOrderId, nil)) {
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchOrder() requires a symbol argument")))
}
var market interface{} = this.Market(symbol)
AddElementToObject(request, "orderId", clientOrderId)
AddElementToObject(request, "idType", "clientOrderId")
AddElementToObject(request, "symbol", GetValue(market, "id"))
}
response:= (<-this.V1PrivateGetApiOrderOrderId(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "success": true,
// "data": {
// "orderId": "555068654076559792",
// "createdAt": "2024-05-08T05:45:42.148Z",
// "updatedAt": "2024-05-08T05:45:42.166Z",
// "clientOrderId": "dummyClientOrderId",
// "reduceOnly": false,
// "side": "SELL",
// "status": "REJECTED",
// "symbol": "BTC_USDC",
// "timeInForce": "GTC",
// "type": "TAKE_PROFIT_MARKET",
// "origQty": "1.000",
// "executedQty": "0.000",
// "cumulativeQuote": "0.00",
// "avgPrice": "0.00",
// "stopPrice": "65000.00",
// "totalPnL": "0.00",
// "workingType": "MARK_PRICE",
// "postOnly": false
// }
// }
//
var data interface{} = this.SafeDict(response, "data")
ch <- this.ParseOrder(data)
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchOrders
* @description fetches information on multiple orders made by the user
* @see https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *defx) FetchOrders(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes17048 := (<-this.LoadMarkets())
PanicOnError(retRes17048)
var request interface{} = map[string]interface{} {}
if IsTrue(!IsEqual(symbol, nil)) {
var market interface{} = this.Market(symbol)
AddElementToObject(request, "symbols", GetValue(market, "id"))
}
var until interface{} = this.SafeInteger(params, "until")
if IsTrue(!IsEqual(until, nil)) {
params = this.Omit(params, "until")
AddElementToObject(request, "end", this.Iso8601(until))
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "start", this.Iso8601(since))
}
if IsTrue(!IsEqual(limit, nil)) {
var maxLimit interface{} = 100
limit = mathMin(maxLimit, limit)
AddElementToObject(request, "pageSize", limit)
}
response:= (<-this.V1PrivateGetApiOrders(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "data": [
// {
// "orderId": "746472647227344528",
// "createdAt": "2024-10-25T16:49:31.077Z",
// "updatedAt": "2024-10-25T16:49:31.378Z",
// "clientOrderId": "0192c495-49c3-71ee-b3d3-7442a2090807",
// "reduceOnly": false,
// "side": "SELL",
// "status": "FILLED",
// "symbol": "SOL_USDC",
// "timeInForce": "GTC",
// "type": "MARKET",
// "origQty": "0.80",
// "executedQty": "0.80",
// "cumulativeQuote": "137.87440000",
// "avgPrice": "172.34300000",
// "totalPnL": "0.00000000",
// "totalFee": "0.07583092",
// "workingType": null,
// "postOnly": false,
// "linkedOrderParentType": null,
// "isTriggered": false,
// "slippagePercentage": 5
// }
// ]
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParseOrders(data, nil, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *defx) 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
var req interface{} = map[string]interface{} {
"statuses": "OPEN",
}
retRes177315 := (<-this.FetchOrders(symbol, since, limit, this.Extend(req, params)))
PanicOnError(retRes177315)
ch <- retRes177315
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *defx) 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
var req interface{} = map[string]interface{} {
"statuses": "FILLED",
}
retRes179215 := (<-this.FetchOrders(symbol, since, limit, this.Extend(req, params)))
PanicOnError(retRes179215)
ch <- retRes179215
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchCanceledOrders
* @description fetches information on multiple canceled orders made by the user
* @see https://api-docs.defx.com/#ab200038-8acb-4170-b05e-4fcb4cc13751
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open order structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch orders for
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *defx) FetchCanceledOrders(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
var req interface{} = map[string]interface{} {
"statuses": "CANCELED",
}
retRes181115 := (<-this.FetchOrders(symbol, since, limit, this.Extend(req, params)))
PanicOnError(retRes181115)
ch <- retRes181115
return nil
}()
return ch
}
/**
* @method
* @name defx#closePosition
* @description closes an open position for a market
* @see https://api-docs.defx.com/#b2c08074-c4d9-4e50-b637-0d6c498fa29e
* @param {string} symbol unified CCXT market symbol
* @param {string} [side] one-way mode: 'buy' or 'sell', hedge-mode: 'long' or 'short'
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.positionId] the position id you want to close
* @param {string} [params.type] 'MARKET' or 'LIMIT'
* @param {string} [params.quantity] how much of currency you want to trade in units of base currency
* @param {string} [params.price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @returns {object} An [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *defx) 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
retRes18298 := (<-this.LoadMarkets())
PanicOnError(retRes18298)
var positionId interface{} = this.SafeString(params, "positionId")
if IsTrue(IsEqual(positionId, nil)) {
panic(ArgumentsRequired(Add(this.Id, " closePosition() requires a positionId")))
}
var typeVar interface{} = this.SafeStringUpper(params, "type")
if IsTrue(IsEqual(typeVar, nil)) {
panic(ArgumentsRequired(Add(this.Id, " closePosition() requires a type")))
}
var quantity interface{} = this.SafeString(params, "quantity")
if IsTrue(IsEqual(quantity, nil)) {
panic(ArgumentsRequired(Add(this.Id, " closePosition() requires a quantity")))
}
var request interface{} = map[string]interface{} {
"positionId": positionId,
"type": typeVar,
"quantity": quantity,
}
if IsTrue(!IsEqual(typeVar, "MARKET")) {
var price interface{} = this.SafeString(params, "price")
if IsTrue(IsEqual(price, nil)) {
panic(ArgumentsRequired(Add(this.Id, " closePosition() requires a price")))
}
AddElementToObject(request, "price", price)
}
params = this.Omit(params, []interface{}{"positionId", "type", "quantity", "price"})
response:= (<-this.V1PrivateDeleteApiPositionPositionId(this.Extend(request, params)))
PanicOnError(response)
//
// {}
//
ch <- response
return nil
}()
return ch
}
/**
* @method
* @name defx#closeAllPositions
* @description closes all open positions for a market type
* @see https://api-docs.defx.com/#d6f63b43-100e-47a9-998c-8b6c0c72d204
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} A list of [position structures]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *defx) CloseAllPositions(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes18718 := (<-this.LoadMarkets())
PanicOnError(retRes18718)
response:= (<-this.V1PrivateDeleteApiPositionAll(params))
PanicOnError(response)
//
// {
// "data": [
// {
// "positionId": "d6ca1a27-28ad-47ae-b244-0bda5ac37b2b",
// "success": true
// }
// ]
// }
//
var data interface{} = this.SafeList(response, "data", []interface{}{})
ch <- this.ParsePositions(data, nil, params)
return nil
}()
return ch
}
/**
* @method
* @name defx#fetchLedger
* @description fetch the history of changes, actions done by the user or operations that altered the balance of the user
* @see https://api-docs.defx.com/#38cc8974-794f-48c0-b959-db045a0ee565
* @param {string} [code] unified currency code
* @param {int} [since] timestamp in ms of the earliest ledger entry
* @param {int} [limit] max number of ledger entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] timestamp in ms of the latest ledger entry
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object} a [ledger structure]{@link https://docs.ccxt.com/#/?id=ledger}
*/
func (this *defx) FetchLedger(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
code := GetArg(optionalArgs, 0, nil)
_ = code
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes19018 := (<-this.LoadMarkets())
PanicOnError(retRes19018)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchLedger", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes190519 := (<-this.FetchPaginatedCallDynamic("fetchLedger", code, since, limit, params))
PanicOnError(retRes190519)
ch <- retRes190519
return nil
}
var request interface{} = map[string]interface{} {}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "start", since)
} else {
AddElementToObject(request, "start", 0)
}
var until interface{} = this.SafeInteger(params, "until")
if IsTrue(!IsEqual(until, nil)) {
params = this.Omit(params, "until")
AddElementToObject(request, "end", until)
} else {
AddElementToObject(request, "end", this.Milliseconds())
}
response:= (<-this.V1PrivateGetApiWalletTransactions(this.Extend(request, params)))
PanicOnError(response)
var data interface{} = this.SafeList(response, "transactions", []interface{}{})
ch <- this.ParseLedger(data, nil, since, limit)
return nil
}()
return ch
}
func (this *defx) ParseLedgerEntry(item interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "id": "01JCSZS6H5VQND3GF5P98SJ29C",
// "timestamp": 1731744012054,
// "type": "FundingFee",
// "amount": "0.02189287",
// "asset": "USDC",
// "operation": "CREDIT"
// }
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
var amount interface{} = this.SafeString(item, "amount")
var currencyId interface{} = this.SafeString(item, "asset")
var code interface{} = this.SafeCurrencyCode(currencyId, currency)
currency = this.SafeCurrency(currencyId, currency)
var timestamp interface{} = this.SafeInteger(item, "timestamp")
var typeVar interface{} = this.SafeString(item, "type")
return this.SafeLedgerEntry(map[string]interface{} {
"info": item,
"id": this.SafeString(item, "id"),
"direction": nil,
"account": nil,
"referenceAccount": nil,
"referenceId": nil,
"type": this.ParseLedgerEntryType(typeVar),
"currency": code,
"amount": this.ParseNumber(amount),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"before": nil,
"after": nil,
"status": nil,
"fee": nil,
}, currency)
}
func (this *defx) ParseLedgerEntryType(typeVar interface{}) interface{} {
var ledgerType interface{} = map[string]interface{} {
"FundingFee": "fee",
"FeeRebate": "fee",
"FeeKickback": "fee",
"RealizedPnl": "trade",
"LiquidationClearance": "trade",
"Transfer": "transfer",
"ReferralPayout": "referral",
"Commission": "commission",
}
return this.SafeString(ledgerType, typeVar, typeVar)
}
/**
* @method
* @name defx#withdraw
* @description make a withdrawal
* @see https://api-docs.defx.com/#2600f503-63ed-4672-b8f6-69ea5f03203b
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {string} tag
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
func (this *defx) Withdraw(code interface{}, amount interface{}, address interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
tag := GetArg(optionalArgs, 0, nil)
_ = tag
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes19888 := (<-this.LoadMarkets())
PanicOnError(retRes19888)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"amount": this.CurrencyToPrecision(code, amount),
"asset": GetValue(currency, "id"),
}
response:= (<-this.V1PrivatePostApiTransfersBridgeWithdrawal(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "transactionId": "0x301e5851e5aefa733abfbc8b30817ca3b61601e0ddf1df8c59656fb888b0bc9c"
// }
//
ch <- this.ParseTransaction(response, currency)
return nil
}()
return ch
}
func (this *defx) ParseTransaction(transaction interface{}, optionalArgs ...interface{}) interface{} {
//
// withdraw
//
// {
// "transactionId": "0x301e5851e5aefa733abfbc8b30817ca3b61601e0ddf1df8c59656fb888b0bc9c"
// }
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
var txid interface{} = this.SafeString(transaction, "transactionId")
return map[string]interface{} {
"info": transaction,
"id": nil,
"txid": txid,
"timestamp": nil,
"datetime": nil,
"network": nil,
"address": nil,
"addressTo": nil,
"addressFrom": nil,
"tag": nil,
"tagTo": nil,
"tagFrom": nil,
"type": nil,
"amount": nil,
"currency": this.SafeCurrencyCode(nil, currency),
"status": nil,
"updated": nil,
"internal": nil,
"comment": nil,
"fee": nil,
}
}
/**
* @method
* @name defx#setLeverage
* @description set the level of leverage for a market
* @see https://api-docs.defx.com/#4cb4ecc4-6c61-4194-8353-be67faaf7ca7
* @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 *defx) SetLeverage(leverage interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " setLeverage() requires a symbol argument")))
}
retRes20528 := (<-this.LoadMarkets())
PanicOnError(retRes20528)
var request interface{} = map[string]interface{} {
"leverage": this.NumberToString(leverage),
}
var market interface{} = this.Market(symbol)
AddElementToObject(request, "symbol", GetValue(market, "id"))
response:= (<-this.V1PrivatePostApiUsersMetadataLeverage(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "success": true,
// "data": {
// "leverage": "11",
// "symbol": "BTC_USDC"
// }
// }
//
var data interface{} = this.SafeDict(response, "data", map[string]interface{} {})
ch <- this.ParseLeverage(data, market)
return nil
}()
return ch
}
func (this *defx) ParseLeverage(leverage interface{}, optionalArgs ...interface{}) interface{} {
//
// "data": {
// "leverage": "11",
// "symbol": "BTC_USDC"
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(leverage, "symbol")
var leverageValue interface{} = this.SafeInteger(leverage, "leverage")
return map[string]interface{} {
"info": leverage,
"symbol": this.SafeSymbol(marketId, market),
"marginMode": nil,
"longLeverage": leverageValue,
"shortLeverage": leverageValue,
}
}
func (this *defx) Nonce() interface{} {
return this.Milliseconds()
}
func (this *defx) Sign(path interface{}, optionalArgs ...interface{}) interface{} {
section := GetArg(optionalArgs, 0, "public")
_ = section
method := GetArg(optionalArgs, 1, "GET")
_ = method
params := GetArg(optionalArgs, 2, map[string]interface{} {})
_ = params
headers := GetArg(optionalArgs, 3, nil)
_ = headers
body := GetArg(optionalArgs, 4, nil)
_ = body
var version interface{} = GetValue(section, 0)
var access interface{} = GetValue(section, 1)
var pathWithParams interface{} = this.ImplodeParams(path, params)
var url interface{} = this.ImplodeHostname(GetValue(GetValue(this.Urls, "api"), access))
url = Add(url, Add(Add("/", version), "/"))
params = this.Omit(params, this.ExtractParams(path))
params = this.Keysort(params)
if IsTrue(IsEqual(access, "public")) {
url = Add(url, Add("open/", pathWithParams))
if IsTrue(GetArrayLength(ObjectKeys(params))) {
url = Add(url, Add("?", this.Rawencode(params)))
}
} else {
this.CheckRequiredCredentials()
headers = map[string]interface{} {
"X-DEFX-SOURCE": "ccxt",
}
url = Add(url, Add("auth/", pathWithParams))
var nonce interface{} = ToString(this.Milliseconds())
var payload interface{} = nonce
if IsTrue(IsTrue(IsEqual(method, "GET")) || IsTrue(IsEqual(path, "api/order/{orderId}"))) {
payload = Add(payload, this.Rawencode(params))
if IsTrue(GetArrayLength(ObjectKeys(params))) {
url = Add(url, Add("?", this.Rawencode(params)))
}
} else {
if IsTrue(!IsEqual(params, nil)) {
body = this.Json(params)
payload = Add(payload, body)
}
AddElementToObject(headers, "Content-Type", "application/json")
}
var signature interface{} = this.Hmac(this.Encode(payload), this.Encode(this.Secret), sha256)
AddElementToObject(headers, "X-DEFX-APIKEY", this.ApiKey)
AddElementToObject(headers, "X-DEFX-TIMESTAMP", nonce)
AddElementToObject(headers, "X-DEFX-SIGNATURE", signature)
}
return map[string]interface{} {
"url": url,
"method": method,
"body": body,
"headers": headers,
}
}
func (this *defx) HandleErrors(httpCode interface{}, reason interface{}, url interface{}, method interface{}, headers interface{}, body interface{}, response interface{}, requestHeaders interface{}, requestBody interface{}) interface{} {
if !IsTrue(response) {
return nil // fallback to default error handler
}
// {"errorCode":404,"errorMessage":"Not Found"}
// {"msg":"Missing auth signature","code":"missing_auth_signature"}
// {"success":false,"err":{"msg":"Invalid order id","code":"invalid_order_id"}}
var success interface{} = this.SafeBool(response, "success")
var err interface{} = this.SafeDict(response, "err", response)
var errorCode interface{} = this.SafeString2(err, "errorCode", "code")
if !IsTrue(success) {
var feedback interface{} = Add(Add(this.Id, " "), this.Json(response))
this.ThrowBroadlyMatchedException(GetValue(this.Exceptions, "broad"), body, feedback)
this.ThrowExactlyMatchedException(GetValue(this.Exceptions, "exact"), errorCode, feedback)
}
return nil
}
func (this *defx) DefaultNetworkCodeForCurrency(code interface{}) interface{} {
var currencyItem interface{} = this.Currency(code)
var networks interface{} = GetValue(currencyItem, "networks")
var networkKeys interface{} = ObjectKeys(networks)
for i := 0; IsLessThan(i, GetArrayLength(networkKeys)); i++ {
var network interface{} = GetValue(networkKeys, i)
if IsTrue(IsEqual(network, "ETH")) {
return network
}
}
// if it was not returned according to above options, then return the first network of currency
return this.SafeValue(networkKeys, 0)
}
func (this *defx) SetSandboxMode(enable interface{}) {
this.Exchange.SetSandboxMode(enable)
AddElementToObject(this.Options, "sandboxMode", enable)
}
func (this *defx) Init(userConfig map[string]interface{}) {
this.Exchange = Exchange{}
this.Exchange.InitParent(userConfig, this.Describe().(map[string]interface{}), this)
this.Exchange.DerivedExchange = this
}