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

4459 lines
193 KiB
Go

package ccxt
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
type deribit struct {
Exchange
}
func NewDeribitCore() deribit {
p := deribit{}
setDefaults(&p)
return p
}
func (this *deribit) Describe() interface{} {
return this.DeepExtend(this.Exchange.Describe(), map[string]interface{} {
"id": "deribit",
"name": "Deribit",
"countries": []interface{}{"NL"},
"version": "v2",
"userAgent": nil,
"rateLimit": 50,
"pro": true,
"has": map[string]interface{} {
"CORS": true,
"spot": false,
"margin": false,
"swap": true,
"future": true,
"option": true,
"cancelAllOrders": true,
"cancelOrder": true,
"cancelOrders": false,
"createDepositAddress": true,
"createOrder": true,
"createStopLimitOrder": true,
"createStopMarketOrder": true,
"createStopOrder": true,
"createTrailingAmountOrder": true,
"editOrder": true,
"fetchAccounts": true,
"fetchBalance": true,
"fetchBorrowRateHistories": false,
"fetchBorrowRateHistory": false,
"fetchClosedOrders": true,
"fetchCrossBorrowRate": false,
"fetchCrossBorrowRates": false,
"fetchCurrencies": true,
"fetchDeposit": false,
"fetchDepositAddress": true,
"fetchDepositAddresses": false,
"fetchDepositAddressesByNetwork": false,
"fetchDeposits": true,
"fetchDepositWithdrawFees": true,
"fetchFundingRate": true,
"fetchFundingRateHistory": true,
"fetchGreeks": true,
"fetchIndexOHLCV": false,
"fetchIsolatedBorrowRate": false,
"fetchIsolatedBorrowRates": false,
"fetchLeverageTiers": false,
"fetchLiquidations": true,
"fetchMarginMode": false,
"fetchMarkets": true,
"fetchMarkOHLCV": false,
"fetchMyLiquidations": true,
"fetchMySettlementHistory": false,
"fetchMyTrades": true,
"fetchOHLCV": true,
"fetchOpenOrders": true,
"fetchOption": true,
"fetchOptionChain": true,
"fetchOrder": true,
"fetchOrderBook": true,
"fetchOrders": false,
"fetchOrderTrades": true,
"fetchPosition": true,
"fetchPositionMode": false,
"fetchPositions": true,
"fetchPremiumIndexOHLCV": false,
"fetchStatus": true,
"fetchTicker": true,
"fetchTickers": true,
"fetchTime": true,
"fetchTrades": true,
"fetchTradingFee": false,
"fetchTradingFees": true,
"fetchTransactions": false,
"fetchTransfer": false,
"fetchTransfers": true,
"fetchUnderlyingAssets": false,
"fetchVolatilityHistory": true,
"fetchWithdrawal": false,
"fetchWithdrawals": true,
"sandbox": true,
"transfer": true,
"withdraw": true,
},
"timeframes": map[string]interface{} {
"1m": "1",
"3m": "3",
"5m": "5",
"10m": "10",
"15m": "15",
"30m": "30",
"1h": "60",
"2h": "120",
"3h": "180",
"6h": "360",
"12h": "720",
"1d": "1D",
},
"urls": map[string]interface{} {
"test": map[string]interface{} {
"rest": "https://test.deribit.com",
},
"logo": "https://user-images.githubusercontent.com/1294454/41933112-9e2dd65a-798b-11e8-8440-5bab2959fcb8.jpg",
"api": map[string]interface{} {
"rest": "https://www.deribit.com",
},
"www": "https://www.deribit.com",
"doc": []interface{}{"https://docs.deribit.com/v2", "https://github.com/deribit"},
"fees": "https://www.deribit.com/pages/information/fees",
"referral": map[string]interface{} {
"url": "https://www.deribit.com/reg-1189.4038",
"discount": 0.1,
},
},
"api": map[string]interface{} {
"public": map[string]interface{} {
"get": map[string]interface{} {
"auth": 1,
"exchange_token": 1,
"fork_token": 1,
"set_heartbeat": 1,
"disable_heartbeat": 1,
"get_time": 1,
"hello": 1,
"status": 1,
"test": 1,
"subscribe": 1,
"unsubscribe": 1,
"unsubscribe_all": 1,
"get_announcements": 1,
"get_book_summary_by_currency": 1,
"get_book_summary_by_instrument": 1,
"get_contract_size": 1,
"get_currencies": 1,
"get_delivery_prices": 1,
"get_funding_chart_data": 1,
"get_funding_rate_history": 1,
"get_funding_rate_value": 1,
"get_historical_volatility": 1,
"get_index": 1,
"get_index_price": 1,
"get_index_price_names": 1,
"get_instrument": 1,
"get_instruments": 1,
"get_last_settlements_by_currency": 1,
"get_last_settlements_by_instrument": 1,
"get_last_trades_by_currency": 1,
"get_last_trades_by_currency_and_time": 1,
"get_last_trades_by_instrument": 1,
"get_last_trades_by_instrument_and_time": 1,
"get_mark_price_history": 1,
"get_order_book": 1,
"get_trade_volumes": 1,
"get_tradingview_chart_data": 1,
"get_volatility_index_data": 1,
"ticker": 1,
},
},
"private": map[string]interface{} {
"get": map[string]interface{} {
"logout": 1,
"enable_cancel_on_disconnect": 1,
"disable_cancel_on_disconnect": 1,
"get_cancel_on_disconnect": 1,
"subscribe": 1,
"unsubscribe": 1,
"unsubscribe_all": 1,
"change_api_key_name": 1,
"change_scope_in_api_key": 1,
"change_subaccount_name": 1,
"create_api_key": 1,
"create_subaccount": 1,
"disable_api_key": 1,
"disable_tfa_for_subaccount": 1,
"enable_affiliate_program": 1,
"enable_api_key": 1,
"get_access_log": 1,
"get_account_summary": 1,
"get_account_summaries": 1,
"get_affiliate_program_info": 1,
"get_email_language": 1,
"get_new_announcements": 1,
"get_portfolio_margins": 1,
"get_position": 1,
"get_positions": 1,
"get_subaccounts": 1,
"get_subaccounts_details": 1,
"get_transaction_log": 1,
"list_api_keys": 1,
"remove_api_key": 1,
"remove_subaccount": 1,
"reset_api_key": 1,
"set_announcement_as_read": 1,
"set_api_key_as_default": 1,
"set_email_for_subaccount": 1,
"set_email_language": 1,
"set_password_for_subaccount": 1,
"toggle_notifications_from_subaccount": 1,
"toggle_subaccount_login": 1,
"execute_block_trade": 4,
"get_block_trade": 1,
"get_last_block_trades_by_currency": 1,
"invalidate_block_trade_signature": 1,
"verify_block_trade": 4,
"buy": 4,
"sell": 4,
"edit": 4,
"edit_by_label": 4,
"cancel": 4,
"cancel_all": 4,
"cancel_all_by_currency": 4,
"cancel_all_by_instrument": 4,
"cancel_by_label": 4,
"close_position": 4,
"get_margins": 1,
"get_mmp_config": 1,
"get_open_orders_by_currency": 1,
"get_open_orders_by_instrument": 1,
"get_order_history_by_currency": 1,
"get_order_history_by_instrument": 1,
"get_order_margin_by_ids": 1,
"get_order_state": 1,
"get_stop_order_history": 1,
"get_trigger_order_history": 1,
"get_user_trades_by_currency": 1,
"get_user_trades_by_currency_and_time": 1,
"get_user_trades_by_instrument": 1,
"get_user_trades_by_instrument_and_time": 1,
"get_user_trades_by_order": 1,
"reset_mmp": 1,
"set_mmp_config": 1,
"get_settlement_history_by_instrument": 1,
"get_settlement_history_by_currency": 1,
"cancel_transfer_by_id": 1,
"cancel_withdrawal": 1,
"create_deposit_address": 1,
"get_current_deposit_address": 1,
"get_deposits": 1,
"get_transfers": 1,
"get_withdrawals": 1,
"submit_transfer_to_subaccount": 1,
"submit_transfer_to_user": 1,
"withdraw": 1,
},
},
},
"features": map[string]interface{} {
"default": map[string]interface{} {
"sandbox": true,
"createOrder": map[string]interface{} {
"marginMode": false,
"triggerPrice": true,
"triggerPriceType": map[string]interface{} {
"last": true,
"mark": true,
"index": true,
},
"triggerDirection": false,
"stopLossPrice": false,
"takeProfitPrice": false,
"attachedStopLossTakeProfit": nil,
"timeInForce": map[string]interface{} {
"IOC": true,
"FOK": true,
"PO": true,
"GTD": true,
},
"hedged": false,
"selfTradePrevention": false,
"trailing": true,
"leverage": false,
"marketBuyByCost": true,
"marketBuyRequiresPrice": false,
"iceberg": true,
},
"createOrders": nil,
"fetchMyTrades": map[string]interface{} {
"marginMode": false,
"limit": 100,
"daysBack": 100000,
"untilDays": 100000,
"symbolRequired": true,
},
"fetchOrder": map[string]interface{} {
"marginMode": false,
"trigger": false,
"trailing": false,
"symbolRequired": true,
},
"fetchOpenOrders": map[string]interface{} {
"marginMode": false,
"limit": nil,
"trigger": false,
"trailing": false,
"symbolRequired": true,
},
"fetchOrders": nil,
"fetchClosedOrders": map[string]interface{} {
"marginMode": false,
"limit": 100,
"daysBack": 100000,
"daysBackCanceled": 1,
"untilDays": 100000,
"trigger": false,
"trailing": false,
"symbolRequired": true,
},
"fetchOHLCV": map[string]interface{} {
"limit": 1000,
},
},
"spot": map[string]interface{} {
"extends": "default",
},
"swap": map[string]interface{} {
"linear": map[string]interface{} {
"extends": "default",
},
"inverse": map[string]interface{} {
"extends": "default",
},
},
"future": map[string]interface{} {
"linear": map[string]interface{} {
"extends": "default",
},
"inverse": map[string]interface{} {
"extends": "default",
},
},
},
"exceptions": map[string]interface{} {
"9999": PermissionDenied,
"10000": AuthenticationError,
"10001": ExchangeError,
"10002": InvalidOrder,
"10003": InvalidOrder,
"10004": OrderNotFound,
"10005": InvalidOrder,
"10006": InvalidOrder,
"10007": InvalidOrder,
"10008": InvalidOrder,
"10009": InsufficientFunds,
"10010": OrderNotFound,
"10011": InvalidOrder,
"10012": InvalidOrder,
"10013": PermissionDenied,
"10014": PermissionDenied,
"10015": PermissionDenied,
"10016": PermissionDenied,
"10017": PermissionDenied,
"10018": PermissionDenied,
"10019": PermissionDenied,
"10020": ExchangeError,
"10021": InvalidOrder,
"10022": InvalidOrder,
"10023": InvalidOrder,
"10024": InvalidOrder,
"10025": InvalidOrder,
"10026": InvalidOrder,
"10027": InvalidOrder,
"10028": DDoSProtection,
"10029": OrderNotFound,
"10030": ExchangeError,
"10031": ExchangeError,
"10032": InvalidOrder,
"10033": NotSupported,
"10034": InvalidOrder,
"10035": InvalidOrder,
"10036": InvalidOrder,
"10040": ExchangeNotAvailable,
"10041": OnMaintenance,
"10043": InvalidOrder,
"10044": InvalidOrder,
"10045": InvalidOrder,
"10046": InvalidOrder,
"10047": DDoSProtection,
"10048": ExchangeError,
"11008": InvalidOrder,
"11029": BadRequest,
"11030": ExchangeError,
"11031": ExchangeError,
"11035": DDoSProtection,
"11036": InvalidOrder,
"11037": BadRequest,
"11038": InvalidOrder,
"11039": InvalidOrder,
"11041": InvalidOrder,
"11042": PermissionDenied,
"11043": BadRequest,
"11044": InvalidOrder,
"11045": BadRequest,
"11046": BadRequest,
"11047": BadRequest,
"11048": ExchangeError,
"11049": BadRequest,
"11050": BadRequest,
"11051": OnMaintenance,
"11052": ExchangeError,
"11053": ExchangeError,
"11090": InvalidAddress,
"11091": InvalidAddress,
"11092": InvalidAddress,
"11093": DDoSProtection,
"11094": ExchangeError,
"11095": ExchangeError,
"11096": ExchangeError,
"12000": AuthenticationError,
"12001": DDoSProtection,
"12002": ExchangeError,
"12998": AuthenticationError,
"12003": AuthenticationError,
"12004": AuthenticationError,
"12005": AuthenticationError,
"12100": ExchangeError,
"12999": AuthenticationError,
"13000": AuthenticationError,
"13001": AuthenticationError,
"13002": PermissionDenied,
"13003": AuthenticationError,
"13004": AuthenticationError,
"13005": AuthenticationError,
"13006": AuthenticationError,
"13007": AuthenticationError,
"13008": ExchangeError,
"13009": AuthenticationError,
"13010": BadRequest,
"13011": BadRequest,
"13012": PermissionDenied,
"13013": BadRequest,
"13014": BadRequest,
"13015": BadRequest,
"13016": BadRequest,
"13017": ExchangeError,
"13018": ExchangeError,
"13019": ExchangeError,
"13020": ExchangeError,
"13021": PermissionDenied,
"13025": ExchangeError,
"-32602": BadRequest,
"-32601": BadRequest,
"-32700": BadRequest,
"-32000": BadRequest,
"11054": InvalidOrder,
},
"precisionMode": TICK_SIZE,
"options": map[string]interface{} {
"code": "BTC",
"fetchBalance": map[string]interface{} {
"code": "BTC",
},
"transfer": map[string]interface{} {
"method": "privateGetSubmitTransferToSubaccount",
},
},
})
}
func (this *deribit) CreateExpiredOptionMarket(symbol interface{}) interface{} {
// support expired option contracts
var quote interface{} = "USD"
var settle interface{} = nil
var optionParts interface{} = Split(symbol, "-")
var symbolBase interface{} = Split(symbol, "/")
var base interface{} = nil
var expiry interface{} = nil
if IsTrue(IsGreaterThan(GetIndexOf(symbol, "/"), OpNeg(1))) {
base = this.SafeString(symbolBase, 0)
expiry = this.SafeString(optionParts, 1)
if IsTrue(IsGreaterThan(GetIndexOf(symbol, "USDC"), OpNeg(1))) {
base = Add(base, "_USDC")
}
} else {
base = this.SafeString(optionParts, 0)
expiry = this.ConvertMarketIdExpireDate(this.SafeString(optionParts, 1))
}
if IsTrue(IsGreaterThan(GetIndexOf(symbol, "USDC"), OpNeg(1))) {
quote = "USDC"
settle = "USDC"
} else {
settle = base
}
var splitBase interface{} = base
if IsTrue(IsGreaterThan(GetIndexOf(base, "_"), OpNeg(1))) {
var splitSymbol interface{} = Split(base, "_")
splitBase = this.SafeString(splitSymbol, 0)
}
var strike interface{} = this.SafeString(optionParts, 2)
var optionType interface{} = this.SafeString(optionParts, 3)
var datetime interface{} = this.ConvertExpireDate(expiry)
var timestamp interface{} = this.Parse8601(datetime)
return map[string]interface{} {
"id": Add(Add(Add(Add(Add(Add(base, "-"), this.ConvertExpireDateToMarketIdDate(expiry)), "-"), strike), "-"), optionType),
"symbol": Add(Add(Add(Add(Add(Add(Add(Add(Add(Add(splitBase, "/"), quote), ":"), settle), "-"), expiry), "-"), strike), "-"), optionType),
"base": base,
"quote": quote,
"settle": settle,
"baseId": base,
"quoteId": quote,
"settleId": settle,
"active": false,
"type": "option",
"linear": nil,
"inverse": nil,
"spot": false,
"swap": false,
"future": false,
"option": true,
"margin": false,
"contract": true,
"contractSize": nil,
"expiry": timestamp,
"expiryDatetime": datetime,
"optionType": Ternary(IsTrue((IsEqual(optionType, "C"))), "call", "put"),
"strike": this.ParseNumber(strike),
"precision": map[string]interface{} {
"amount": nil,
"price": nil,
},
"limits": map[string]interface{} {
"amount": map[string]interface{} {
"min": nil,
"max": nil,
},
"price": map[string]interface{} {
"min": nil,
"max": nil,
},
"cost": map[string]interface{} {
"min": nil,
"max": nil,
},
},
"info": nil,
}
}
func (this *deribit) SafeMarket(optionalArgs ...interface{}) interface{} {
marketId := GetArg(optionalArgs, 0, nil)
_ = marketId
market := GetArg(optionalArgs, 1, nil)
_ = market
delimiter := GetArg(optionalArgs, 2, nil)
_ = delimiter
marketType := GetArg(optionalArgs, 3, nil)
_ = marketType
var isOption interface{} = IsTrue((!IsEqual(marketId, nil))) && IsTrue((IsTrue((EndsWith(marketId, "-C"))) || IsTrue((EndsWith(marketId, "-P")))))
if IsTrue(IsTrue(isOption) && !IsTrue((InOp(this.Markets_by_id, marketId)))) {
// handle expired option contracts
return this.CreateExpiredOptionMarket(marketId)
}
return this.Exchange.SafeMarket(marketId, market, delimiter, marketType)
}
/**
* @method
* @name deribit#fetchTime
* @description fetches the current integer timestamp in milliseconds from the exchange server
* @see https://docs.deribit.com/#public-get_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 *deribit) 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.PublicGetGetTime(params))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": 1583922446019,
// "usIn": 1583922446019955,
// "usOut": 1583922446019956,
// "usDiff": 1,
// "testnet": false
// }
//
ch <- this.SafeInteger(response, "result")
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchCurrencies
* @description fetches all available currencies on an exchange
* @see https://docs.deribit.com/#public-get_currencies
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an associative dictionary of currencies
*/
func (this *deribit) FetchCurrencies(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
response:= (<-this.PublicGetGetCurrencies(params))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": [
// {
// "withdrawal_priorities": [],
// "withdrawal_fee": 0.01457324,
// "min_withdrawal_fee": 0.000001,
// "min_confirmations": 1,
// "fee_precision": 8,
// "currency_long": "Solana",
// "currency": "SOL",
// "coin_type": "SOL"
// },
// ...
// ],
// "usIn": 1688652701456124,
// "usOut": 1688652701456390,
// "usDiff": 266,
// "testnet": true
// }
//
var data interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var result interface{} = map[string]interface{} {}
for i := 0; IsLessThan(i, GetArrayLength(data)); i++ {
var currency interface{} = GetValue(data, i)
var currencyId interface{} = this.SafeString(currency, "currency")
var code interface{} = this.SafeCurrencyCode(currencyId)
var name interface{} = this.SafeString(currency, "currency_long")
AddElementToObject(result, code, map[string]interface{} {
"info": currency,
"code": code,
"id": currencyId,
"name": name,
"active": nil,
"deposit": nil,
"withdraw": nil,
"fee": this.SafeNumber(currency, "withdrawal_fee"),
"precision": this.ParseNumber(this.ParsePrecision(this.SafeString(currency, "fee_precision"))),
"limits": map[string]interface{} {
"amount": map[string]interface{} {
"min": nil,
"max": nil,
},
"withdraw": map[string]interface{} {
"min": nil,
"max": nil,
},
"deposit": map[string]interface{} {
"min": nil,
"max": nil,
},
},
"networks": nil,
})
}
ch <- result
return nil
}()
return ch
}
func (this *deribit) CodeFromOptions(methodName interface{}, optionalArgs ...interface{}) interface{} {
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
var defaultCode interface{} = this.SafeValue(this.Options, "code", "BTC")
var options interface{} = this.SafeValue(this.Options, methodName, map[string]interface{} {})
var code interface{} = this.SafeValue(options, "code", defaultCode)
return this.SafeValue(params, "code", code)
}
/**
* @method
* @name deribit#fetchStatus
* @description the latest known information on the availability of the exchange API
* @see https://docs.deribit.com/#public-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 *deribit) 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.PublicGetStatus(params))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": {
// "locked": "false" // true, partial, false
// },
// "usIn": 1650641690226788,
// "usOut": 1650641690226836,
// "usDiff": 48,
// "testnet": false
// }
//
var result interface{} = this.SafeValue(response, "result")
var locked interface{} = this.SafeString(result, "locked")
var updateTime interface{} = this.SafeIntegerProduct(response, "usIn", 0.001, this.Milliseconds())
ch <- map[string]interface{} {
"status": Ternary(IsTrue((IsEqual(locked, "false"))), "ok", "maintenance"),
"updated": updateTime,
"eta": nil,
"url": nil,
"info": response,
}
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchAccounts
* @description fetch all the accounts associated with a profile
* @see https://docs.deribit.com/#private-get_subaccounts
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [account structures]{@link https://docs.ccxt.com/#/?id=account-structure} indexed by the account type
*/
func (this *deribit) FetchAccounts(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
retRes7258 := (<-this.LoadMarkets())
PanicOnError(retRes7258)
response:= (<-this.PrivateGetGetSubaccounts(params))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": [{
// "username": "someusername",
// "type": "main",
// "system_name": "someusername",
// "security_keys_enabled": false,
// "security_keys_assignments": [],
// "receive_notifications": false,
// "login_enabled": true,
// "is_password": true,
// "id": "238216",
// "email": "pablo@abcdef.com"
// },
// {
// "username": "someusername_1",
// "type": "subaccount",
// "system_name": "someusername_1",
// "security_keys_enabled": false,
// "security_keys_assignments": [],
// "receive_notifications": false,
// "login_enabled": false,
// "is_password": false,
// "id": "245499",
// "email": "pablo@abcdef.com"
// }
// ],
// "usIn": "1652736468292006",
// "usOut": "1652736468292377",
// "usDiff": "371",
// "testnet": false
// }
//
var result interface{} = this.SafeValue(response, "result", []interface{}{})
ch <- this.ParseAccounts(result)
return nil
}()
return ch
}
func (this *deribit) ParseAccount(account interface{}) interface{} {
//
// {
// "username": "someusername_1",
// "type": "subaccount",
// "system_name": "someusername_1",
// "security_keys_enabled": false,
// "security_keys_assignments": [],
// "receive_notifications": false,
// "login_enabled": false,
// "is_password": false,
// "id": "245499",
// "email": "pablo@abcdef.com"
// }
//
return map[string]interface{} {
"info": account,
"id": this.SafeString(account, "id"),
"type": this.SafeString(account, "type"),
"code": nil,
}
}
/**
* @method
* @name deribit#fetchMarkets
* @description retrieves data on all markets for deribit
* @see https://docs.deribit.com/#public-get_currencies
* @see https://docs.deribit.com/#public-get_instruments
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} an array of objects representing market data
*/
func (this *deribit) 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 instrumentsResponses interface{} = []interface{}{}
var result interface{} = []interface{}{}
var parsedMarkets interface{} = map[string]interface{} {}
var fetchAllMarkets interface{} = nil
fetchAllMarketsparamsVariable := this.HandleOptionAndParams(params, "fetchMarkets", "fetchAllMarkets", true);
fetchAllMarkets = GetValue(fetchAllMarketsparamsVariable,0);
params = GetValue(fetchAllMarketsparamsVariable,1)
if IsTrue(fetchAllMarkets) {
instrumentsResponse:= (<-this.PublicGetGetInstruments(params))
PanicOnError(instrumentsResponse)
AppendToArray(&instrumentsResponses,instrumentsResponse)
} else {
currenciesResponse:= (<-this.PublicGetGetCurrencies(params))
PanicOnError(currenciesResponse)
//
// {
// "jsonrpc": "2.0",
// "result": [
// {
// "withdrawal_priorities": [
// { value: 0.15, name: "very_low" },
// { value: 1.5, name: "very_high" },
// ],
// "withdrawal_fee": 0.0005,
// "min_withdrawal_fee": 0.0005,
// "min_confirmations": 1,
// "fee_precision": 4,
// "currency_long": "Bitcoin",
// "currency": "BTC",
// "coin_type": "BITCOIN"
// }
// ],
// "usIn": 1583761588590479,
// "usOut": 1583761588590544,
// "usDiff": 65,
// "testnet": false
// }
//
var currenciesResult interface{} = this.SafeValue(currenciesResponse, "result", []interface{}{})
for i := 0; IsLessThan(i, GetArrayLength(currenciesResult)); i++ {
var currencyId interface{} = this.SafeString(GetValue(currenciesResult, i), "currency")
var request interface{} = map[string]interface{} {
"currency": currencyId,
}
instrumentsResponse:= (<-this.PublicGetGetInstruments(this.Extend(request, params)))
PanicOnError(instrumentsResponse)
//
// {
// "jsonrpc":"2.0",
// "result":[
// {
// "tick_size":0.0005,
// "taker_commission":0.0003,
// "strike":52000.0,
// "settlement_period":"month",
// "settlement_currency":"BTC",
// "quote_currency":"BTC",
// "option_type":"put", // put, call
// "min_trade_amount":0.1,
// "maker_commission":0.0003,
// "kind":"option",
// "is_active":true,
// "instrument_name":"BTC-24JUN22-52000-P",
// "expiration_timestamp":1656057600000,
// "creation_timestamp":1648199543000,
// "counter_currency":"USD",
// "contract_size":1.0,
// "block_trade_commission":0.0003,
// "base_currency":"BTC"
// },
// {
// "tick_size":0.5,
// "taker_commission":0.0005,
// "settlement_period":"month", // month, week
// "settlement_currency":"BTC",
// "quote_currency":"USD",
// "min_trade_amount":10.0,
// "max_liquidation_commission":0.0075,
// "max_leverage":50,
// "maker_commission":0.0,
// "kind":"future",
// "is_active":true,
// "instrument_name":"BTC-27MAY22",
// "future_type":"reversed",
// "expiration_timestamp":1653638400000,
// "creation_timestamp":1648195209000,
// "counter_currency":"USD",
// "contract_size":10.0,
// "block_trade_commission":0.0001,
// "base_currency":"BTC"
// },
// {
// "tick_size":0.5,
// "taker_commission":0.0005,
// "settlement_period":"perpetual",
// "settlement_currency":"BTC",
// "quote_currency":"USD",
// "min_trade_amount":10.0,
// "max_liquidation_commission":0.0075,
// "max_leverage":50,
// "maker_commission":0.0,
// "kind":"future",
// "is_active":true,
// "instrument_name":"BTC-PERPETUAL",
// "future_type":"reversed",
// "expiration_timestamp":32503708800000,
// "creation_timestamp":1534242287000,
// "counter_currency":"USD",
// "contract_size":10.0,
// "block_trade_commission":0.0001,
// "base_currency":"BTC"
// },
// ],
// "usIn":1648691472831791,
// "usOut":1648691472831896,
// "usDiff":105,
// "testnet":false
// }
//
AppendToArray(&instrumentsResponses,instrumentsResponse)
}
}
for i := 0; IsLessThan(i, GetArrayLength(instrumentsResponses)); i++ {
var instrumentsResult interface{} = this.SafeValue(GetValue(instrumentsResponses, i), "result", []interface{}{})
for k := 0; IsLessThan(k, GetArrayLength(instrumentsResult)); k++ {
var market interface{} = GetValue(instrumentsResult, k)
var kind interface{} = this.SafeString(market, "kind")
var isSpot interface{} = (IsEqual(kind, "spot"))
var id interface{} = this.SafeString(market, "instrument_name")
var baseId interface{} = this.SafeString(market, "base_currency")
var quoteId interface{} = this.SafeString(market, "counter_currency")
var settleId interface{} = this.SafeString(market, "settlement_currency")
var base interface{} = this.SafeCurrencyCode(baseId)
var quote interface{} = this.SafeCurrencyCode(quoteId)
var settle interface{} = this.SafeCurrencyCode(settleId)
var settlementPeriod interface{} = this.SafeValue(market, "settlement_period")
var swap interface{} = (IsEqual(settlementPeriod, "perpetual"))
var future interface{} = !IsTrue(swap) && IsTrue((IsGreaterThanOrEqual(GetIndexOf(kind, "future"), 0)))
var option interface{} = (IsGreaterThanOrEqual(GetIndexOf(kind, "option"), 0))
var isComboMarket interface{} = IsGreaterThanOrEqual(GetIndexOf(kind, "combo"), 0)
var expiry interface{} = this.SafeInteger(market, "expiration_timestamp")
var strike interface{} = nil
var optionType interface{} = nil
var symbol interface{} = id
var typeVar interface{} = "swap"
if IsTrue(future) {
typeVar = "future"
} else if IsTrue(option) {
typeVar = "option"
} else if IsTrue(isSpot) {
typeVar = "spot"
}
var inverse interface{} = nil
var linear interface{} = nil
if IsTrue(isSpot) {
symbol = Add(Add(base, "/"), quote)
} else if !IsTrue(isComboMarket) {
symbol = Add(Add(Add(Add(base, "/"), quote), ":"), settle)
if IsTrue(IsTrue(option) || IsTrue(future)) {
symbol = Add(Add(symbol, "-"), this.Yymmdd(expiry, ""))
if IsTrue(option) {
strike = this.SafeNumber(market, "strike")
optionType = this.SafeString(market, "option_type")
var letter interface{} = Ternary(IsTrue((IsEqual(optionType, "call"))), "C", "P")
symbol = Add(Add(Add(Add(symbol, "-"), this.NumberToString(strike)), "-"), letter)
}
}
inverse = (!IsEqual(quote, settle))
linear = (IsEqual(settle, quote))
}
var parsedMarketValue interface{} = this.SafeValue(parsedMarkets, symbol)
if IsTrue(parsedMarketValue) {
continue
}
AddElementToObject(parsedMarkets, symbol, true)
var minTradeAmount interface{} = this.SafeNumber(market, "min_trade_amount")
var tickSize interface{} = this.SafeNumber(market, "tick_size")
AppendToArray(&result,map[string]interface{} {
"id": id,
"symbol": symbol,
"base": base,
"quote": quote,
"settle": settle,
"baseId": baseId,
"quoteId": quoteId,
"settleId": settleId,
"type": typeVar,
"spot": isSpot,
"margin": false,
"swap": swap,
"future": future,
"option": option,
"active": this.SafeValue(market, "is_active"),
"contract": !IsTrue(isSpot),
"linear": linear,
"inverse": inverse,
"taker": this.SafeNumber(market, "taker_commission"),
"maker": this.SafeNumber(market, "maker_commission"),
"contractSize": this.SafeNumber(market, "contract_size"),
"expiry": expiry,
"expiryDatetime": this.Iso8601(expiry),
"strike": strike,
"optionType": optionType,
"precision": map[string]interface{} {
"amount": minTradeAmount,
"price": tickSize,
},
"limits": map[string]interface{} {
"leverage": map[string]interface{} {
"min": nil,
"max": nil,
},
"amount": map[string]interface{} {
"min": minTradeAmount,
"max": nil,
},
"price": map[string]interface{} {
"min": tickSize,
"max": nil,
},
"cost": map[string]interface{} {
"min": nil,
"max": nil,
},
},
"created": this.SafeInteger(market, "creation_timestamp"),
"info": market,
})
}
}
ch <- result
return nil
}()
return ch
}
func (this *deribit) ParseBalance(balance interface{}) interface{} {
var result interface{} = map[string]interface{} {
"info": balance,
}
var summaries interface{} = []interface{}{}
if IsTrue(InOp(balance, "summaries")) {
summaries = this.SafeList(balance, "summaries")
} else {
summaries = []interface{}{balance}
}
for i := 0; IsLessThan(i, GetArrayLength(summaries)); i++ {
var data interface{} = GetValue(summaries, i)
var currencyId interface{} = this.SafeString(data, "currency")
var currencyCode interface{} = this.SafeCurrencyCode(currencyId)
var account interface{} = this.Account()
AddElementToObject(account, "free", this.SafeString(data, "available_funds"))
AddElementToObject(account, "used", this.SafeString(data, "maintenance_margin"))
AddElementToObject(account, "total", this.SafeString(data, "equity"))
AddElementToObject(result, currencyCode, account)
}
return this.SafeBalance(result)
}
/**
* @method
* @name deribit#fetchBalance
* @description query for balance and get the amount of funds available for trading or funds locked in orders
* @see https://docs.deribit.com/#private-get_account_summary
* @see https://docs.deribit.com/#private-get_account_summaries
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.code] unified currency code of the currency for the balance, if defined 'privateGetGetAccountSummary' will be used, otherwise 'privateGetGetAccountSummaries' will be used
* @returns {object} a [balance structure]{@link https://docs.ccxt.com/#/?id=balance-structure}
*/
func (this *deribit) 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
retRes10608 := (<-this.LoadMarkets())
PanicOnError(retRes10608)
var code interface{} = this.SafeString(params, "code")
params = this.Omit(params, "code")
var request interface{} = map[string]interface{} {}
if IsTrue(!IsEqual(code, nil)) {
AddElementToObject(request, "currency", this.CurrencyId(code))
}
var response interface{} = nil
if IsTrue(IsEqual(code, nil)) {
response = (<-this.PrivateGetGetAccountSummaries(params))
PanicOnError(response)
} else {
response = (<-this.PrivateGetGetAccountSummary(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// "jsonrpc": "2.0",
// "result": {
// "total_pl": 0,
// "session_upl": 0,
// "session_rpl": 0,
// "session_funding": 0,
// "portfolio_margining_enabled": false,
// "options_vega": 0,
// "options_theta": 0,
// "options_session_upl": 0,
// "options_session_rpl": 0,
// "options_pl": 0,
// "options_gamma": 0,
// "options_delta": 0,
// "margin_balance": 0.00062359,
// "maintenance_margin": 0,
// "limits": {
// "non_matching_engine_burst": 300,
// "non_matching_engine": 200,
// "matching_engine_burst": 20,
// "matching_engine": 2
// },
// "initial_margin": 0,
// "futures_session_upl": 0,
// "futures_session_rpl": 0,
// "futures_pl": 0,
// "equity": 0.00062359,
// "deposit_address": "13tUtNsJSZa1F5GeCmwBywVrymHpZispzw",
// "delta_total": 0,
// "currency": "BTC",
// "balance": 0.00062359,
// "available_withdrawal_funds": 0.00062359,
// "available_funds": 0.00062359
// },
// "usIn": 1583775838115975,
// "usOut": 1583775838116520,
// "usDiff": 545,
// "testnet": false
// }
//
var result interface{} = this.SafeDict(response, "result", map[string]interface{} {})
ch <- this.ParseBalance(result)
return nil
}()
return ch
}
/**
* @method
* @name deribit#createDepositAddress
* @description create a currency deposit address
* @see https://docs.deribit.com/#private-create_deposit_address
* @param {string} code unified currency code of the currency for the deposit address
* @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 *deribit) CreateDepositAddress(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
retRes11308 := (<-this.LoadMarkets())
PanicOnError(retRes11308)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
}
response:= (<-this.PrivateGetCreateDepositAddress(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "id": 7538,
// "result": {
// "address": "2N8udZGBc1hLRCFsU9kGwMPpmYUwMFTuCwB",
// "creation_timestamp": 1550575165170,
// "currency": "BTC",
// "type": "deposit"
// }
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var address interface{} = this.SafeString(result, "address")
this.CheckAddress(address)
ch <- map[string]interface{} {
"currency": code,
"address": address,
"tag": nil,
"info": response,
}
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchDepositAddress
* @description fetch the deposit address for a currency associated with this account
* @see https://docs.deribit.com/#private-get_current_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 *deribit) 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
retRes11698 := (<-this.LoadMarkets())
PanicOnError(retRes11698)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
}
response:= (<-this.PrivateGetGetCurrentDepositAddress(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": {
// "type": "deposit",
// "status": "ready",
// "requires_confirmation": true,
// "currency": "BTC",
// "creation_timestamp": 1514694684651,
// "address": "13tUtNsJSZa1F5GeCmwBywVrymHpZispzw"
// },
// "usIn": 1583785137274288,
// "usOut": 1583785137274454,
// "usDiff": 166,
// "testnet": false
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var address interface{} = this.SafeString(result, "address")
this.CheckAddress(address)
ch <- map[string]interface{} {
"info": response,
"currency": code,
"network": nil,
"address": address,
"tag": nil,
}
return nil
}()
return ch
}
func (this *deribit) ParseTicker(ticker interface{}, optionalArgs ...interface{}) interface{} {
//
// fetchTicker /public/ticker
//
// {
// "timestamp": 1583778859480,
// "stats": { volume: 60627.57263769, low: 7631.5, high: 8311.5 },
// "state": "open",
// "settlement_price": 7903.21,
// "open_interest": 111543850,
// "min_price": 7634,
// "max_price": 7866.51,
// "mark_price": 7750.02,
// "last_price": 7750.5,
// "instrument_name": "BTC-PERPETUAL",
// "index_price": 7748.01,
// "funding_8h": 0.0000026,
// "current_funding": 0,
// "best_bid_price": 7750,
// "best_bid_amount": 19470,
// "best_ask_price": 7750.5,
// "best_ask_amount": 343280
// }
//
// fetchTicker /public/get_book_summary_by_instrument
// fetchTickers /public/get_book_summary_by_currency
//
// {
// "volume": 124.1,
// "underlying_price": 7856.445926872601,
// "underlying_index": "SYN.BTC-10MAR20",
// "quote_currency": "USD",
// "open_interest": 121.8,
// "mid_price": 0.01975,
// "mark_price": 0.01984559,
// "low": 0.0095,
// "last": 0.0205,
// "interest_rate": 0,
// "instrument_name": "BTC-10MAR20-7750-C",
// "high": 0.0295,
// "estimated_delivery_price": 7856.29,
// "creation_timestamp": 1583783678366,
// "bid_price": 0.0185,
// "base_currency": "BTC",
// "ask_price": 0.021
// },
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var timestamp interface{} = this.SafeInteger2(ticker, "timestamp", "creation_timestamp")
var marketId interface{} = this.SafeString(ticker, "instrument_name")
var symbol interface{} = this.SafeSymbol(marketId, market)
var last interface{} = this.SafeString2(ticker, "last_price", "last")
var stats interface{} = this.SafeValue(ticker, "stats", ticker)
return this.SafeTicker(map[string]interface{} {
"symbol": symbol,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"high": this.SafeString2(stats, "high", "max_price"),
"low": this.SafeString2(stats, "low", "min_price"),
"bid": this.SafeString2(ticker, "best_bid_price", "bid_price"),
"bidVolume": this.SafeString(ticker, "best_bid_amount"),
"ask": this.SafeString2(ticker, "best_ask_price", "ask_price"),
"askVolume": this.SafeString(ticker, "best_ask_amount"),
"vwap": nil,
"open": nil,
"close": last,
"last": last,
"previousClose": nil,
"change": nil,
"percentage": nil,
"average": nil,
"baseVolume": nil,
"quoteVolume": this.SafeString(stats, "volume"),
"markPrice": this.SafeString(ticker, "mark_price"),
"indexPrice": this.SafeString(ticker, "index_price"),
"info": ticker,
}, market)
}
/**
* @method
* @name deribit#fetchTicker
* @description fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
* @see https://docs.deribit.com/#public-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 *deribit) 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
retRes12928 := (<-this.LoadMarkets())
PanicOnError(retRes12928)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
}
response:= (<-this.PublicGetTicker(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": {
// "timestamp": 1583778859480,
// "stats": { volume: 60627.57263769, low: 7631.5, high: 8311.5 },
// "state": "open",
// "settlement_price": 7903.21,
// "open_interest": 111543850,
// "min_price": 7634,
// "max_price": 7866.51,
// "mark_price": 7750.02,
// "last_price": 7750.5,
// "instrument_name": "BTC-PERPETUAL",
// "index_price": 7748.01,
// "funding_8h": 0.0000026,
// "current_funding": 0,
// "best_bid_price": 7750,
// "best_bid_amount": 19470,
// "best_ask_price": 7750.5,
// "best_ask_amount": 343280
// },
// "usIn": 1583778859483941,
// "usOut": 1583778859484075,
// "usDiff": 134,
// "testnet": false
// }
//
var result interface{} = this.SafeDict(response, "result")
ch <- this.ParseTicker(result, market)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchTickers
* @description fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
* @see https://docs.deribit.com/#public-get_book_summary_by_currency
* @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.code] *required* the currency code to fetch the tickers for, eg. 'BTC', 'ETH'
* @returns {object} a dictionary of [ticker structures]{@link https://docs.ccxt.com/#/?id=ticker-structure}
*/
func (this *deribit) 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
retRes13418 := (<-this.LoadMarkets())
PanicOnError(retRes13418)
symbols = this.MarketSymbols(symbols)
var code interface{} = this.SafeString2(params, "code", "currency")
params = this.Omit(params, []interface{}{"code"})
if IsTrue(IsEqual(code, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchTickers requires a currency/code (eg: BTC/ETH/USDT) parameter to fetch tickers for")))
}
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
}
response:= (<-this.PublicGetGetBookSummaryByCurrency(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": [
// {
// "volume": 124.1,
// "underlying_price": 7856.445926872601,
// "underlying_index": "SYN.BTC-10MAR20",
// "quote_currency": "USD",
// "open_interest": 121.8,
// "mid_price": 0.01975,
// "mark_price": 0.01984559,
// "low": 0.0095,
// "last": 0.0205,
// "interest_rate": 0,
// "instrument_name": "BTC-10MAR20-7750-C",
// "high": 0.0295,
// "estimated_delivery_price": 7856.29,
// "creation_timestamp": 1583783678366,
// "bid_price": 0.0185,
// "base_currency": "BTC",
// "ask_price": 0.021
// },
// ],
// "usIn": 1583783678361966,
// "usOut": 1583783678372069,
// "usDiff": 10103,
// "testnet": false
// }
//
var result interface{} = this.SafeList(response, "result", []interface{}{})
var tickers interface{} = map[string]interface{} {}
for i := 0; IsLessThan(i, GetArrayLength(result)); i++ {
var ticker interface{} = this.ParseTicker(GetValue(result, i))
var symbol interface{} = GetValue(ticker, "symbol")
AddElementToObject(tickers, symbol, ticker)
}
ch <- this.FilterByArrayTickers(tickers, "symbol", symbols)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchOHLCV
* @description fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
* @see https://docs.deribit.com/#public-get_tradingview_chart_data
* @param {string} symbol unified symbol of the market to fetch OHLCV data for
* @param {string} timeframe the length of time each candle represents
* @param {int} [since] timestamp in ms of the earliest candle to fetch
* @param {int} [limit] the maximum amount of candles to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {boolean} [params.paginate] whether to paginate the results, set to false by default
* @param {int} [params.until] the latest time in ms to fetch ohlcv for
* @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
*/
func (this *deribit) 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
retRes14088 := (<-this.LoadMarkets())
PanicOnError(retRes14088)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchOHLCV", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes141219 := (<-this.FetchPaginatedCallDeterministic("fetchOHLCV", symbol, since, limit, timeframe, params, 5000))
PanicOnError(retRes141219)
ch <- retRes141219
return nil
}
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
"resolution": this.SafeString(this.Timeframes, timeframe, timeframe),
}
var duration interface{} = this.ParseTimeframe(timeframe)
var now interface{} = this.Milliseconds()
if IsTrue(IsEqual(since, nil)) {
if IsTrue(IsEqual(limit, nil)) {
limit = 1000 // at max, it provides 5000 bars, but we set generous default here
}
AddElementToObject(request, "start_timestamp", Subtract(now, Multiply(Multiply((Subtract(limit, 1)), duration), 1000)))
AddElementToObject(request, "end_timestamp", now)
} else {
since = mathMax(Subtract(since, 1), 0)
AddElementToObject(request, "start_timestamp", since)
if IsTrue(IsEqual(limit, nil)) {
AddElementToObject(request, "end_timestamp", now)
} else {
AddElementToObject(request, "end_timestamp", this.Sum(since, Multiply(Multiply(limit, duration), 1000)))
}
}
var until interface{} = this.SafeInteger(params, "until")
if IsTrue(!IsEqual(until, nil)) {
params = this.Omit(params, "until")
AddElementToObject(request, "end_timestamp", until)
}
response:= (<-this.PublicGetGetTradingviewChartData(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": {
// "volume": [ 3.6680847969999992, 22.682721123, 3.011587939, 0 ],
// "ticks": [ 1583916960000, 1583917020000, 1583917080000, 1583917140000 ],
// "status": "ok",
// "open": [ 7834, 7839, 7833.5, 7833 ],
// "low": [ 7834, 7833.5, 7832.5, 7833 ],
// "high": [ 7839.5, 7839, 7833.5, 7833 ],
// "cost": [ 28740, 177740, 23590, 0 ],
// "close": [ 7839.5, 7833.5, 7833, 7833 ]
// },
// "usIn": 1583917166709801,
// "usOut": 1583917166710175,
// "usDiff": 374,
// "testnet": false
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var ohlcvs interface{} = this.ConvertTradingViewToOHLCV(result, "ticks", "open", "high", "low", "close", "volume", true)
ch <- this.ParseOHLCVs(ohlcvs, market, timeframe, since, limit)
return nil
}()
return ch
}
func (this *deribit) ParseTrade(trade interface{}, optionalArgs ...interface{}) interface{} {
//
// fetchTrades (public)
//
// {
// "trade_seq":132564271,
// "trade_id":"195402220",
// "timestamp":1639684927932,
// "tick_direction":0,
// "price":47946.5,
// "mark_price":47944.13,
// "instrument_name":"BTC-PERPETUAL",
// "index_price":47925.45,
// "direction":"buy",
// "amount":580.0
// }
//
//
// fetchMyTrades, fetchOrderTrades (private)
//
// {
// "trade_seq": 3,
// "trade_id": "ETH-34066",
// "timestamp": 1550219814585,
// "tick_direction": 1,
// "state": "open",
// "self_trade": false,
// "reduce_only": false,
// "price": 0.04,
// "post_only": false,
// "order_type": "limit",
// "order_id": "ETH-334607",
// "matching_id": null,
// "liquidity": "M",
// "iv": 56.83,
// "instrument_name": "ETH-22FEB19-120-C",
// "index_price": 121.37,
// "fee_currency": "ETH",
// "fee": 0.0011,
// "direction": "buy",
// "amount": 11
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var id interface{} = this.SafeString(trade, "trade_id")
var marketId interface{} = this.SafeString(trade, "instrument_name")
var symbol interface{} = this.SafeSymbol(marketId, market)
var timestamp interface{} = this.SafeInteger(trade, "timestamp")
var side interface{} = this.SafeString(trade, "direction")
var priceString interface{} = this.SafeString(trade, "price")
market = this.SafeMarket(marketId, market)
// Amount for inverse perpetual and futures is in USD which in ccxt is the cost
// For options amount and linear is in corresponding cryptocurrency contracts, e.g., BTC or ETH
var amount interface{} = this.SafeString(trade, "amount")
var cost interface{} = Precise.StringMul(amount, priceString)
if IsTrue(GetValue(market, "inverse")) {
cost = Precise.StringDiv(amount, priceString)
}
var liquidity interface{} = this.SafeString(trade, "liquidity")
var takerOrMaker interface{} = nil
if IsTrue(!IsEqual(liquidity, nil)) {
// M = maker, T = taker, MT = both
takerOrMaker = Ternary(IsTrue((IsEqual(liquidity, "M"))), "maker", "taker")
}
var feeCostString interface{} = this.SafeString(trade, "fee")
var fee interface{} = nil
if IsTrue(!IsEqual(feeCostString, nil)) {
var feeCurrencyId interface{} = this.SafeString(trade, "fee_currency")
var feeCurrencyCode interface{} = this.SafeCurrencyCode(feeCurrencyId)
fee = map[string]interface{} {
"cost": feeCostString,
"currency": feeCurrencyCode,
}
}
return this.SafeTrade(map[string]interface{} {
"id": id,
"info": trade,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"symbol": symbol,
"order": this.SafeString(trade, "order_id"),
"type": this.SafeString(trade, "order_type"),
"side": side,
"takerOrMaker": takerOrMaker,
"price": priceString,
"amount": amount,
"cost": cost,
"fee": fee,
}, market)
}
/**
* @method
* @name deribit#fetchTrades
* @see https://docs.deribit.com/#public-get_last_trades_by_instrument
* @see https://docs.deribit.com/#public-get_last_trades_by_instrument_and_time
* @description get the list of most recent trades for a particular symbol.
* @param {string} symbol unified symbol of the market to fetch trades for
* @param {int} [since] timestamp in ms of the earliest trade to fetch
* @param {int} [limit] the maximum amount of trades to fetch
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.until] the latest time in ms to fetch trades for
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=public-trades}
*/
func (this *deribit) 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
retRes15708 := (<-this.LoadMarkets())
PanicOnError(retRes15708)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
"include_old": true,
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "start_timestamp", since)
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "count", mathMin(limit, 1000)) // default 10
}
var until interface{} = this.SafeInteger2(params, "until", "end_timestamp")
if IsTrue(!IsEqual(until, nil)) {
params = this.Omit(params, []interface{}{"until"})
AddElementToObject(request, "end_timestamp", until)
}
var response interface{} = nil
if IsTrue(IsTrue((IsEqual(since, nil))) && !IsTrue((InOp(request, "end_timestamp")))) {
response = (<-this.PublicGetGetLastTradesByInstrument(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.PublicGetGetLastTradesByInstrumentAndTime(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// "jsonrpc":"2.0",
// "result": {
// "trades": [
// {
// "trade_seq":132564271,
// "trade_id":"195402220",
// "timestamp":1639684927932,
// "tick_direction":0,
// "price":47946.5,
// "mark_price":47944.13,
// "instrument_name":"BTC-PERPETUAL",
// "index_price":47925.45,
// "direction":"buy","amount":580.0
// }
// ],
// "has_more":true
// },
// "usIn":1639684931934671,
// "usOut":1639684931935337,
// "usDiff":666,
// "testnet":false
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var trades interface{} = this.SafeList(result, "trades", []interface{}{})
ch <- this.ParseTrades(trades, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchTradingFees
* @description fetch the trading fees for multiple markets
* @see https://docs.deribit.com/#private-get_account_summary
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a dictionary of [fee structures]{@link https://docs.ccxt.com/#/?id=fee-structure} indexed by market symbols
*/
func (this *deribit) FetchTradingFees(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes16328 := (<-this.LoadMarkets())
PanicOnError(retRes16328)
var code interface{} = this.CodeFromOptions("fetchTradingFees", params)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
"extended": true,
}
response:= (<-this.PrivateGetGetAccountSummary(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": {
// "total_pl": 0,
// "session_upl": 0,
// "session_rpl": 0,
// "session_funding": 0,
// "portfolio_margining_enabled": false,
// "options_vega": 0,
// "options_theta": 0,
// "options_session_upl": 0,
// "options_session_rpl": 0,
// "options_pl": 0,
// "options_gamma": 0,
// "options_delta": 0,
// "margin_balance": 0.00062359,
// "maintenance_margin": 0,
// "limits": {
// "non_matching_engine_burst": 300,
// "non_matching_engine": 200,
// "matching_engine_burst": 20,
// "matching_engine": 2
// },
// "initial_margin": 0,
// "futures_session_upl": 0,
// "futures_session_rpl": 0,
// "futures_pl": 0,
// "equity": 0.00062359,
// "deposit_address": "13tUtNsJSZa1F5GeCmwBywVrymHpZispzw",
// "delta_total": 0,
// "currency": "BTC",
// "balance": 0.00062359,
// "available_withdrawal_funds": 0.00062359,
// "available_funds": 0.00062359,
// "fees": [
// "currency": '',
// "instrument_type": "perpetual",
// "fee_type": "relative",
// "maker_fee": 0,
// "taker_fee": 0,
// ],
// },
// "usIn": 1583775838115975,
// "usOut": 1583775838116520,
// "usDiff": 545,
// "testnet": false
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var fees interface{} = this.SafeValue(result, "fees", []interface{}{})
var perpetualFee interface{} = map[string]interface{} {}
var futureFee interface{} = map[string]interface{} {}
var optionFee interface{} = map[string]interface{} {}
for i := 0; IsLessThan(i, GetArrayLength(fees)); i++ {
var fee interface{} = GetValue(fees, i)
var instrumentType interface{} = this.SafeString(fee, "instrument_type")
if IsTrue(IsEqual(instrumentType, "future")) {
futureFee = map[string]interface{} {
"info": fee,
"maker": this.SafeNumber(fee, "maker_fee"),
"taker": this.SafeNumber(fee, "taker_fee"),
}
} else if IsTrue(IsEqual(instrumentType, "perpetual")) {
perpetualFee = map[string]interface{} {
"info": fee,
"maker": this.SafeNumber(fee, "maker_fee"),
"taker": this.SafeNumber(fee, "taker_fee"),
}
} else if IsTrue(IsEqual(instrumentType, "option")) {
optionFee = map[string]interface{} {
"info": fee,
"maker": this.SafeNumber(fee, "maker_fee"),
"taker": this.SafeNumber(fee, "taker_fee"),
}
}
}
var parsedFees interface{} = map[string]interface{} {}
for i := 0; IsLessThan(i, GetArrayLength(this.Symbols)); i++ {
var symbol interface{} = GetValue(this.Symbols, i)
var market interface{} = this.Market(symbol)
var fee interface{} = map[string]interface{} {
"info": market,
"symbol": symbol,
"percentage": true,
"tierBased": true,
"maker": GetValue(market, "maker"),
"taker": GetValue(market, "taker"),
}
if IsTrue(GetValue(market, "swap")) {
fee = this.Extend(fee, perpetualFee)
} else if IsTrue(GetValue(market, "future")) {
fee = this.Extend(fee, futureFee)
} else if IsTrue(GetValue(market, "option")) {
fee = this.Extend(fee, optionFee)
}
AddElementToObject(parsedFees, symbol, fee)
}
ch <- parsedFees
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchOrderBook
* @description fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
* @see https://docs.deribit.com/#public-get_order_book
* @param {string} symbol unified symbol of the market to fetch the order book for
* @param {int} [limit] the maximum amount of order book entries to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/#/?id=order-book-structure} indexed by market symbols
*/
func (this *deribit) 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
retRes17528 := (<-this.LoadMarkets())
PanicOnError(retRes17528)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "depth", limit)
}
response:= (<-this.PublicGetGetOrderBook(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": {
// "timestamp": 1583781354740,
// "stats": { volume: 61249.66735634, low: 7631.5, high: 8311.5 },
// "state": "open",
// "settlement_price": 7903.21,
// "open_interest": 111536690,
// "min_price": 7695.13,
// "max_price": 7929.49,
// "mark_price": 7813.06,
// "last_price": 7814.5,
// "instrument_name": "BTC-PERPETUAL",
// "index_price": 7810.12,
// "funding_8h": 0.0000031,
// "current_funding": 0,
// "change_id": 17538025952,
// "bids": [
// [7814, 351820],
// [7813.5, 207490],
// [7813, 32160],
// ],
// "best_bid_price": 7814,
// "best_bid_amount": 351820,
// "best_ask_price": 7814.5,
// "best_ask_amount": 11880,
// "asks": [
// [7814.5, 11880],
// [7815, 18100],
// [7815.5, 2640],
// ],
// },
// "usIn": 1583781354745804,
// "usOut": 1583781354745932,
// "usDiff": 128,
// "testnet": false
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var timestamp interface{} = this.SafeInteger(result, "timestamp")
var nonce interface{} = this.SafeInteger(result, "change_id")
var orderbook interface{} = this.ParseOrderBook(result, GetValue(market, "symbol"), timestamp)
AddElementToObject(orderbook, "nonce", nonce)
ch <- orderbook
return nil
}()
return ch
}
func (this *deribit) ParseOrderStatus(status interface{}) interface{} {
var statuses interface{} = map[string]interface{} {
"open": "open",
"cancelled": "canceled",
"filled": "closed",
"rejected": "rejected",
"untriggered": "open",
}
return this.SafeString(statuses, status, status)
}
func (this *deribit) ParseTimeInForce(timeInForce interface{}) interface{} {
var timeInForces interface{} = map[string]interface{} {
"good_til_cancelled": "GTC",
"fill_or_kill": "FOK",
"immediate_or_cancel": "IOC",
}
return this.SafeString(timeInForces, timeInForce, timeInForce)
}
func (this *deribit) ParseOrderType(orderType interface{}) interface{} {
var orderTypes interface{} = map[string]interface{} {
"stop_limit": "limit",
"take_limit": "limit",
"stop_market": "market",
"take_market": "market",
}
return this.SafeString(orderTypes, orderType, orderType)
}
func (this *deribit) ParseOrder(order interface{}, optionalArgs ...interface{}) interface{} {
//
// createOrder
//
// {
// "time_in_force": "good_til_cancelled",
// "reduce_only": false,
// "profit_loss": 0,
// "price": "market_price",
// "post_only": false,
// "order_type": "market",
// "order_state": "filled",
// "order_id": "ETH-349249",
// "max_show": 40,
// "last_update_timestamp": 1550657341322,
// "label": "market0000234",
// "is_liquidation": false,
// "instrument_name": "ETH-PERPETUAL",
// "filled_amount": 40,
// "direction": "buy",
// "creation_timestamp": 1550657341322,
// "commission": 0.000139,
// "average_price": 143.81,
// "api": true,
// "amount": 40,
// "trades": [], // injected by createOrder
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var marketId interface{} = this.SafeString(order, "instrument_name")
market = this.SafeMarket(marketId, market)
var timestamp interface{} = this.SafeInteger(order, "creation_timestamp")
var lastUpdate interface{} = this.SafeInteger(order, "last_update_timestamp")
var id interface{} = this.SafeString(order, "order_id")
var priceString interface{} = this.SafeString(order, "price")
if IsTrue(IsEqual(priceString, "market_price")) {
priceString = nil
}
var averageString interface{} = this.SafeString(order, "average_price")
// Inverse contracts amount is in USD which in ccxt is the cost
// For options and Linear contracts amount is in corresponding cryptocurrency, e.g., BTC or ETH
var filledString interface{} = this.SafeString(order, "filled_amount")
var amount interface{} = this.SafeString(order, "amount")
var cost interface{} = Precise.StringMul(filledString, averageString)
if IsTrue(this.SafeBool(market, "inverse")) {
if IsTrue(!IsEqual(averageString, "0")) {
cost = Precise.StringDiv(amount, averageString)
}
}
var lastTradeTimestamp interface{} = nil
if IsTrue(!IsEqual(filledString, nil)) {
var isFilledPositive interface{} = Precise.StringGt(filledString, "0")
if IsTrue(isFilledPositive) {
lastTradeTimestamp = lastUpdate
}
}
var status interface{} = this.ParseOrderStatus(this.SafeString(order, "order_state"))
var side interface{} = this.SafeStringLower(order, "direction")
var feeCostString interface{} = this.SafeString(order, "commission")
var fee interface{} = nil
if IsTrue(!IsEqual(feeCostString, nil)) {
feeCostString = Precise.StringAbs(feeCostString)
fee = map[string]interface{} {
"cost": feeCostString,
"currency": GetValue(market, "base"),
}
}
var rawType interface{} = this.SafeString(order, "order_type")
var typeVar interface{} = this.ParseOrderType(rawType)
// injected in createOrder
var trades interface{} = this.SafeValue(order, "trades")
var timeInForce interface{} = this.ParseTimeInForce(this.SafeString(order, "time_in_force"))
var postOnly interface{} = this.SafeValue(order, "post_only")
return this.SafeOrder(map[string]interface{} {
"info": order,
"id": id,
"clientOrderId": nil,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"lastTradeTimestamp": lastTradeTimestamp,
"symbol": GetValue(market, "symbol"),
"type": typeVar,
"timeInForce": timeInForce,
"postOnly": postOnly,
"side": side,
"price": priceString,
"triggerPrice": this.SafeValue(order, "stop_price"),
"amount": amount,
"cost": cost,
"average": averageString,
"filled": filledString,
"remaining": nil,
"status": status,
"fee": fee,
"trades": trades,
}, market)
}
/**
* @method
* @name deribit#fetchOrder
* @description fetches information on an order made by the user
* @see https://docs.deribit.com/#private-get_order_state
* @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 *deribit) 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
retRes19468 := (<-this.LoadMarkets())
PanicOnError(retRes19468)
var request interface{} = map[string]interface{} {
"order_id": id,
}
var market interface{} = nil
if IsTrue(!IsEqual(symbol, nil)) {
market = this.Market(symbol)
}
response:= (<-this.PrivateGetGetOrderState(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "id": 4316,
// "result": {
// "time_in_force": "good_til_cancelled",
// "reduce_only": false,
// "profit_loss": 0.051134,
// "price": 118.94,
// "post_only": false,
// "order_type": "limit",
// "order_state": "filled",
// "order_id": "ETH-331562",
// "max_show": 37,
// "last_update_timestamp": 1550219810944,
// "label": "",
// "is_liquidation": false,
// "instrument_name": "ETH-PERPETUAL",
// "filled_amount": 37,
// "direction": "sell",
// "creation_timestamp": 1550219749176,
// "commission": 0.000031,
// "average_price": 118.94,
// "api": false,
// "amount": 37
// }
// }
//
var result interface{} = this.SafeDict(response, "result")
ch <- this.ParseOrder(result, market)
return nil
}()
return ch
}
/**
* @method
* @name deribit#createOrder
* @description create a trade order
* @see https://docs.deribit.com/#private-buy
* @see https://docs.deribit.com/#private-sell
* @param {string} symbol unified symbol of the market to create an order in
* @param {string} type 'market' or 'limit'
* @param {string} side 'buy' or 'sell'
* @param {float} amount how much you want to trade in units of the base currency. For perpetual and inverse futures the amount is in USD units. For options it is in the underlying assets base currency.
* @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.trigger] the trigger type 'index_price', 'mark_price', or 'last_price', default is 'last_price'
* @param {float} [params.trailingAmount] the quote amount to trail away from the current market price
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *deribit) 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
retRes20048 := (<-this.LoadMarkets())
PanicOnError(retRes20048)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
"amount": this.AmountToPrecision(symbol, amount),
"type": typeVar,
}
var trigger interface{} = this.SafeString(params, "trigger", "last_price")
var timeInForce interface{} = this.SafeStringUpper(params, "timeInForce")
var reduceOnly interface{} = this.SafeValue2(params, "reduceOnly", "reduce_only")
// only stop loss sell orders are allowed when price crossed from above
var stopLossPrice interface{} = this.SafeValue(params, "stopLossPrice")
// only take profit buy orders are allowed when price crossed from below
var takeProfitPrice interface{} = this.SafeValue(params, "takeProfitPrice")
var trailingAmount interface{} = this.SafeString2(params, "trailingAmount", "trigger_offset")
var isTrailingAmountOrder interface{} = !IsEqual(trailingAmount, nil)
var isStopLimit interface{} = IsEqual(typeVar, "stop_limit")
var isStopMarket interface{} = IsEqual(typeVar, "stop_market")
var isTakeLimit interface{} = IsEqual(typeVar, "take_limit")
var isTakeMarket interface{} = IsEqual(typeVar, "take_market")
var isStopLossOrder interface{} = IsTrue(IsTrue(isStopLimit) || IsTrue(isStopMarket)) || IsTrue((!IsEqual(stopLossPrice, nil)))
var isTakeProfitOrder interface{} = IsTrue(IsTrue(isTakeLimit) || IsTrue(isTakeMarket)) || IsTrue((!IsEqual(takeProfitPrice, nil)))
if IsTrue(IsTrue(isStopLossOrder) && IsTrue(isTakeProfitOrder)) {
panic(InvalidOrder(Add(this.Id, " createOrder () only allows one of stopLossPrice or takeProfitPrice to be specified")))
}
var isStopOrder interface{} = IsTrue(isStopLossOrder) || IsTrue(isTakeProfitOrder)
var isLimitOrder interface{} = IsTrue(IsTrue((IsEqual(typeVar, "limit"))) || IsTrue(isStopLimit)) || IsTrue(isTakeLimit)
var isMarketOrder interface{} = IsTrue(IsTrue((IsEqual(typeVar, "market"))) || IsTrue(isStopMarket)) || IsTrue(isTakeMarket)
var exchangeSpecificPostOnly interface{} = this.SafeValue(params, "post_only")
var postOnly interface{} = this.IsPostOnly(isMarketOrder, exchangeSpecificPostOnly, params)
if IsTrue(isLimitOrder) {
AddElementToObject(request, "type", "limit")
AddElementToObject(request, "price", this.PriceToPrecision(symbol, price))
} else {
AddElementToObject(request, "type", "market")
}
if IsTrue(isTrailingAmountOrder) {
AddElementToObject(request, "trigger", trigger)
AddElementToObject(request, "type", "trailing_stop")
AddElementToObject(request, "trigger_offset", this.ParseToNumeric(trailingAmount))
} else if IsTrue(isStopOrder) {
var triggerPrice interface{} = Ternary(IsTrue((!IsEqual(stopLossPrice, nil))), stopLossPrice, takeProfitPrice)
AddElementToObject(request, "trigger_price", this.PriceToPrecision(symbol, triggerPrice))
AddElementToObject(request, "trigger", trigger)
if IsTrue(isStopLossOrder) {
if IsTrue(isMarketOrder) {
// stop_market (sell only)
AddElementToObject(request, "type", "stop_market")
} else {
// stop_limit (sell only)
AddElementToObject(request, "type", "stop_limit")
}
} else {
if IsTrue(isMarketOrder) {
// take_market (buy only)
AddElementToObject(request, "type", "take_market")
} else {
// take_limit (buy only)
AddElementToObject(request, "type", "take_limit")
}
}
}
if IsTrue(reduceOnly) {
AddElementToObject(request, "reduce_only", true)
}
if IsTrue(postOnly) {
AddElementToObject(request, "post_only", true)
AddElementToObject(request, "reject_post_only", true)
}
if IsTrue(!IsEqual(timeInForce, nil)) {
if IsTrue(IsEqual(timeInForce, "GTC")) {
AddElementToObject(request, "time_in_force", "good_til_cancelled")
}
if IsTrue(IsEqual(timeInForce, "IOC")) {
AddElementToObject(request, "time_in_force", "immediate_or_cancel")
}
if IsTrue(IsEqual(timeInForce, "FOK")) {
AddElementToObject(request, "time_in_force", "fill_or_kill")
}
}
params = this.Omit(params, []interface{}{"timeInForce", "stopLossPrice", "takeProfitPrice", "postOnly", "reduceOnly", "trailingAmount"})
var response interface{} = nil
if IsTrue(IsEqual(this.Capitalize(side), "Buy")) {
response = (<-this.PrivateGetBuy(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.PrivateGetSell(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// "jsonrpc": "2.0",
// "id": 5275,
// "result": {
// "trades": [
// {
// "trade_seq": 14151,
// "trade_id": "ETH-37435",
// "timestamp": 1550657341322,
// "tick_direction": 2,
// "state": "closed",
// "self_trade": false,
// "price": 143.81,
// "order_type": "market",
// "order_id": "ETH-349249",
// "matching_id": null,
// "liquidity": "T",
// "label": "market0000234",
// "instrument_name": "ETH-PERPETUAL",
// "index_price": 143.73,
// "fee_currency": "ETH",
// "fee": 0.000139,
// "direction": "buy",
// "amount": 40
// }
// ],
// "order": {
// "time_in_force": "good_til_cancelled",
// "reduce_only": false,
// "profit_loss": 0,
// "price": "market_price",
// "post_only": false,
// "order_type": "market",
// "order_state": "filled",
// "order_id": "ETH-349249",
// "max_show": 40,
// "last_update_timestamp": 1550657341322,
// "label": "market0000234",
// "is_liquidation": false,
// "instrument_name": "ETH-PERPETUAL",
// "filled_amount": 40,
// "direction": "buy",
// "creation_timestamp": 1550657341322,
// "commission": 0.000139,
// "average_price": 143.81,
// "api": true,
// "amount": 40
// }
// }
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var order interface{} = this.SafeValue(result, "order")
var trades interface{} = this.SafeValue(result, "trades", []interface{}{})
AddElementToObject(order, "trades", trades)
ch <- this.ParseOrder(order, market)
return nil
}()
return ch
}
/**
* @method
* @name deribit#editOrder
* @description edit a trade order
* @see https://docs.deribit.com/#private-edit
* @param {string} id edit order id
* @param {string} [symbol] unified symbol of the market to edit an order in
* @param {string} [type] 'market' or 'limit'
* @param {string} [side] 'buy' or 'sell'
* @param {float} amount how much you want to trade in units of the base currency. For perpetual and inverse futures the amount is in USD units. For options it is in the underlying assets 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.trailingAmount] the quote amount to trail away from the current market price
* @returns {object} an [order structure]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *deribit) EditOrder(id interface{}, symbol interface{}, typeVar interface{}, side interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
amount := GetArg(optionalArgs, 0, nil)
_ = amount
price := GetArg(optionalArgs, 1, nil)
_ = price
params := GetArg(optionalArgs, 2, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(amount, nil)) {
panic(ArgumentsRequired(Add(this.Id, " editOrder() requires an amount argument")))
}
retRes21798 := (<-this.LoadMarkets())
PanicOnError(retRes21798)
var request interface{} = map[string]interface{} {
"order_id": id,
"amount": this.AmountToPrecision(symbol, amount),
}
if IsTrue(!IsEqual(price, nil)) {
AddElementToObject(request, "price", this.PriceToPrecision(symbol, price))
}
var trailingAmount interface{} = this.SafeString2(params, "trailingAmount", "trigger_offset")
var isTrailingAmountOrder interface{} = !IsEqual(trailingAmount, nil)
if IsTrue(isTrailingAmountOrder) {
AddElementToObject(request, "trigger_offset", this.ParseToNumeric(trailingAmount))
params = this.Omit(params, "trigger_offset")
}
response:= (<-this.PrivateGetEdit(this.Extend(request, params)))
PanicOnError(response)
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var order interface{} = this.SafeValue(result, "order")
var trades interface{} = this.SafeValue(result, "trades", []interface{}{})
AddElementToObject(order, "trades", trades)
ch <- this.ParseOrder(order)
return nil
}()
return ch
}
/**
* @method
* @name deribit#cancelOrder
* @description cancels an open order
* @see https://docs.deribit.com/#private-cancel
* @param {string} id order id
* @param {string} symbol not used by deribit cancelOrder ()
* @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 *deribit) 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
retRes22178 := (<-this.LoadMarkets())
PanicOnError(retRes22178)
var request interface{} = map[string]interface{} {
"order_id": id,
}
response:= (<-this.PrivateGetCancel(this.Extend(request, params)))
PanicOnError(response)
var result interface{} = this.SafeDict(response, "result", map[string]interface{} {})
ch <- this.ParseOrder(result)
return nil
}()
return ch
}
/**
* @method
* @name deribit#cancelAllOrders
* @description cancel all open orders
* @see https://docs.deribit.com/#private-cancel_all
* @see https://docs.deribit.com/#private-cancel_all_by_instrument
* @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 *deribit) 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
retRes22378 := (<-this.LoadMarkets())
PanicOnError(retRes22378)
var request interface{} = map[string]interface{} {}
var response interface{} = nil
if IsTrue(IsEqual(symbol, nil)) {
response = (<-this.PrivateGetCancelAll(this.Extend(request, params)))
PanicOnError(response)
} else {
var market interface{} = this.Market(symbol)
AddElementToObject(request, "instrument_name", GetValue(market, "id"))
response = (<-this.PrivateGetCancelAllByInstrument(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// jsonrpc: '2.0',
// result: '1',
// usIn: '1720508354127369',
// usOut: '1720508354133603',
// usDiff: '6234',
// testnet: true
// }
//
ch <- []interface{}{this.SafeOrder(map[string]interface{} {
"info": response,
})}
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchOpenOrders
* @description fetch all unfilled currently open orders
* @see https://docs.deribit.com/#private-get_open_orders_by_currency
* @see https://docs.deribit.com/#private-get_open_orders_by_instrument
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch open orders for
* @param {int} [limit] the maximum number of open orders structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *deribit) 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
retRes22778 := (<-this.LoadMarkets())
PanicOnError(retRes22778)
var request interface{} = map[string]interface{} {}
var market interface{} = nil
var response interface{} = nil
if IsTrue(IsEqual(symbol, nil)) {
var code interface{} = this.CodeFromOptions("fetchOpenOrders", params)
var currency interface{} = this.Currency(code)
AddElementToObject(request, "currency", GetValue(currency, "id"))
response = (<-this.PrivateGetGetOpenOrdersByCurrency(this.Extend(request, params)))
PanicOnError(response)
} else {
market = this.Market(symbol)
AddElementToObject(request, "instrument_name", GetValue(market, "id"))
response = (<-this.PrivateGetGetOpenOrdersByInstrument(this.Extend(request, params)))
PanicOnError(response)
}
var result interface{} = this.SafeList(response, "result", []interface{}{})
ch <- this.ParseOrders(result, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchClosedOrders
* @description fetches information on multiple closed orders made by the user
* @see https://docs.deribit.com/#private-get_order_history_by_currency
* @see https://docs.deribit.com/#private-get_order_history_by_instrument
* @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
* @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/#/?id=order-structure}
*/
func (this *deribit) 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
retRes23088 := (<-this.LoadMarkets())
PanicOnError(retRes23088)
var request interface{} = map[string]interface{} {}
var market interface{} = nil
var response interface{} = nil
if IsTrue(IsEqual(symbol, nil)) {
var code interface{} = this.CodeFromOptions("fetchClosedOrders", params)
var currency interface{} = this.Currency(code)
AddElementToObject(request, "currency", GetValue(currency, "id"))
response = (<-this.PrivateGetGetOrderHistoryByCurrency(this.Extend(request, params)))
PanicOnError(response)
} else {
market = this.Market(symbol)
AddElementToObject(request, "instrument_name", GetValue(market, "id"))
response = (<-this.PrivateGetGetOrderHistoryByInstrument(this.Extend(request, params)))
PanicOnError(response)
}
var result interface{} = this.SafeList(response, "result", []interface{}{})
ch <- this.ParseOrders(result, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchOrderTrades
* @description fetch all the trades made from a single order
* @see https://docs.deribit.com/#private-get_user_trades_by_order
* @param {string} id order id
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch trades for
* @param {int} [limit] the maximum number of trades to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure}
*/
func (this *deribit) FetchOrderTrades(id interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
retRes23398 := (<-this.LoadMarkets())
PanicOnError(retRes23398)
var request interface{} = map[string]interface{} {
"order_id": id,
}
response:= (<-this.PrivateGetGetUserTradesByOrder(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "id": 9367,
// "result": {
// "trades": [
// {
// "trade_seq": 3,
// "trade_id": "ETH-34066",
// "timestamp": 1550219814585,
// "tick_direction": 1,
// "state": "open",
// "self_trade": false,
// "reduce_only": false,
// "price": 0.04,
// "post_only": false,
// "order_type": "limit",
// "order_id": "ETH-334607",
// "matching_id": null,
// "liquidity": "M",
// "iv": 56.83,
// "instrument_name": "ETH-22FEB19-120-C",
// "index_price": 121.37,
// "fee_currency": "ETH",
// "fee": 0.0011,
// "direction": "buy",
// "amount": 11
// },
// ],
// "has_more": true
// }
// }
//
var result interface{} = this.SafeList(response, "result", []interface{}{})
ch <- this.ParseTrades(result, nil, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchMyTrades
* @description fetch all trades made by the user
* @see https://docs.deribit.com/#private-get_user_trades_by_currency
* @see https://docs.deribit.com/#private-get_user_trades_by_currency_and_time
* @see https://docs.deribit.com/#private-get_user_trades_by_instrument
* @see https://docs.deribit.com/#private-get_user_trades_by_instrument_and_time
* @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
* @returns {Trade[]} a list of [trade structures]{@link https://docs.ccxt.com/#/?id=trade-structure}
*/
func (this *deribit) 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
retRes23968 := (<-this.LoadMarkets())
PanicOnError(retRes23968)
var request interface{} = map[string]interface{} {
"include_old": true,
}
var market interface{} = nil
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "count", limit) // default 10
}
var response interface{} = nil
if IsTrue(IsEqual(symbol, nil)) {
var code interface{} = this.CodeFromOptions("fetchMyTrades", params)
var currency interface{} = this.Currency(code)
AddElementToObject(request, "currency", GetValue(currency, "id"))
if IsTrue(IsEqual(since, nil)) {
response = (<-this.PrivateGetGetUserTradesByCurrency(this.Extend(request, params)))
PanicOnError(response)
} else {
AddElementToObject(request, "start_timestamp", since)
response = (<-this.PrivateGetGetUserTradesByCurrencyAndTime(this.Extend(request, params)))
PanicOnError(response)
}
} else {
market = this.Market(symbol)
AddElementToObject(request, "instrument_name", GetValue(market, "id"))
if IsTrue(IsEqual(since, nil)) {
response = (<-this.PrivateGetGetUserTradesByInstrument(this.Extend(request, params)))
PanicOnError(response)
} else {
AddElementToObject(request, "start_timestamp", since)
response = (<-this.PrivateGetGetUserTradesByInstrumentAndTime(this.Extend(request, params)))
PanicOnError(response)
}
}
//
// {
// "jsonrpc": "2.0",
// "id": 9367,
// "result": {
// "trades": [
// {
// "trade_seq": 3,
// "trade_id": "ETH-34066",
// "timestamp": 1550219814585,
// "tick_direction": 1,
// "state": "open",
// "self_trade": false,
// "reduce_only": false,
// "price": 0.04,
// "post_only": false,
// "order_type": "limit",
// "order_id": "ETH-334607",
// "matching_id": null,
// "liquidity": "M",
// "iv": 56.83,
// "instrument_name": "ETH-22FEB19-120-C",
// "index_price": 121.37,
// "fee_currency": "ETH",
// "fee": 0.0011,
// "direction": "buy",
// "amount": 11
// },
// ],
// "has_more": true
// }
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var trades interface{} = this.SafeList(result, "trades", []interface{}{})
ch <- this.ParseTrades(trades, market, since, limit)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchDeposits
* @description fetch all deposits made to an account
* @see https://docs.deribit.com/#private-get_deposits
* @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 *deribit) 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
if IsTrue(IsEqual(code, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchDeposits() requires a currency code argument")))
}
retRes24788 := (<-this.LoadMarkets())
PanicOnError(retRes24788)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "count", limit)
}
response:= (<-this.PrivateGetGetDeposits(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "id": 5611,
// "result": {
// "count": 1,
// "data": [
// {
// "address": "2N35qDKDY22zmJq9eSyiAerMD4enJ1xx6ax",
// "amount": 5,
// "currency": "BTC",
// "received_timestamp": 1549295017670,
// "state": "completed",
// "transaction_id": "230669110fdaf0a0dbcdc079b6b8b43d5af29cc73683835b9bc6b3406c065fda",
// "updated_timestamp": 1549295130159
// }
// ]
// }
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var data interface{} = this.SafeList(result, "data", []interface{}{})
ch <- this.ParseTransactions(data, currency, since, limit, params)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchWithdrawals
* @description fetch all withdrawals made from an account
* @see https://docs.deribit.com/#private-get_withdrawals
* @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 *deribit) 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
if IsTrue(IsEqual(code, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchWithdrawals() requires a currency code argument")))
}
retRes25278 := (<-this.LoadMarkets())
PanicOnError(retRes25278)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "count", limit)
}
response:= (<-this.PrivateGetGetWithdrawals(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "id": 2745,
// "result": {
// "count": 1,
// "data": [
// {
// "address": "2NBqqD5GRJ8wHy1PYyCXTe9ke5226FhavBz",
// "amount": 0.5,
// "confirmed_timestamp": null,
// "created_timestamp": 1550571443070,
// "currency": "BTC",
// "fee": 0.0001,
// "id": 1,
// "priority": 0.15,
// "state": "unconfirmed",
// "transaction_id": null,
// "updated_timestamp": 1550571443070
// }
// ]
// }
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var data interface{} = this.SafeList(result, "data", []interface{}{})
ch <- this.ParseTransactions(data, currency, since, limit, params)
return nil
}()
return ch
}
func (this *deribit) ParseTransactionStatus(status interface{}) interface{} {
var statuses interface{} = map[string]interface{} {
"completed": "ok",
"unconfirmed": "pending",
}
return this.SafeString(statuses, status, status)
}
func (this *deribit) ParseTransaction(transaction interface{}, optionalArgs ...interface{}) interface{} {
//
// fetchWithdrawals
//
// {
// "address": "2NBqqD5GRJ8wHy1PYyCXTe9ke5226FhavBz",
// "amount": 0.5,
// "confirmed_timestamp": null,
// "created_timestamp": 1550571443070,
// "currency": "BTC",
// "fee": 0.0001,
// "id": 1,
// "priority": 0.15,
// "state": "unconfirmed",
// "transaction_id": null,
// "updated_timestamp": 1550571443070
// }
//
// fetchDeposits
//
// {
// "address": "2N35qDKDY22zmJq9eSyiAerMD4enJ1xx6ax",
// "amount": 5,
// "currency": "BTC",
// "received_timestamp": 1549295017670,
// "state": "completed",
// "transaction_id": "230669110fdaf0a0dbcdc079b6b8b43d5af29cc73683835b9bc6b3406c065fda",
// "updated_timestamp": 1549295130159
// }
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
var currencyId interface{} = this.SafeString(transaction, "currency")
var code interface{} = this.SafeCurrencyCode(currencyId, currency)
var timestamp interface{} = this.SafeInteger2(transaction, "created_timestamp", "received_timestamp")
var updated interface{} = this.SafeInteger(transaction, "updated_timestamp")
var status interface{} = this.ParseTransactionStatus(this.SafeString(transaction, "state"))
var address interface{} = this.SafeString(transaction, "address")
var feeCost interface{} = this.SafeNumber(transaction, "fee")
var typeVar interface{} = "deposit"
var fee interface{} = nil
if IsTrue(!IsEqual(feeCost, nil)) {
typeVar = "withdrawal"
fee = map[string]interface{} {
"cost": feeCost,
"currency": code,
}
}
return map[string]interface{} {
"info": transaction,
"id": this.SafeString(transaction, "id"),
"txid": this.SafeString(transaction, "transaction_id"),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"address": address,
"addressTo": address,
"addressFrom": nil,
"tag": nil,
"tagTo": nil,
"tagFrom": nil,
"type": typeVar,
"amount": this.SafeNumber(transaction, "amount"),
"currency": code,
"status": status,
"updated": updated,
"network": nil,
"internal": nil,
"comment": nil,
"fee": fee,
}
}
func (this *deribit) ParsePosition(position interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "jsonrpc": "2.0",
// "id": 404,
// "result": {
// "average_price": 0,
// "delta": 0,
// "direction": "buy",
// "estimated_liquidation_price": 0,
// "floating_profit_loss": 0,
// "index_price": 3555.86,
// "initial_margin": 0,
// "instrument_name": "BTC-PERPETUAL",
// "leverage": 100,
// "kind": "future",
// "maintenance_margin": 0,
// "mark_price": 3556.62,
// "open_orders_margin": 0.000165889,
// "realized_profit_loss": 0,
// "settlement_price": 3555.44,
// "size": 0,
// "size_currency": 0,
// "total_profit_loss": 0
// }
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var contract interface{} = this.SafeString(position, "instrument_name")
market = this.SafeMarket(contract, market)
var side interface{} = this.SafeString(position, "direction")
side = Ternary(IsTrue((IsEqual(side, "buy"))), "long", "short")
var unrealizedPnl interface{} = this.SafeString(position, "floating_profit_loss")
var initialMarginString interface{} = this.SafeString(position, "initial_margin")
var notionalString interface{} = this.SafeString(position, "size_currency")
var maintenanceMarginString interface{} = this.SafeString(position, "maintenance_margin")
var currentTime interface{} = this.Milliseconds()
return this.SafePosition(map[string]interface{} {
"info": position,
"id": nil,
"symbol": this.SafeString(market, "symbol"),
"timestamp": currentTime,
"datetime": this.Iso8601(currentTime),
"lastUpdateTimestamp": nil,
"initialMargin": this.ParseNumber(initialMarginString),
"initialMarginPercentage": this.ParseNumber(Precise.StringMul(Precise.StringDiv(initialMarginString, notionalString), "100")),
"maintenanceMargin": this.ParseNumber(maintenanceMarginString),
"maintenanceMarginPercentage": this.ParseNumber(Precise.StringMul(Precise.StringDiv(maintenanceMarginString, notionalString), "100")),
"entryPrice": this.SafeNumber(position, "average_price"),
"notional": this.ParseNumber(notionalString),
"leverage": this.SafeInteger(position, "leverage"),
"unrealizedPnl": this.ParseNumber(unrealizedPnl),
"contracts": nil,
"contractSize": this.SafeNumber(market, "contractSize"),
"marginRatio": nil,
"liquidationPrice": this.SafeNumber(position, "estimated_liquidation_price"),
"markPrice": this.SafeNumber(position, "mark_price"),
"lastPrice": nil,
"collateral": nil,
"marginMode": nil,
"side": side,
"percentage": nil,
"hedged": nil,
"stopLossPrice": nil,
"takeProfitPrice": nil,
})
}
/**
* @method
* @name deribit#fetchPosition
* @description fetch data on a single open contract trade position
* @see https://docs.deribit.com/#private-get_position
* @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 *deribit) 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
retRes27208 := (<-this.LoadMarkets())
PanicOnError(retRes27208)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
}
response:= (<-this.PrivateGetGetPosition(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "id": 404,
// "result": {
// "average_price": 0,
// "delta": 0,
// "direction": "buy",
// "estimated_liquidation_price": 0,
// "floating_profit_loss": 0,
// "index_price": 3555.86,
// "initial_margin": 0,
// "instrument_name": "BTC-PERPETUAL",
// "leverage": 100,
// "kind": "future",
// "maintenance_margin": 0,
// "mark_price": 3556.62,
// "open_orders_margin": 0.000165889,
// "realized_profit_loss": 0,
// "settlement_price": 3555.44,
// "size": 0,
// "size_currency": 0,
// "total_profit_loss": 0
// }
// }
//
var result interface{} = this.SafeDict(response, "result")
ch <- this.ParsePosition(result)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchPositions
* @description fetch all open positions
* @see https://docs.deribit.com/#private-get_positions
* @param {string[]|undefined} symbols list of unified market symbols
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.currency] currency code filter for positions
* @param {string} [params.kind] market type filter for positions 'future', 'option', 'spot', 'future_combo' or 'option_combo'
* @param {int} [params.subaccount_id] the user id for the subaccount
* @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/#/?id=position-structure}
*/
func (this *deribit) 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
retRes27698 := (<-this.LoadMarkets())
PanicOnError(retRes27698)
var code interface{} = this.SafeString(params, "currency")
var request interface{} = map[string]interface{} {}
if IsTrue(!IsEqual(code, nil)) {
params = this.Omit(params, "currency")
var currency interface{} = this.Currency(code)
AddElementToObject(request, "currency", GetValue(currency, "id"))
}
response:= (<-this.PrivateGetGetPositions(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "id": 2236,
// "result": [
// {
// "average_price": 7440.18,
// "delta": 0.006687487,
// "direction": "buy",
// "estimated_liquidation_price": 1.74,
// "floating_profit_loss": 0,
// "index_price": 7466.79,
// "initial_margin": 0.000197283,
// "instrument_name": "BTC-PERPETUAL",
// "kind": "future",
// "leverage": 34,
// "maintenance_margin": 0.000143783,
// "mark_price": 7476.65,
// "open_orders_margin": 0.000197288,
// "realized_funding": -1e-8,
// "realized_profit_loss": -9e-9,
// "settlement_price": 7476.65,
// "size": 50,
// "size_currency": 0.006687487,
// "total_profit_loss": 0.000032781
// },
// ]
// }
//
var result interface{} = this.SafeList(response, "result")
ch <- this.ParsePositions(result, symbols)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchVolatilityHistory
* @description fetch the historical volatility of an option market based on an underlying asset
* @see https://docs.deribit.com/#public-get_historical_volatility
* @param {string} code unified currency code
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [volatility history objects]{@link https://docs.ccxt.com/#/?id=volatility-structure}
*/
func (this *deribit) FetchVolatilityHistory(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
retRes28218 := (<-this.LoadMarkets())
PanicOnError(retRes28218)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
}
response:= (<-this.PublicGetGetHistoricalVolatility(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": [
// [1640142000000,63.828320460740585],
// [1640142000000,63.828320460740585],
// [1640145600000,64.03821964123213]
// ],
// "usIn": 1641515379467734,
// "usOut": 1641515379468095,
// "usDiff": 361,
// "testnet": false
// }
//
ch <- this.ParseVolatilityHistory(response)
return nil
}()
return ch
}
func (this *deribit) ParseVolatilityHistory(volatility interface{}) interface{} {
//
// {
// "jsonrpc": "2.0",
// "result": [
// [1640142000000,63.828320460740585],
// [1640142000000,63.828320460740585],
// [1640145600000,64.03821964123213]
// ],
// "usIn": 1641515379467734,
// "usOut": 1641515379468095,
// "usDiff": 361,
// "testnet": false
// }
//
var volatilityResult interface{} = this.SafeValue(volatility, "result", []interface{}{})
var result interface{} = []interface{}{}
for i := 0; IsLessThan(i, GetArrayLength(volatilityResult)); i++ {
var timestamp interface{} = this.SafeInteger(GetValue(volatilityResult, i), 0)
var volatilityObj interface{} = this.SafeNumber(GetValue(volatilityResult, i), 1)
AppendToArray(&result,map[string]interface{} {
"info": volatilityObj,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"volatility": volatilityObj,
})
}
return result
}
/**
* @method
* @name deribit#fetchTransfers
* @description fetch a history of internal transfers made on an account
* @see https://docs.deribit.com/#private-get_transfers
* @param {string} code unified currency code of the currency transferred
* @param {int} [since] the earliest time in ms to fetch transfers for
* @param {int} [limit] the maximum number of transfers structures to retrieve
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [transfer structures]{@link https://docs.ccxt.com/#/?id=transfer-structure}
*/
func (this *deribit) FetchTransfers(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
code := GetArg(optionalArgs, 0, nil)
_ = code
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(code, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchTransfers() requires a currency code argument")))
}
retRes28898 := (<-this.LoadMarkets())
PanicOnError(retRes28898)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "count", limit)
}
response:= (<-this.PrivateGetGetTransfers(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "id": 7606,
// "result": {
// "count": 2,
// "data": [
// {
// "amount": 0.2,
// "created_timestamp": 1550579457727,
// "currency": "BTC",
// "direction": "payment",
// "id": 2,
// "other_side": "2MzyQc5Tkik61kJbEpJV5D5H9VfWHZK9Sgy",
// "state": "prepared",
// "type": "user",
// "updated_timestamp": 1550579457727
// },
// {
// "amount": 0.3,
// "created_timestamp": 1550579255800,
// "currency": "BTC",
// "direction": "payment",
// "id": 1,
// "other_side": "new_user_1_1",
// "state": "confirmed",
// "type": "subaccount",
// "updated_timestamp": 1550579255800
// }
// ]
// }
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var transfers interface{} = this.SafeList(result, "data", []interface{}{})
ch <- this.ParseTransfers(transfers, currency, since, limit, params)
return nil
}()
return ch
}
/**
* @method
* @name deribit#transfer
* @description transfer currency internally between wallets on the same account
* @see https://docs.deribit.com/#private-submit_transfer_to_user
* @see https://docs.deribit.com/#private-submit_transfer_to_subaccount
* @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 *deribit) 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
retRes29508 := (<-this.LoadMarkets())
PanicOnError(retRes29508)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"amount": amount,
"currency": GetValue(currency, "id"),
"destination": toAccount,
}
var method interface{} = this.SafeString(params, "method")
params = this.Omit(params, "method")
if IsTrue(IsEqual(method, nil)) {
var transferOptions interface{} = this.SafeValue(this.Options, "transfer", map[string]interface{} {})
method = this.SafeString(transferOptions, "method", "privateGetSubmitTransferToSubaccount")
}
var response interface{} = nil
if IsTrue(IsEqual(method, "privateGetSubmitTransferToUser")) {
response = (<-this.PrivateGetSubmitTransferToUser(this.Extend(request, params)))
PanicOnError(response)
} else {
response = (<-this.PrivateGetSubmitTransferToSubaccount(this.Extend(request, params)))
PanicOnError(response)
}
//
// {
// "jsonrpc": "2.0",
// "id": 9421,
// "result": {
// "updated_timestamp": 1550232862350,
// "type": "user",
// "state": "prepared",
// "other_side": "0x4aa0753d798d668056920094d65321a8e8913e26",
// "id": 3,
// "direction": "payment",
// "currency": "ETH",
// "created_timestamp": 1550232862350,
// "amount": 13.456
// }
// }
//
var result interface{} = this.SafeDict(response, "result", map[string]interface{} {})
ch <- this.ParseTransfer(result, currency)
return nil
}()
return ch
}
func (this *deribit) ParseTransfer(transfer interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "updated_timestamp": 1550232862350,
// "type": "user",
// "state": "prepared",
// "other_side": "0x4aa0753d798d668056920094d65321a8e8913e26",
// "id": 3,
// "direction": "payment",
// "currency": "ETH",
// "created_timestamp": 1550232862350,
// "amount": 13.456
// }
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
var timestamp interface{} = this.SafeTimestamp(transfer, "created_timestamp")
var status interface{} = this.SafeString(transfer, "state")
var account interface{} = this.SafeString(transfer, "other_side")
var direction interface{} = this.SafeString(transfer, "direction")
var currencyId interface{} = this.SafeString(transfer, "currency")
return map[string]interface{} {
"info": transfer,
"id": this.SafeString(transfer, "id"),
"status": this.ParseTransferStatus(status),
"amount": this.SafeNumber(transfer, "amount"),
"currency": this.SafeCurrencyCode(currencyId, currency),
"fromAccount": Ternary(IsTrue(!IsEqual(direction, "payment")), account, nil),
"toAccount": Ternary(IsTrue(IsEqual(direction, "payment")), account, nil),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
}
}
func (this *deribit) ParseTransferStatus(status interface{}) interface{} {
var statuses interface{} = map[string]interface{} {
"prepared": "pending",
"confirmed": "ok",
"cancelled": "cancelled",
"waiting_for_admin": "pending",
}
return this.SafeString(statuses, status, status)
}
/**
* @method
* @name deribit#withdraw
* @description make a withdrawal
* @see https://docs.deribit.com/#private-withdraw
* @param {string} code unified currency code
* @param {float} amount the amount to withdraw
* @param {string} address the address to withdraw to
* @param {string} tag
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [transaction structure]{@link https://docs.ccxt.com/#/?id=transaction-structure}
*/
func (this *deribit) Withdraw(code interface{}, amount interface{}, address interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
tag := GetArg(optionalArgs, 0, nil)
_ = tag
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
tagparamsVariable := this.HandleWithdrawTagAndParams(tag, params);
tag = GetValue(tagparamsVariable,0);
params = GetValue(tagparamsVariable,1)
this.CheckAddress(address)
retRes30478 := (<-this.LoadMarkets())
PanicOnError(retRes30478)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
"address": address,
"amount": amount,
}
if IsTrue(!IsEqual(this.Twofa, nil)) {
AddElementToObject(request, "tfa", Totp(this.Twofa))
}
response:= (<-this.PrivateGetWithdraw(this.Extend(request, params)))
PanicOnError(response)
ch <- this.ParseTransaction(response, currency)
return nil
}()
return ch
}
func (this *deribit) ParseDepositWithdrawFee(fee interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "withdrawal_priorities": [],
// "withdrawal_fee": 0.01457324,
// "min_withdrawal_fee": 0.000001,
// "min_confirmations": 1,
// "fee_precision": 8,
// "currency_long": "Solana",
// "currency": "SOL",
// "coin_type": "SOL"
// }
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
return map[string]interface{} {
"info": fee,
"withdraw": map[string]interface{} {
"fee": this.SafeNumber(fee, "withdrawal_fee"),
"percentage": false,
},
"deposit": map[string]interface{} {
"fee": nil,
"percentage": nil,
},
"networks": map[string]interface{} {},
}
}
/**
* @method
* @name deribit#fetchDepositWithdrawFees
* @description fetch deposit and withdraw fees
* @see https://docs.deribit.com/#public-get_currencies
* @param {string[]|undefined} codes list of unified currency codes
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [fee structures]{@link https://docs.ccxt.com/#/?id=fee-structure}
*/
func (this *deribit) FetchDepositWithdrawFees(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
codes := GetArg(optionalArgs, 0, nil)
_ = codes
params := GetArg(optionalArgs, 1, map[string]interface{} {})
_ = params
retRes31008 := (<-this.LoadMarkets())
PanicOnError(retRes31008)
response:= (<-this.PublicGetGetCurrencies(params))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": [
// {
// "withdrawal_priorities": [],
// "withdrawal_fee": 0.01457324,
// "min_withdrawal_fee": 0.000001,
// "min_confirmations": 1,
// "fee_precision": 8,
// "currency_long": "Solana",
// "currency": "SOL",
// "coin_type": "SOL"
// },
// ...
// ],
// "usIn": 1688652701456124,
// "usOut": 1688652701456390,
// "usDiff": 266,
// "testnet": true
// }
//
var data interface{} = this.SafeList(response, "result", []interface{}{})
ch <- this.ParseDepositWithdrawFees(data, codes, "currency")
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchFundingRate
* @description fetch the current funding rate
* @see https://docs.deribit.com/#public-get_funding_rate_value
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.start_timestamp] fetch funding rate starting from this timestamp
* @param {int} [params.end_timestamp] fetch funding rate ending at this timestamp
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/#/?id=funding-rate-structure}
*/
func (this *deribit) 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
retRes31408 := (<-this.LoadMarkets())
PanicOnError(retRes31408)
var market interface{} = this.Market(symbol)
var time interface{} = this.Milliseconds()
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
"start_timestamp": Subtract(time, (Multiply(Multiply(Multiply(8, 60), 60), 1000))),
"end_timestamp": time,
}
response:= (<-this.PublicGetGetFundingRateValue(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc":"2.0",
// "result":"0",
// "usIn":"1691161645596519",
// "usOut":"1691161645597149",
// "usDiff":"630",
// "testnet":false
// }
//
ch <- this.ParseFundingRate(response, market)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchFundingRateHistory
* @description fetch the current funding rate
* @see https://docs.deribit.com/#public-get_funding_rate_history
* @param {string} symbol unified market symbol
* @param {int} [since] the earliest time in ms to fetch funding rate 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] fetch funding rate ending at this timestamp
* @param {boolean} [params.paginate] default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
* @returns {object} a [funding rate structure]{@link https://docs.ccxt.com/#/?id=funding-rate-structure}
*/
func (this *deribit) 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
retRes31768 := (<-this.LoadMarkets())
PanicOnError(retRes31768)
var market interface{} = this.Market(symbol)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchFundingRateHistory", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
var maxEntriesPerRequest interface{} = 744 // seems exchange returns max 744 items per request
var eachItemDuration interface{} = "1h"
if IsTrue(paginate) {
retRes318419 := (<-this.FetchPaginatedCallDeterministic("fetchFundingRateHistory", symbol, since, limit, eachItemDuration, this.Extend(params, map[string]interface{} {
"isDeribitPaginationCall": true,
}), maxEntriesPerRequest))
PanicOnError(retRes318419)
// fix for: https://github.com/ccxt/ccxt/issues/25040
ch <- retRes318419
return nil
}
var duration interface{} = Multiply(this.ParseTimeframe(eachItemDuration), 1000)
var time interface{} = this.Milliseconds()
var month interface{} = Multiply(Multiply(Multiply(Multiply(30, 24), 60), 60), 1000)
if IsTrue(IsEqual(since, nil)) {
since = Subtract(time, month)
} else {
time = Add(since, month)
}
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
"start_timestamp": Subtract(since, 1),
}
var until interface{} = this.SafeInteger2(params, "until", "end_timestamp")
if IsTrue(!IsEqual(until, nil)) {
params = this.Omit(params, []interface{}{"until"})
AddElementToObject(request, "end_timestamp", until)
} else {
AddElementToObject(request, "end_timestamp", time)
}
if IsTrue(InOp(params, "isDeribitPaginationCall")) {
params = this.Omit(params, "isDeribitPaginationCall")
var maxUntil interface{} = this.Sum(since, Multiply(limit, duration))
AddElementToObject(request, "end_timestamp", mathMin(GetValue(request, "end_timestamp"), maxUntil))
}
response:= (<-this.PublicGetGetFundingRateHistory(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "id": 7617,
// "result": [
// {
// "timestamp": 1569891600000,
// "index_price": 8222.87,
// "prev_index_price": 8305.72,
// "interest_8h": -0.00009234260068476106,
// "interest_1h": -4.739622041017375e-7
// }
// ]
// }
//
var rates interface{} = []interface{}{}
var result interface{} = this.SafeValue(response, "result", []interface{}{})
for i := 0; IsLessThan(i, GetArrayLength(result)); i++ {
var fr interface{} = GetValue(result, i)
var rate interface{} = this.ParseFundingRate(fr, market)
AppendToArray(&rates,rate)
}
ch <- this.FilterBySymbolSinceLimit(rates, symbol, since, limit)
return nil
}()
return ch
}
func (this *deribit) ParseFundingRate(contract interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "jsonrpc":"2.0",
// "result":"0",
// "usIn":"1691161645596519",
// "usOut":"1691161645597149",
// "usDiff":"630",
// "testnet":false
// }
// history
// {
// "timestamp": 1569891600000,
// "index_price": 8222.87,
// "prev_index_price": 8305.72,
// "interest_8h": -0.00009234260068476106,
// "interest_1h": -4.739622041017375e-7
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var timestamp interface{} = this.SafeInteger(contract, "timestamp")
var datetime interface{} = this.Iso8601(timestamp)
var result interface{} = this.SafeNumber2(contract, "result", "interest_8h")
return map[string]interface{} {
"info": contract,
"symbol": this.SafeSymbol(nil, market),
"markPrice": nil,
"indexPrice": this.SafeNumber(contract, "index_price"),
"interestRate": nil,
"estimatedSettlePrice": nil,
"timestamp": timestamp,
"datetime": datetime,
"fundingRate": result,
"fundingTimestamp": nil,
"fundingDatetime": nil,
"nextFundingRate": nil,
"nextFundingTimestamp": nil,
"nextFundingDatetime": nil,
"previousFundingRate": nil,
"previousFundingTimestamp": nil,
"previousFundingDatetime": nil,
"interval": "8h",
}
}
/**
* @method
* @name deribit#fetchLiquidations
* @description retrieves the public liquidations of a trading pair
* @see https://docs.deribit.com/#public-get_last_settlements_by_currency
* @param {string} symbol unified CCXT market symbol
* @param {int} [since] the earliest time in ms to fetch liquidations for
* @param {int} [limit] the maximum number of liquidation structures to retrieve
* @param {object} [params] exchange specific parameters for the deribit 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 {object} an array of [liquidation structures]{@link https://docs.ccxt.com/#/?id=liquidation-structure}
*/
func (this *deribit) FetchLiquidations(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
since := GetArg(optionalArgs, 0, nil)
_ = since
limit := GetArg(optionalArgs, 1, nil)
_ = limit
params := GetArg(optionalArgs, 2, map[string]interface{} {})
_ = params
retRes32938 := (<-this.LoadMarkets())
PanicOnError(retRes32938)
var paginate interface{} = false
paginateparamsVariable := this.HandleOptionAndParams(params, "fetchLiquidations", "paginate");
paginate = GetValue(paginateparamsVariable,0);
params = GetValue(paginateparamsVariable,1)
if IsTrue(paginate) {
retRes329719 := (<-this.FetchPaginatedCallCursor("fetchLiquidations", symbol, since, limit, params, "continuation", "continuation", nil))
PanicOnError(retRes329719)
ch <- retRes329719
return nil
}
var market interface{} = this.Market(symbol)
if IsTrue(GetValue(market, "spot")) {
panic(NotSupported(Add(Add(Add(this.Id, " fetchLiquidations() does not support "), GetValue(market, "type")), " markets")))
}
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
"type": "bankruptcy",
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "search_start_timestamp", since)
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "count", limit)
}
response:= (<-this.PublicGetGetLastSettlementsByInstrument(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": {
// "settlements": [
// {
// "type": "bankruptcy",
// "timestamp": 1696579200041,
// "funded": 10000.0,
// "session_bankrupcy": 10000.0
// "session_profit_loss": 112951.68715857354,
// "session_tax": 0.15,
// "session_tax_rate": 0.0015,
// "socialized": 0.001,
// },
// ],
// "continuation": "5dHzoGyD8Hs8KURoUhfgXgHpJTA5oyapoudSmNeAfEftqRbjNE6jNNUpo2oCu1khnZL9ao"
// },
// "usIn": 1696652052254890,
// "usOut": 1696652052255733,
// "usDiff": 843,
// "testnet": false
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var cursor interface{} = this.SafeString(result, "continuation")
var settlements interface{} = this.SafeValue(result, "settlements", []interface{}{})
var settlementsWithCursor interface{} = this.AddPaginationCursorToResult(cursor, settlements)
ch <- this.ParseLiquidations(settlementsWithCursor, market, since, limit)
return nil
}()
return ch
}
func (this *deribit) AddPaginationCursorToResult(cursor interface{}, data interface{}) interface{} {
if IsTrue(!IsEqual(cursor, nil)) {
var dataLength interface{} = GetArrayLength(data)
if IsTrue(IsGreaterThan(dataLength, 0)) {
var first interface{} = GetValue(data, 0)
var last interface{} = GetValue(data, Subtract(dataLength, 1))
AddElementToObject(first, "continuation", cursor)
AddElementToObject(last, "continuation", cursor)
AddElementToObject(data, 0, first)
AddElementToObject(data, Subtract(dataLength, 1), last)
}
}
return data
}
/**
* @method
* @name deribit#fetchMyLiquidations
* @description retrieves the users liquidated positions
* @see https://docs.deribit.com/#private-get_settlement_history_by_instrument
* @param {string} symbol unified CCXT market symbol
* @param {int} [since] the earliest time in ms to fetch liquidations for
* @param {int} [limit] the maximum number of liquidation structures to retrieve
* @param {object} [params] exchange specific parameters for the deribit api endpoint
* @returns {object} an array of [liquidation structures]{@link https://docs.ccxt.com/#/?id=liquidation-structure}
*/
func (this *deribit) FetchMyLiquidations(optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
symbol := GetArg(optionalArgs, 0, nil)
_ = symbol
since := GetArg(optionalArgs, 1, nil)
_ = since
limit := GetArg(optionalArgs, 2, nil)
_ = limit
params := GetArg(optionalArgs, 3, map[string]interface{} {})
_ = params
if IsTrue(IsEqual(symbol, nil)) {
panic(ArgumentsRequired(Add(this.Id, " fetchMyLiquidations() requires a symbol argument")))
}
retRes33758 := (<-this.LoadMarkets())
PanicOnError(retRes33758)
var market interface{} = this.Market(symbol)
if IsTrue(GetValue(market, "spot")) {
panic(NotSupported(Add(Add(Add(this.Id, " fetchMyLiquidations() does not support "), GetValue(market, "type")), " markets")))
}
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
"type": "bankruptcy",
}
if IsTrue(!IsEqual(since, nil)) {
AddElementToObject(request, "search_start_timestamp", since)
}
if IsTrue(!IsEqual(limit, nil)) {
AddElementToObject(request, "count", limit)
}
response:= (<-this.PrivateGetGetSettlementHistoryByInstrument(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": {
// "settlements": [
// {
// "type": "bankruptcy",
// "timestamp": 1696579200041,
// "funded": 10000.0,
// "session_bankrupcy": 10000.0
// "session_profit_loss": 112951.68715857354,
// "session_tax": 0.15,
// "session_tax_rate": 0.0015,
// "socialized": 0.001,
// },
// ],
// "continuation": "5dHzoGyD8Hs8KURoUhfgXgHpJTA5oyapoudSmNeAfEftqRbjNE6jNNUpo2oCu1khnZL9ao"
// },
// "usIn": 1696652052254890,
// "usOut": 1696652052255733,
// "usDiff": 843,
// "testnet": false
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
var settlements interface{} = this.SafeList(result, "settlements", []interface{}{})
ch <- this.ParseLiquidations(settlements, market, since, limit)
return nil
}()
return ch
}
func (this *deribit) ParseLiquidation(liquidation interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "type": "bankruptcy",
// "timestamp": 1696579200041,
// "funded": 1,
// "session_bankrupcy": 0.001,
// "session_profit_loss": 0.001,
// "session_tax": 0.0015,
// "session_tax_rate": 0.0015,
// "socialized": 0.001,
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var timestamp interface{} = this.SafeInteger(liquidation, "timestamp")
return this.SafeLiquidation(map[string]interface{} {
"info": liquidation,
"symbol": this.SafeSymbol(nil, market),
"contracts": nil,
"contractSize": this.SafeNumber(market, "contractSize"),
"price": nil,
"baseValue": this.SafeNumber(liquidation, "session_bankrupcy"),
"quoteValue": nil,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
})
}
/**
* @method
* @name deribit#fetchGreeks
* @description fetches an option contracts greeks, financial metrics used to measure the factors that affect the price of an options contract
* @see https://docs.deribit.com/#public-ticker
* @param {string} symbol unified symbol of the market to fetch greeks for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [greeks structure]{@link https://docs.ccxt.com/#/?id=greeks-structure}
*/
func (this *deribit) FetchGreeks(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes34578 := (<-this.LoadMarkets())
PanicOnError(retRes34578)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
}
response:= (<-this.PublicGetTicker(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": {
// "estimated_delivery_price": 36552.72,
// "best_bid_amount": 0.2,
// "best_ask_amount": 9.1,
// "interest_rate": 0.0,
// "best_bid_price": 0.214,
// "best_ask_price": 0.219,
// "open_interest": 368.8,
// "settlement_price": 0.22103022,
// "last_price": 0.215,
// "bid_iv": 60.51,
// "ask_iv": 61.88,
// "mark_iv": 61.27,
// "underlying_index": "BTC-27SEP24",
// "underlying_price": 38992.71,
// "min_price": 0.1515,
// "max_price": 0.326,
// "mark_price": 0.2168,
// "instrument_name": "BTC-27SEP24-40000-C",
// "index_price": 36552.72,
// "greeks": {
// "rho": 130.63998,
// "theta": -13.48784,
// "vega": 141.90146,
// "gamma": 0.00002,
// "delta": 0.59621
// },
// "stats": {
// "volume_usd": 100453.9,
// "volume": 12.0,
// "price_change": -2.2727,
// "low": 0.2065,
// "high": 0.238
// },
// "state": "open",
// "timestamp": 1699578548021
// },
// "usIn": 1699578548308414,
// "usOut": 1699578548308606,
// "usDiff": 192,
// "testnet": false
// }
//
var result interface{} = this.SafeValue(response, "result", map[string]interface{} {})
ch <- this.ParseGreeks(result, market)
return nil
}()
return ch
}
func (this *deribit) ParseGreeks(greeks interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "estimated_delivery_price": 36552.72,
// "best_bid_amount": 0.2,
// "best_ask_amount": 9.1,
// "interest_rate": 0.0,
// "best_bid_price": 0.214,
// "best_ask_price": 0.219,
// "open_interest": 368.8,
// "settlement_price": 0.22103022,
// "last_price": 0.215,
// "bid_iv": 60.51,
// "ask_iv": 61.88,
// "mark_iv": 61.27,
// "underlying_index": "BTC-27SEP24",
// "underlying_price": 38992.71,
// "min_price": 0.1515,
// "max_price": 0.326,
// "mark_price": 0.2168,
// "instrument_name": "BTC-27SEP24-40000-C",
// "index_price": 36552.72,
// "greeks": {
// "rho": 130.63998,
// "theta": -13.48784,
// "vega": 141.90146,
// "gamma": 0.00002,
// "delta": 0.59621
// },
// "stats": {
// "volume_usd": 100453.9,
// "volume": 12.0,
// "price_change": -2.2727,
// "low": 0.2065,
// "high": 0.238
// },
// "state": "open",
// "timestamp": 1699578548021
// }
//
market := GetArg(optionalArgs, 0, nil)
_ = market
var timestamp interface{} = this.SafeInteger(greeks, "timestamp")
var marketId interface{} = this.SafeString(greeks, "instrument_name")
var symbol interface{} = this.SafeSymbol(marketId, market)
var stats interface{} = this.SafeValue(greeks, "greeks", map[string]interface{} {})
return map[string]interface{} {
"symbol": symbol,
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"delta": this.SafeNumber(stats, "delta"),
"gamma": this.SafeNumber(stats, "gamma"),
"theta": this.SafeNumber(stats, "theta"),
"vega": this.SafeNumber(stats, "vega"),
"rho": this.SafeNumber(stats, "rho"),
"bidSize": this.SafeNumber(greeks, "best_bid_amount"),
"askSize": this.SafeNumber(greeks, "best_ask_amount"),
"bidImpliedVolatility": this.SafeNumber(greeks, "bid_iv"),
"askImpliedVolatility": this.SafeNumber(greeks, "ask_iv"),
"markImpliedVolatility": this.SafeNumber(greeks, "mark_iv"),
"bidPrice": this.SafeNumber(greeks, "best_bid_price"),
"askPrice": this.SafeNumber(greeks, "best_ask_price"),
"markPrice": this.SafeNumber(greeks, "mark_price"),
"lastPrice": this.SafeNumber(greeks, "last_price"),
"underlyingPrice": this.SafeNumber(greeks, "underlying_price"),
"info": greeks,
}
}
/**
* @method
* @name deribit#fetchOption
* @description fetches option data that is commonly found in an option chain
* @see https://docs.deribit.com/#public-get_book_summary_by_instrument
* @param {string} symbol unified market symbol
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [option chain structure]{@link https://docs.ccxt.com/#/?id=option-chain-structure}
*/
func (this *deribit) FetchOption(symbol interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes35908 := (<-this.LoadMarkets())
PanicOnError(retRes35908)
var market interface{} = this.Market(symbol)
var request interface{} = map[string]interface{} {
"instrument_name": GetValue(market, "id"),
}
response:= (<-this.PublicGetGetBookSummaryByInstrument(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": [
// {
// "mid_price": 0.04025,
// "volume_usd": 11045.12,
// "quote_currency": "BTC",
// "estimated_delivery_price": 65444.72,
// "creation_timestamp": 1711100949273,
// "base_currency": "BTC",
// "underlying_index": "BTC-27DEC24",
// "underlying_price": 73742.14,
// "volume": 4.0,
// "interest_rate": 0.0,
// "price_change": -6.9767,
// "open_interest": 274.2,
// "ask_price": 0.042,
// "bid_price": 0.0385,
// "instrument_name": "BTC-27DEC24-240000-C",
// "mark_price": 0.04007735,
// "last": 0.04,
// "low": 0.04,
// "high": 0.043
// }
// ],
// "usIn": 1711100949273223,
// "usOut": 1711100949273580,
// "usDiff": 357,
// "testnet": false
// }
//
var result interface{} = this.SafeList(response, "result", []interface{}{})
var chain interface{} = this.SafeDict(result, 0, map[string]interface{} {})
ch <- this.ParseOption(chain, nil, market)
return nil
}()
return ch
}
/**
* @method
* @name deribit#fetchOptionChain
* @description fetches data for an underlying asset that is commonly found in an option chain
* @see https://docs.deribit.com/#public-get_book_summary_by_currency
* @param {string} code base currency to fetch an option chain for
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a list of [option chain structures]{@link https://docs.ccxt.com/#/?id=option-chain-structure}
*/
func (this *deribit) FetchOptionChain(code interface{}, optionalArgs ...interface{}) <- chan interface{} {
ch := make(chan interface{})
go func() interface{} {
defer close(ch)
defer ReturnPanicError(ch)
params := GetArg(optionalArgs, 0, map[string]interface{} {})
_ = params
retRes36438 := (<-this.LoadMarkets())
PanicOnError(retRes36438)
var currency interface{} = this.Currency(code)
var request interface{} = map[string]interface{} {
"currency": GetValue(currency, "id"),
"kind": "option",
}
response:= (<-this.PublicGetGetBookSummaryByCurrency(this.Extend(request, params)))
PanicOnError(response)
//
// {
// "jsonrpc": "2.0",
// "result": [
// {
// "mid_price": 0.4075,
// "volume_usd": 2836.83,
// "quote_currency": "BTC",
// "estimated_delivery_price": 65479.26,
// "creation_timestamp": 1711101594477,
// "base_currency": "BTC",
// "underlying_index": "BTC-28JUN24",
// "underlying_price": 68827.27,
// "volume": 0.1,
// "interest_rate": 0.0,
// "price_change": 0.0,
// "open_interest": 364.1,
// "ask_price": 0.411,
// "bid_price": 0.404,
// "instrument_name": "BTC-28JUN24-42000-C",
// "mark_price": 0.40752052,
// "last": 0.423,
// "low": 0.423,
// "high": 0.423
// }
// ],
// "usIn": 1711101594456388,
// "usOut": 1711101594484065,
// "usDiff": 27677,
// "testnet": false
// }
//
var result interface{} = this.SafeList(response, "result", []interface{}{})
ch <- this.ParseOptionChain(result, "base_currency", "instrument_name")
return nil
}()
return ch
}
func (this *deribit) ParseOption(chain interface{}, optionalArgs ...interface{}) interface{} {
//
// {
// "mid_price": 0.04025,
// "volume_usd": 11045.12,
// "quote_currency": "BTC",
// "estimated_delivery_price": 65444.72,
// "creation_timestamp": 1711100949273,
// "base_currency": "BTC",
// "underlying_index": "BTC-27DEC24",
// "underlying_price": 73742.14,
// "volume": 4.0,
// "interest_rate": 0.0,
// "price_change": -6.9767,
// "open_interest": 274.2,
// "ask_price": 0.042,
// "bid_price": 0.0385,
// "instrument_name": "BTC-27DEC24-240000-C",
// "mark_price": 0.04007735,
// "last": 0.04,
// "low": 0.04,
// "high": 0.043
// }
//
currency := GetArg(optionalArgs, 0, nil)
_ = currency
market := GetArg(optionalArgs, 1, nil)
_ = market
var marketId interface{} = this.SafeString(chain, "instrument_name")
market = this.SafeMarket(marketId, market)
var currencyId interface{} = this.SafeString(chain, "base_currency")
var code interface{} = this.SafeCurrencyCode(currencyId, currency)
var timestamp interface{} = this.SafeInteger(chain, "timestamp")
return map[string]interface{} {
"info": chain,
"currency": code,
"symbol": GetValue(market, "symbol"),
"timestamp": timestamp,
"datetime": this.Iso8601(timestamp),
"impliedVolatility": nil,
"openInterest": this.SafeNumber(chain, "open_interest"),
"bidPrice": this.SafeNumber(chain, "bid_price"),
"askPrice": this.SafeNumber(chain, "ask_price"),
"midPrice": this.SafeNumber(chain, "mid_price"),
"markPrice": this.SafeNumber(chain, "mark_price"),
"lastPrice": this.SafeNumber(chain, "last"),
"underlyingPrice": this.SafeNumber(chain, "underlying_price"),
"change": nil,
"percentage": this.SafeNumber(chain, "price_change"),
"baseVolume": this.SafeNumber(chain, "volume"),
"quoteVolume": this.SafeNumber(chain, "volume_usd"),
}
}
func (this *deribit) Nonce() interface{} {
return this.Milliseconds()
}
func (this *deribit) Sign(path interface{}, optionalArgs ...interface{}) interface{} {
api := GetArg(optionalArgs, 0, "public")
_ = api
method := GetArg(optionalArgs, 1, "GET")
_ = method
params := GetArg(optionalArgs, 2, map[string]interface{} {})
_ = params
headers := GetArg(optionalArgs, 3, nil)
_ = headers
body := GetArg(optionalArgs, 4, nil)
_ = body
var request interface{} = Add(Add(Add(Add(Add(Add("/", "api/"), this.Version), "/"), api), "/"), path)
if IsTrue(IsEqual(api, "public")) {
if IsTrue(GetArrayLength(ObjectKeys(params))) {
request = Add(request, Add("?", this.Urlencode(params)))
}
}
if IsTrue(IsEqual(api, "private")) {
this.CheckRequiredCredentials()
var nonce interface{} = ToString(this.Nonce())
var timestamp interface{} = ToString(this.Milliseconds())
var requestBody interface{} = ""
if IsTrue(GetArrayLength(ObjectKeys(params))) {
request = Add(request, Add("?", this.Urlencode(params)))
}
var requestData interface{} = Add(Add(Add(Add(Add(method, "\n"), request), "\n"), requestBody), "\n") // eslint-disable-line quotes
var auth interface{} = Add(Add(Add(Add(timestamp, "\n"), nonce), "\n"), requestData) // eslint-disable-line quotes
var signature interface{} = this.Hmac(this.Encode(auth), this.Encode(this.Secret), sha256)
headers = map[string]interface{} {
"Authorization": Add(Add(Add(Add(Add(Add(Add(Add("deri-hmac-sha256 id=", this.ApiKey), ",ts="), timestamp), ",sig="), signature), ","), "nonce="), nonce),
}
}
var url interface{} = Add(GetValue(GetValue(this.Urls, "api"), "rest"), request)
return map[string]interface{} {
"url": url,
"method": method,
"body": body,
"headers": headers,
}
}
func (this *deribit) 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
}
//
// {
// "jsonrpc": "2.0",
// "error": {
// "message": "Invalid params",
// "data": { reason: "invalid currency", param: "currency" },
// "code": -32602
// },
// "testnet": false,
// "usIn": 1583763842150374,
// "usOut": 1583763842150410,
// "usDiff": 36
// }
//
var error interface{} = this.SafeValue(response, "error")
if IsTrue(!IsEqual(error, nil)) {
var errorCode interface{} = this.SafeString(error, "code")
var feedback interface{} = Add(Add(this.Id, " "), body)
this.ThrowExactlyMatchedException(this.Exceptions, errorCode, feedback)
panic(ExchangeError(feedback))
}
return nil
}
func (this *deribit) Init(userConfig map[string]interface{}) {
this.Exchange = Exchange{}
this.Exchange.InitParent(userConfig, this.Describe().(map[string]interface{}), this)
this.Exchange.DerivedExchange = this
}